Find out if the number is a prime number or not

Background:
  1. Prime number should not be divisible by 2. If n%2 is 0 then it is not a prime number.
  2. Moreover, a prime number is only divisible by itself and 1. Hence to find out a prime number we will iterate through a loop from 2 to n-1.
  3. At any point if n%i is 0 then it is not a prime number. If we reach end of loop and if the number is not divisible by anything till n then it is a prime number.
  4. The reason why we are starting the loop at 2 is because 2 is also a prime number. 

Implementation:
 
bool isPrime(int n)
{
 int count = 0;
 bool flag = false;
 
 if( n ==2 ) {
  count = 0;
 }
  
 for(int i=2;i < n;i++)
 {
  if(((n % i) == 0) && (n!=i))
  {
   print("Not Prime");
   break;
  }
  else
   count = 0;
 }
  if(count == 0)
  {
   print("Prime");
   flag = true;
  }  
 return flag;
}


Complexity:
O(n)

Explain bitset in C++

Bitset class of c++. 
It will has methods that will perform operations on the bits of the numbers. 
Following code has different operations along with its explanation in the comments section. 

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

using namespace std;



int main()
{
 bitset<8> b; //MSB...LSB
 cin>>b;

        //This will return true if all the bits are set true
 int i = b.all();

        //This will return true if any of the bit is set to true
 i = b.any(); 

        //This will return true if the bit at position 1 is set to true
 i = b.at(1); 

        //This will return the count of the bits that are set
 i = b.count(); 

        //It will flip the bit specified at the position 1
 b.flip(4); 

        //It will return 1 will none of the bits are set. O/w zero
 i = b.none(); 

        //It will reset(set to zero) the specified bit
 b.reset(1); 

        //It will set(to one) the specified bit
 b.set(2); 

        //It will return the no. of bits specified in the bit vector
 i = b.size(); 

        //It will return 0 or 1. Whatever, is the value of the bit
 i = b.test(2); 


 return 0;
}
More Concepts: C++ Cheat Sheet

Java Concepts

Substring:
Substring function of string has 2 versions:

  1. BeginIndex
  2. BeginIndex, endIndex++


String is immutable &amp; calling substring creates a new string in the memory


If beginIndex is the length of the string then it will return emptyString and not IndexOutOfBoundException


IndexOutOfBound Exception only occurs when BeginIndex is -ve OR greater than startIndex OR greater than string length


Internal implementation
constructor(offset, count, value[]); //value is the original string


II) Contract between equals &amp; hashCode
If 2 objects are equal then their hashCode should be equal.
If 2 objects are not equal than their hashCode can or cannot be equal






String:
Why String is immutable
Strings are created in a string pool. If anyone of them changes then it will change all others that are referring that string.
String s1 = "Test";
String s2 = "Test";


If we change any of the string then the change will be reflected in other. Now "Test" is created once in the pool and different variables point to it.


Usage & Security

  1. DB Connections, Files, etc are created as Strings. If they are allowed to be mutable then DB connection or files will be overwritten.
  2. Class load is immutable. If it can be changed then it will be easy to load any other class.


Will its hashCode be same?
Yes it will be same since the strings are immutable


Advantage:
Helps in thread safety.





What char array is better than string for storing password in java?

  1. Strings are immutable so if we encrypt/change it, it will create a new string.
  2. This way old string will still be placed in same memory location.
  3. It will be available till it is Garbage Collected or else it will be available for a long time in the pool.
  4. Also strings might appear easily in the logs with character array. Also their location can be easily identified.






Why Java doesn’t support multiple inheritance?
To have a cleaner design, less ambiguity, no need of typecasting, and no confusion in which constructor to call.






What is Error in Java?
If an application throws some error and it can’t be recovered and it can’t be caught. It is called as an Error.






What is an Exception?

  1. It is different from an error in the sense that it can be caught.
  2. It can be of 2 types: Checked and Unchecked.
  3. Checked exception includes: FileNotFound, ParseException.
  4. Unchecked exception includes: NullPointer, ArrayOutOfBounds.
try {
.
.
}
catch(Exception e)
{
}


OR
public void doSomething() throws Exception.






What is difference between hash map and hash table?
Hashtable is synchronized and hash map is not.
If you want to use synchronized hash map then use concurrenthashmap.






Java Interfaces:
It can be divided into 3 types:

  1. Set
  2. Map
  3. List


Set:

  1. It cannot contain duplicates.
  2. Inherit the properties of the collection.
  3. 3 types include: HashSet, LinkedHashSet, TreeSet
  4. HashSet has hash table implementation,
  5. treeset has red-black tree implementation
  6. Linked hashset: Linked list in value of the hashtable.
  7. It common functions include: size(), isEmpty(), add(Object), remove(Object), contains(Object), addAll, removeAll, Clear


List:

  1. It is inherit from collection
  2. It can contain duplicates.
  3. Provides positional access to the elements.
  4. Common Access functions include: get(i), add(i), add(i,e), contains(i), remove(i)
  5. Common Search functions include: indexOf(0), lastIndex(0)
  6. Its 2 types include: ArrayList(lookup is easy), LinkedList(Addition and deletion are easy)


Map:

  1. Cannot contain duplicates.
  2. It is implemented as key-value pairs.
  3. Basic operations: put(key, value), get(key), containsKey(object), containsValue(Object), size(), isEmpty(), clear()
  4. 3 types include: LinkedMap, HashMap, TreeMap(Balanced Tree implementation).


TreeMap:

  1. Key value pairs are stored in the tree form. Keys are stored in the sorted form. It is useful to find the elements in ascending order or to find the max element, sorting will be easier, finding parent is easier.
  2. Lookup will be O(logn), and insertion will be O(logn)
  3. TreeSet: There are only values. All the elements are stored in the sorted form on the values. It is basically tree data structure.


LinkedHashMap:

  1. The order of insertion is maintained. Lookup: O(n), insertion: O(1), Deletion O(n)
  2. LinkedHashSet: A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
  3. Use this class instead of HashSet when you care about the iteration order.
    1. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.






Java advantages:

  1. Portability: Only one version of the code is useful on all the environments and platforms
  2. Class library: Java class library is available on any machine with a Java runtime system.         
  3. Byte Code: Doesn’t compile the source code to the machine code. It compiles it to the byte code. JRE interprets the machine code and executes it.
    1. Hence we need Java compiler to convert it to the Byte code.
    2. We need the JRE to convert the byte code to the m/c level.
  4. Security:
    1. No pointer arithmetic
    2. No array out of bounds – Array bounds checking.
    3. Garbage collection
    4. No illegal data conversion
    5. No jumping to bad address since the pointer arithmetic is absent.
    6. Interfaces and exceptions
    7. The byte code is placed in a separate file where the JRE could find it.
    8. If the program instantiate the object of a class, the class loader searches the CLASSPATH environment for the *.class file. The class file will contain the byte code and class definition for the file A.
    9. All linking is done dynamically.
  5. JRE will first search for the .class and then the public static void main method.
  6. Document comment:
    1. /** Doc comment */ : These comments are processed by the javadoc program  to generate the documentation of the source code.






Allocation:

  1. Nothing is allocated on stack. All java objects are allocated on heap.
  2. Because of garbage collection, storing of the object doesn’t cause the memory leakage issues.






Strings:

  1. Strings are pointers to the memory. They are objects. Could or couldn’t be null terminated.
  2. Constant in length.
  3. For variable length, use the StringBuffer
  4. Operators +, .length
  5. Int to a string : String.valueOf(4)
  6. String to an int Integer.parseInt(“5”);






Array:

  1. Objects that know the number and type of the elements.
  2. To allocate the array use the new operator.
  3. Array allocation will not allocate any memory and will not do any assignment.
  4. Creating multi-dimensional array: T[][]t = new T[10][5]
  5. ArrayIndexOutOfBoundsException: Runtime exception while accessing an undefined array element.
  6. NullPointerException: Assessing an array element that has not been assigned to an object






Other data:

  1. Constant in java: Static final int I;
  2. Break and continue statement might have a label.
  3. Objects are passed by reference and not value.
  4. Primitive types are passed by value
  5. Shallow comparision: if(a==b)
  6. Deep comparision(a.equals(b))
  7. S->method: dereference in C++. S.method(). Dereference automatically.
  8. Garbage collector de-allocated memory that is not in use anymore. Hence, the java object is either null or valid. There is no other state(invalid or stale)
  9. However the memory de-allocation doesn’t happen all the time. It happens at a scheduled time.
  10. Primitive data types: Boolean, int, byte, char, short, long, float, double.

You might also like:
Java String concepts
Immutable classes in Java
Remove duplicates from the array
Telephonic phone technical interview questions
Telephonic phone technical interview questions - Part 2
Serialization & Deserialization
Jersey Package Dependencies
Observable and Observer Interface
Servlet Filter
Servlet Client Request
Spring dependencies for Maven
Java String Operations

String class of Java

Java has string class and it has a lot of functions. However, it is common for interviewers to ask about implementation of different string functions. But if you want to know the available functions with the string class then you can go through this documentation. It lists the method and function that it will perform.
  1. String S = new String("This is a new is language");
  2. S.charAt(0); //Finds the character as location 0
  3. S.compareTo(S1); //It will compare the strings S and S1
  4. S.concat(S); //It will concat the string S to itself.
  5. If S = "xyz", then concat will result into xyzxyz
  6. S.contains("new"); //It will find out if the string S contains substring "new"
  7. S.contentEquals("This is new"); //It will find out if String S is equal to the inputted string.
  8. S.endsWith("uage"); //It will find out if the String S ends with 'uage'
  9. S.equals(S); //Will compare 2 strings.
  10. S.getClass().getName();
  11. S.hashCode(); //It will compute the hashcode of the string
  12. S.indexOf('T'); //It will find the index of character 'T'
  13. S.indexOf("This"); //It will find the index of String "this"
  14. S.indexOf("s", 4); //It will find location of character s from location 4.
  15. S.indexOf("is", 10); //It will find location of string 'is' starting from location 10.
  16. S.isEmpty(); //It find out if the string is empty or not
  17. S.lastIndexOf(s); //Will find the location of character s starting from end of string.
  18. S.lastIndexOf("is"); //Will find the location of string 'is' starting from end of string.
  19. S.lastIndexOf(s, 10);
  20. S.lastIndexOf("is",10);
  21. S.length(); //Find the length of the string
  22. S.replace(s, e); //It will replace character s with e in the string
  23. S.replace("new", "old"); //It will replace occurence of string new to old.
  24. S.replaceAll("is", "was"); //Will replace all
  25. S.replaceFirst("is", "was"); //Will only replace First occurence of string 'is'
  26. S.substring(10); //Find a substring from character 10
  27. S.substring(10, 16); //Find a substring from character 10 to 16
  28. S.toLowerCase(); //Converts all characters to lowercase
  29. S.toUpperCase(); //Converts all characters to uppercase
  30. S.trim(); //Trims the leading and trailing whitespaces;
  31. S.copyValueOf(c); //Creates a copy of string
  32. S.copyValueOf(c, 0, 5); //Creates a copy of string from character 0 to 5
How to convert a string to a character array:
  1. char[] c = new char[20];
  2. c = S.toCharArray(); //Converts a string to a character array
How to get character from specific locations in the character array
  1. char[] destChar = new char[10]; S.getChars(0, 10, destChar, 0); //It will get characters from location 0 to 10 into destination character array


Find a character in the string


This algorithm will find out a character in the string. If string is ‘Programming’, and if you want to find the character r. Then this algorithm will if the character r exists in the string. If you want to find out character ‘z’ then it will return ‘String not found’ since it is not present in the inputted string.

Algorithm:

  1. Find the length of the string and store it in len variable.
  2. Create a count variable, and initialize to 0.
  3. Compare character at each location start from count=0.
  4. Increment the count till len and keep comparing its character to inputted character.
  5. If character matches then break the loop.
  6. Else repeat statement 4.


 
int main ()
{
  char c;
  char s[] = "Programming";
  char *p;

  c = '9';
  p = s;

  int count, len = strlen (s);
  count = 0;

  while (count != len)
    {
      if (c == s[count])
 {
   std::cout << count << std::endl;
   break;
 }
      else
 count++;
    }

  if (count == len)
    {
      std::cout << "Character not found" << std::endl;
    }

  std::cin >> c;

  return 0;
}

Algorithm run:
Step 1: Declare a character array ‘s’ and initialize it with the given string value “Programming”. char s[ ] = “programming”;  
  0     1 2     3 4 5       6 7 8 9     10
‘p’
‘r’
‘o’
‘g’
‘r’
‘a’
‘m’
‘m’
‘i’
‘n’
‘g’
Step 2 : Declare a character variable ‘c’ and initialize it with the individual character to be searched for. char c = ‘g’
Step 3: Declare and initialize a count variable with the value 0(zero). int count = 0 Step 4: Find the length of the given string using strlen() method and assign the length value to the ‘len’ integer variable. strlen(s) = 11 int len = 11; Step 5: Using while loop, iterate through the character array to find whether the given individual character is present or not. If the character is matched, then print the count value otherwise increment the count value. Iteration 1: count = 0, len = 11 0 != 11 -> Condition true
  0     1 2      3 4 5      6 7 8 9      10
‘p’
‘r’
‘o’
‘g’
‘r’
‘a’
‘m’
‘m’
‘i’
‘n’
‘g’
IF : c = ‘g’, s[0] = ‘p’
‘g’ == ‘p’   -> Condition false
ELSE : 
count = 1 (incremented by one)
Iteration 2:
count = 1, len = 11
1 != 11   -> Condition true
  0     1 2      3 4 5      6 7 8 9      10
‘p’
‘r’
‘o’
‘g’
‘r’
‘a’
‘m’
‘m’
‘i’
‘n’
‘g’
IF : c = ‘g’, s[1] = ‘r’
‘g’ == ‘r’   -> Condition false
ELSE : 
count = 2 (incremented by one)
Iteration 3:
count = 2, len = 11
2 != 11   -> Condition true
  0     1 2      3 4 5      6 7 8 9      10
‘p’
‘r’
‘o’
‘g’
‘r’
‘a’
‘m’
‘m’
‘i’
‘n’
‘g’
IF : c = ‘g’, s[2] = ‘o’
‘g’ == ‘o’   -> Condition false
ELSE : 
count = 3 (incremented by one)
Iteration 4:
count = 3, len = 11
3 != 11   -> Condition true
  0     1 2      3 4 5      6 7 8 9      10
‘p’
‘r’
‘o’
‘g’
‘r’
‘a’
‘m’
‘m’
‘i’
‘n’
‘g’
IF : c = ‘g’, s[3] = ‘g’
‘g’ == ‘g’   -> Condition true
Then,
Print the count value to console 3.
Enters the break statement, So terminate the loop.
Step 6: If the count reaches the end of string then print “Character not found” otherwise print “Character found”. Count = 3, len = 11 IF: 3 == 11 -> Condition false ELSE: Print “Character found” to the console.
Output :
Character found at Location: 3

Algorithm Complexity :
O(n)

















NoSQL

This one is reviewed but I need to delete its copy from hubpages or somewhere NoSQL Data models: key-value  Aggregate model.  key or i...