Saturday, March 14, 2015

String, StringBuilder, StringBuffer

Difference between String and StringBuffer/StringBuilder

  • String is immutable objects means once created it cannot be changed, reference will point to new object.
  • If our application has string manipulation activity, then there will be many discarded string object in heap memory which might result in performance impact.
  • StringBuffer/StringBuilder is mutable
  • StringBuffer/StringBuilder can have characters/strings may be inserted in between or appended at end for which the StringBuffer/StringBuilder automatically grow


Difference between StringBuffer & StringBuilder

  • Methods in StringBuilder are not synchronized hence better performance over StringBuffer
  • Methods in StringBuilder are not synchronized hence it is not thread safe
Examples with basic methods
String

public class StringDemo {
public static void main (String[] args)
{
// Following are 2 ways to instantiate String object
String s=new String("ABCDMNOP");
String s1="PqRS";
Date e=new Date();
System.out.println("Current time: " + new Timestamp(e.getTime()));
System.out.println(s); // Print ABCDMNOP
System.out.println(s1); // Print PqRS
System.out.println(s.length());
System.out.println(s.toLowerCase());
System.out.println(s.charAt(1));
System.out.println(s1.charAt(3));
//System.out.println(s1.charAt(4)); // Throws IndexOutOfBoundsException since length of s1 is 4
System.out.println(s.substring(1)); // Return the substring starting from index 1
System.out.println(s.substring(1,4)); /* Return the substring starting from index 1 
upto (endIndex-1) index i.e. BCD*/
System.out.println(s.subSequence(1, 4)); /* works similar to substring except the difference  that return type of this method is CharSequence while return type for substring is String */
}
}
StringBuffer
public class StringBufferDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub
String s=new String("ABCDMNOP");
StringBuffer sb=new StringBuffer(s); /* StringBuffer works same as StringBuilder with a difference that methods in StringBuffer are synchronized while methods in StringBuilder are non-synchronized hence StringBuilder is not thread safe so better performance */ 
System.out.println(sb);
System.out.println(sb.deleteCharAt(2));
System.out.println(sb.delete(4, 6)); /* delete the substring starting from startIndex  upto (endIndex-1) index i.e. NO  */
System.out.println(sb.replace(1, 3, "XYZQ")); /* replace the substring starting from index 1 upto (endIndex-1) index with the specified string pattern i.e. BD with "XYZQ"  */
System.out.println(sb.reverse());
System.out.println(sb);//Original String is also changed with the last operation
System.out.println(sb.charAt(3));
System.out.println(sb.substring(4, 7)); /* Return the substring starting from index 1 upto (endIndex-1) index i.e. YXA*/
System.out.println(sb.insert(2, 'x'));/* Insert the specified character on given index i.e. x on index 2 */
System.out.println(sb.insert(3, true)); /* Insert the specified boolean on given index i.e. x on index 3 */
System.out.println(sb.insert(3, "Test")); /* Insert the specified string on given index i.e. x on index 3 */

}

}

StringBuilder
public class StringBuilderDemo {

public static void main(String[] args) {
// TODO Auto-generated method stub

String s=new String("ABCDMNOP");
StringBuilder sb=new StringBuilder(s);
System.out.println(sb);
System.out.println(sb.deleteCharAt(2));
System.out.println(sb.delete(4, 6)); /* delete the substring starting from startIndex  upto (endIndex-1) index i.e. NO  */
System.out.println(sb.replace(1, 3, "XYZQ")); /* replace the substring starting from index 1 upto (endIndex-1) index with the specified string pattern i.e. BD with "XYZQ"  */
System.out.println(sb.reverse());
System.out.println(sb);//Original String is also changed with the last operation
System.out.println(sb.charAt(3));
System.out.println(sb.substring(4, 7)); /* Return the substring starting from index 1 upto (endIndex-1) index i.e. YXA*/
System.out.println(sb.insert(2, 'x'));/* Insert the specified character on given index i.e. x on index 2 */
System.out.println(sb.insert(3, true)); /* Insert the specified boolean on given index i.e. x on index 3 */
System.out.println(sb.insert(3, "Test")); /* Insert the specified string on given index i.e. x on index 3 */
}

}




Thursday, March 12, 2015

Test Strategy Vs Test Plan

Test Strategy

  • Set of guide lines which describes test design for the project
  • Can be either on organization level prepared by QA Manager/Director OR on project level prepared by QA Manger/Lead
  • Pre-requisite for this document is Business Requirement Document (BRD)
  • Often a static document i.e. not much changes happen in this document during the project life cycle
  • Contain generic information about what should be covered/used as testing. Few key points can be (Not limited to)- 
    • Business scope & objective
    • QA Best Practices 
    • Test Automation tools (Used at organization level OR Proposed for the project)
    • Defect Management tools (Used at organization level OR Proposed for the project)
    • Change & configuration management tool (Used at organization level OR Proposed for the project)
    • Test Deliverables
    • Test status communication 
    • Test metrics reporting
    • Training requirements

Test Plan

  • Details out test methodology for a particular project release or phase 
  • Prepared by QA Manager or QA Lead
  • Pre-requisite for a Test plan is Business Requirement Document (FRD) Or Software requirement specification (SRS)
  • Mostly a dynamic document where changes can happen during release cycle and all these changes are tracked in a different version e.g. There can be certain features which can be discovered as out of scope in the current release due to ANY reason. Such features should be scoped out from QA perspective as well in the Test plan
  • Can contain following information (Not limited to)
    • Feature/Release introduction
    • Features in scope 
    • Features not is scope 
    • Entry/Exit/Resumption Criteria
    • Testing in/out scope, can be a combination of functional / non- functional testing 
      • Functional Testing
        • Unit
        • Integration 
        • System
        • UAT
        • DB Testing
      • Non-functional Testing
        • Performance
        • Load
        • Stress
    • Schedule & responsibilities
    • Test tools (Used in the particular release based on the consent with client or group)
      • Automation tools
      • Defect Management tool
      • Change & configuration management tool
    • Test data strategy
    • Test Scenarios/ Test Case
    • Test Environments
    • Test Deliverables
      • Test Plan
      • Test Cases
      • Test Results
      • Test Status/Report (Daily/Weekly)
      • User document
      • Test Sign-off report
    • Risks & contingencies
    • Test plan Approvals

Saturday, March 7, 2015

Algorithm Complexity Analysis

What it is?
Big O notation and Algorithm complexity analysis is a way to formally measure that how  fast a program or an algo runs

Complexity analysis also helps to identify how fast an algo will run for the given input or how the algo behaves if the input grows larger
How to do that?
There are tools available, known as profilers which determine the run time of an algo in milliseconds and help us to optimize the code by identify bottlenecks

Asymptotic Behaviour
Out of an algo's complexity dropping the all the other factors and keeping only the largest growing term is known as asymptotic behavior

following examples shows asymptotic behavior of  dropping the constant terms and keeping only the one which grows fastest

  1. f( n ) = 5n + 12 gives f( n ) = n.

  2. f( n ) = 109 gives f( n ) = 1.
    We're dropping the multiplier 109 * 1, but we still have to put a 1 here to indicate that this function has a non-zero value.
  3. f( n ) = n2 + 3n + 112 gives f( n ) = n2
    Here, n2 grows larger than 3n for sufficiently large n, so we're keeping that.
  4. f( n ) = n3 + 1999n + 1337 gives f( n ) = n
  5. f( n ) = n + sqrt( n ) gives f( n ) = n
  6. Any program that doesn't have any loops will have f( n ) = 1, since the number of instructions it needs is just a constant (unless it uses recursion)
  7. Any program with a single loop which goes from 1 to n will have f( n ) = n, since it will do a constant number of instructions before the loop, a constant number of instructions after the loop, and a constant number of instructions within the loop which all run n times

Key Point to note about Asymptotic Behavior-
1. Any program that doesn't have any loop will have f(n)=1
2. Any program which has a single loop goes from 1 to n will have f(n)=n
3. When we have two nested loop within each other, we will have asymptotic behavior as f(n)= n2
4. A loop within a loop within a loop will yield f(n)= n3
5. Given a series of for loops that are sequential, the slowest of them determines the asymptotic behavior of the program. Two nested loops followed by a single loop is asymptotically the same as the nested loops alone, because the nested loops dominate the simple loop. e.g. Two nested loop followed by another single loop will have asymptotic behavior as f(n)= n2

Θ( here )

  • When we've figured out the exact such f asymptotically, we'll say that our program is Θ( f( n ) )  e.g. O(1), O(n), O(n2) etc. 
  • We call this function i.e. O(here) as complexity of our algorithm
  • Program with bigger O() run slower than program having smaller O() 

Complexity of Binary Search- O(log n)
Complexity of Merge Sort- O(n log n)
Complexity of Selection sort- O(n2 )

Reference-
Material in this blog is referenced from http://discrete.gr/complexity/. Visit it for explanation of computing the complexity of different popular search & sorting algos

Monday, January 19, 2015

2015: Intw question 4- SQL

Difference b/w delete, truncate and drop
Delete
  • The Delete command is used to delete rows from table
  • After Delete operation we need to perform COMMIT or ROLLBACK to make the changes permanent or undo
  • Delete operations will cause all the delete triggers on the table to fire
  • DML command
Truncate

  • The Truncate command is used to delete rows from table
  • After Truncate operation data can't be rolled back
  • No Delete triggers will be fired 
  • Truncate is faster that Delete
  • DDL command
Drop

  • The Drop command is used to delete table
  • All table rows, indexes, privileges will also be removed
  • Can't be roll back
  • No Delete triggers will be fired 
  • DDL Command
DDL Command- Create, Alter, Truncate, Rename, Drop
DML Command- Select, Insert, Delete, Update
DCL Command- Grant, Revoke

                                                   Difference b/w Primary, Unique & Foreign Key
Primary Key
  • The PRIMARY KEY constraint uniquely identifies each record in a database table.
  • Primary keys must contain unique values.
  • A primary key column cannot contain NULL values.
  • Most tables should have a primary key, and each table can have only ONE primary key.
  • A Primary Key can be comprised of more than one column of a table
CREATE TABLE Persons
(
P_Id int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

Unique Key

  • The UNIQUE constraint uniquely identifies each record in a database table.
  • The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns.
  • A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it.
  • Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
  • A unique key can be comprised of more than one column of a table
  • In MS SQL Server, at most a single row for that column can have NULL
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)
)

Foreign Key
  • A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
 CREATE TABLE Orders
(
O_Id int NOT NULL PRIMARY KEY,
OrderNo int NOT NULL,
P_Id int FOREIGN KEY REFERENCES Persons(P_Id)
)

Indexes, Views & Triggers
Indexes
  • Indexes are special lookup tables that the database search engine can use to speed up data retrieval. 
  • An index is a pointer to data in a table
  • The basic syntax of CREATE INDEX is as follows:
CREATE INDEX index_name ON table_name;
  • A composite index is an index on two or more columns of a table. The basic syntax is as follows:
CREATE INDEX index_name
on table_name (column1, column2);
  • Implicit indexes are indexes that are automatically created by the database server when an object is created. Indexes are automatically created for primary key constraints and unique constraints.
Views
  • A view is a virtual table.
  • A view is a virtual table based on the result-set of an SQL statement.
  • A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
  • A view always shows up-to-date data! The database engine recreates the data, using the view's SQL statement, every time a user queries a view.
  • Syntax to create view 
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition

Triggers
  • Triggers are stored programs, which are automatically executed or fired when some events occur. 
  • Triggers are, in fact, written to be executed in response to any of the following events:
    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
  • The syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name 
{BEFORE | AFTER | INSTEAD OF } 
{INSERT [OR] | UPDATE [OR] | DELETE} 
[OF col_name] 
ON table_name 
[REFERENCING OLD AS o NEW AS n] 
[FOR EACH ROW] 
WHEN (condition)  
DECLARE
   Declaration-statements
BEGIN 
   Executable-statements
EXCEPTION
   Exception-handling-statements
END;
Difference between Stored Procedure and Functions
  • SPs are pre-compiled objects where they are compiled first time and it's compiled format is executed whenever it is called. But Function is compiled and executed every time when it is called
  • Function must return a value but in SP it is optional
  • Functions can be called from SPs but SPs can't be called from Function

    2015: Intw question 3- Basic Xpath

    XPath
    • XPath is used to navigate through elements and attributes in an XML document.
    • XPath is a language for finding information in an XML document.
    • In XPath, there are seven kinds of nodes: 
      • element
      • attribute
      • text
      • namespace
      • processing-instruction
      • comment
      • document
    • Look at the following XML document:
    <?xml version="1.0" encoding="UTF-8"?>

    <bookstore>
      <book>
        <title lang="en">Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
      </book>
    </bookstore>

    Example of nodes in the XML document above:
    <bookstore> (root element node)

    <author>J K. Rowling</author> (element node)

    lang="en" (attribute node)

    • Atomic values/Items/NodeAtomic values are nodes with no children or parent. e.g. 
    J K. Rowling

    "en"

    • Relationship of Nodes
    Refer following example
    <book>
      <title>Harry Potter</title>
      <author>J K. Rowling</author>
      <year>2005</year>
      <price>29.99</price>
    </book>

      • Parent- Each element and attribute has one parent. e.g. book is parent is of title/author/year/price
      • Children- Element nodes may have zero, one or more children. e.g. title/author/year/price are children of book
      • Siblings- Nodes that have same parent e.g. title/author/year/price
      • Ancestors- Node's parent, parent's parent e.g. book is ancestor of title/author/year/price
      • Descendants- Node's children, children's children e.g. title/author/year/price are descendants of book

    • Basic XPath Syntax- Refer following article -
           http://www.w3schools.com/xpath/xpath_syntax.asp

    Sunday, January 18, 2015

    2015: Interview Que2- Java related

    How to call a method of a class without creating it's instance
    • create a method in inherit class in which you can use base keyword to call the base class method....
    public class Person
        {
            protected string ssn = "444-55-6666";
            protected string name = "John L. Malgraine";
    
            public virtual void GetInfo()
            {
                Console.WriteLine("Name: {0}", name);
                Console.WriteLine("SSN: {0}", ssn);
            }
        }
        class Employee : Person
        {
            public string id = "ABC567EFG";
            public override void GetInfo()
            {
                // Calling the base class GetInfo method: 
                base.GetInfo();
                Console.WriteLine("Employee ID: {0}", id);
            }
        }
    
        class TestClass
        {
            static void Main()
            {
                Employee E = new Employee();
                E.GetInfo();
            }
        }
    Output
    Name: John L. Malgraine
    SSN: 444-55-6666 
    Employee ID: ABC567EFG
    • We can make the method static, a static method belongs to class rather than object of a class. We can invoke static method without creating instance of a class. Please note there are following restrictions on static method- 
      • static method can access static data member and can change the value of it.
      • The static method can not use non static data member or call non-static method directly
      • this and super cannot be used in static context.
    Example of static Method
    1. class Student9{  
    2.      int rollno;  
    3.      String name;  
    4.      static String college = "ITS";  
    5.        
    6.      static void change(){  
    7.      college = "BBDIT";  
    8.      }  
    9.   
    10.      Student9(int r, String n){  
    11.      rollno = r;  
    12.      name = n;  
    13.      }  
    14.   
    15.      void display (){System.out.println(rollno+" "+name+" "+college);}  
    16.   
    17.     public static void main(String args[]){  
    18.     Student9.change();  
    19.   
    20.     Student9 s1 = new Student9 (111,"Karan");  
    21.     Student9 s2 = new Student9 (222,"Aryan");  
    22.     Student9 s3 = new Student9 (333,"Sonoo");  
    23.   
    24.     s1.display();  
    25.     s2.display();  
    26.     s3.display();  
    27.     }  
    28. }  

    Output

    111 Karan BBDIT
    222 Aryan BBDIT
    333 Sonoo BBDIT

    Difference between class and structure
    • In structure have a by default public. In class have a by default private.
    • There is no data hiding features comes with structures. Classes do, private, protected and public.
    • A structure can't be abstract, a class can.
    • Structure cannot be inherited. But class can be inherit.
    Structure :

    struct struct-name
    {
    data-type member1;
    data-type member2;
    data-type membern;
    };
    struct struct-name v1,v2...vn;

    Class :

    class class-name
    {
    private :

    data members;
    member functions;

    public :

    data members;
    member functions;

    protected :

    data members;
    member functions;

    };
    class class-name obj1,obj2...objn;

    Java.util.Scanner Class

    • The java.util.Scanner class is a simple text scanner which can parse primitive types and strings using regular expressions.
    • A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespac
    • A scanning operation may block waiting for input.
    • This class inherits methods from the following classes: java.util.Object
    Popular class constructors
    • Scanner(InputStream source) 
    This constructs a new Scanner that produces values scanned from the specified input stream..
    e.g. Scanner sc=new Scanner(System.in);
    • Scanner(File source) 
    This constructs a new Scanner that produces values scanned from the specified file.
    • Scanner(String source) 
    This constructs a new Scanner that produces values scanned from the specified string.

    Popular class methods

    boolean hasNext() 
    This method returns true if this scanner has another token in its input.

    int nextInt() 
    This method scans the next token of the input as an int.

    String next() 
    This method finds and returns the next complete token from this scanner..

    String nextLine() 
    This method advances this scanner past the current line and returns the input that was skipped.

    Example to differentiate between next() and nextLine()

    String str, str1;
    Scanner sc= new Scanner(System.in);
    str=sc.next();
            System.out.println(str);
            str1=sc.nextLine();

            System.out.println(str1);

    Input#0
    www.test.com
    www.test1.com
    Output#0
    www.test.com


    String str, str1;
    Scanner sc= new Scanner(System.in);
    str=sc.nextLine();
            System.out.println(str);
            str1=sc.next();

            System.out.println(str1);

    Input#1
    my name is test
    my name is test1
    Output#1
    my name is test
    my

    System.in/System.out/System.err
    • System.in is an InputStream which is typically connected to keyboard input of console programs. 
    • System.out is a PrintStreamSystem.out normally outputs the data you write to it to the console. 
    • System.err is a PrintStreamSystem.err works like System.out except it is normally only used to output error texts.
    Here is a simple example that uses System.out and System.err:
    try {
      InputStream input = new FileInputStream("c:\\data\\...");
      System.out.println("File opened...");
    
    } catch (IOException e){
      System.err.println("File opening failed:");
      e.printStackTrace();
    }