Showing posts with label Notes. Show all posts
Showing posts with label Notes. Show all posts

Wednesday, 1 March 2017

Java collection Notes



Java Collections and Generics
·        The Java Collections Framework
·        Java Generics
13.1. The Java Collections Framework
·        Java arrays have limitations.
o   They cannot dynamically shrink and grow.
o   They have limited type safety.
o   Implementing efficient, complex data structures from scratch would be difficult.

·        The Java Collections Framework is a set of classes and interfaces implementing complex collection data structures.
o   collection is an object that represents a group of objects.

·        The Java Collections Framework provides many benefits:
o   Reduces programming effort (already there)
o   Increases performance (tested and optimized)
o   Part of the core API (available, easy to learn)
o   Promotes software reuse (standard interface)
o   Easy to design APIs based on generic collections

Sunday, 16 October 2016

Selenium find element Notes

8 locations for selecting object: (Firebug and firepath for visualising)

by.id:
id attribute is availble, value must be unique, should be constant(not dynamic),

name:
name attribute is availble, value must be unique, should be constant,

classname:
attribute is availble, value must be unique, should be constant, no space(compound name)-if space use only any one word

linktext:
must be a link, must have text, unique

paritlalinktext:
must be a link, must have text(paritlaltext can be taken)

tagname:
any html tag

cssselector:
rules of css, even if no attributes, use tag+atttrib combination
css rules:
using id selector: tag#id or #id (button#epam)
using class selector: tag.class or .class
********** using attribute selector: tag[att='attvalue'][att='attvalue']
using id,class and attributeselector: tag#id[class='value'] or tag.class[id='value']
using attributrnameselector:  css=tag[attribute], not pseudo class syntax: css=tag:not([attribute])
using innertext: css=tag.contains("inner text") supports link+other elements without text
partial match on attribute values:
^= input[id^='ctri'] starting with ctrl
$= input[id$='_ctri'] ending with _ctrl
*= input[id*='ctri'] containing ctrl
TIP:
Absolute: Starting from html tag
Relative: relative to tag
While going through nested elements use > for child elements + for sibling elements
*:nth-child(number) for the nth child element

Xpath: 
xml path language 
query language, search backward forward, slow, flexible
absolutepath: start with /  ,  [1] index starts from 1, [@attribute='value'], structure changes wont work, lengthy 
relativepath:
starts with // , use attributes rather than index, //*[@attribute='value'] - any element in html document, using index use parent for sure
multiple attributes: //tag[@attribute='value'][@attribute='value']   //tag[@attribute='value' and @attribute='value']  //tag[@attribute='value' or @attribute='value']
using attributes: //tag[@attribute]
//tag[starts-with(@att,'val')] //tag[ends-with(@att,'val')] //tag[contains(@att,'val')] //not works in fire bug
//tag[@*='value'] -any attribute with value
//tag[@text()='unicode value'] -alternative to link text
**********Xpath Axis- locate elements based on relationship with other elements
axiselement:: - axis elements are ancestor, descendant, following(everything after closing of current tag), following-sibling(after current node), preceding(nodes appear before except ancestor ) , preceding-sibling(before current node)

Monday, 15 August 2016

Sanfoundry 1000 Java MCQS Notes

Networking:
How many ports of TCP/IP are reserved for specific protocols?
1024

Which of these exception is thrown by URL class’s constructors?
MalformedURLException

Which of these methods is used to know the full URL of an URL object?
toExternalForm()

What is the output of this program?
                URL obj = new URL("http://www.sanfoundry.com/javamcq");
                System.out.print(obj.getPort());
Ans. -1

Which of these method of DatagramPacket is used to find the port number?
port()

Which of these method of DatagramPacket is used to obtain the byte array of data contained in a datagram?
getData()

Sunday, 7 August 2016

Java Random Notes


throws is used to postpone the handling of a checked exception and throw is used to invoke an exception explicitly. Mainly used for user defined exceptions.
public class className
{
   public void deposit(double amount) throws RemoteException
   {
      // Method implementation
      throw new RemoteException();
   }
   //Remainder of class definition
}

Sunday, 23 August 2015

SQL interview questions

Assume a schema of Emp ( Id, Name, DeptId ) , Dept ( Id, Name).If there are 10 records in the Emp table and 5 records in the Dept table, how many rows will be displayed in the result of the following SQL query: Select * From Emp, Dept
The query will result in 50 rows as a “cartesian product” or “cross join”, which is the default whenever the ‘where’ clause is omitted.

Given a table SALARIES, such as the one below, that has m = male and f = female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.
columns:  Id, Name, Sex, Salary
UPDATE SALARIES SET sex = CASE sex WHEN 'm' THEN 'f' ELSE 'm' END

Given a table TBL with a field Nmbr that has rows with the following values:
1,0,0,1,1,1,1,0,0,1,0,1,0,1,0,1
Write a query to add 2 where Nmbr is 0 and add 3 where Nmbr is 1.
update TBL set Nmbr = case when Nmbr > 0 then Nmbr+3 else Nmbr+2 end;

Write a SQL query to find the 10th highest employee salary from an Employee table. Explain your answer.
SELECT TOP (1) Salary FROM
(
    SELECT DISTINCT TOP (10) Salary FROM Employee ORDER BY Salary DESC
) AS Emp ORDER BY Salary
WHEN TOP IS NOT SUPPORTED
SELECT Salary FROM
(
    SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 10
) AS Emp ORDER BY Salary DESC LIMIT 1;

Write a SQL query using UNION ALL (not UNION) that uses the WHERE clause to eliminate duplicates. Why might you want to do this?
SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X
The key is the AND a!=X part. This gives you the benefits of the UNION (a.k.a., UNION DISTINCT) command,

Table Name : Employee
Employee_id    First_name    Last_name    Salary    Joining_date    Department
Table Name : Incentives
Employee_ref_id    Incentive_date    Incentive_amount

Get First_Name from employee table in upper case
Select upper(FIRST_NAME) from EMPLOYEE

Select first 3 characters of FIRST_NAME from EMPLOYEE
select substr(FIRST_NAME,0,3) from employee //oracle
select substring(FIRST_NAME,1,3) from employee //mysql

Get position of 'o' in name 'John' from employee table
Select instr(FIRST_NAME,'o') from employee where first_name='John' //oracle
Select LOCATE('o',FIRST_NAME) from employee where first_name='John' //mysql

Get FIRST_NAME from employee table after removing white spaces from right side
select RTRIM(FIRST_NAME) from employee

Get length of FIRST_NAME from employee table
select length(FIRST_NAME) from employee

Get First_Name from employee table after replacing 'o' with '$'
select REPLACE(FIRST_NAME,'o','$') from employee

Get First_Name and Last_Name as single column from employee table separated by a '_'
Select FIRST_NAME|| '_' ||LAST_NAME from EMPLOYEE //oracle
Select concat(FIRST_NAME,'_',LAST_NAME) from EMPLOYEE //mysql

Get FIRST_NAME ,Joining year,Joining Month and Joining Date from employee table
Select FIRST_NAME, to_char(joining_date,'YYYY') JoinYear , to_char(joining_date,'Mon'), to_char(joining_date,'dd') from EMPLOYEE //oracle
select year(joining_date),month(joining_date), DAY(joining_date) from EMPLOYEE //mysql

Get all employee details from the employee table order by First_Name Ascending and Salary descending
Select * from employee order by FIRST_NAME asc,SALARY desc

Get employee details from employee table whose employee name are “John” and “Roy”
Select * from EMPLOYEE where FIRST_NAME in ('John','Roy')

Get employee details from employee table whose joining year is “2013”
Select * from EMPLOYEE where to_char(joining_date,'YYYY')='2013' //oracle
Select * from EMPLOYEE where year(joining_date)='2013' //mysql

Get employee details from employee table who joined before January 1st 2013
Select * from EMPLOYEE where JOINING_DATE <to_date('01/01/2013','dd/mm/yyyy') //oracle
Select * from EMPLOYEE where joining_date <'2013-01-01' //mysql

Get Joining Date,Time including milliseconds from employee table
select to_char(JOINING_DATE,'dd/mm/yyyy HH:mi:ss.ff') from EMPLOYEE . Column Data Type should be “TimeStamp”  //oracle
Select MICROSECOND(joining_date) from EMPLOYEE //mysql

Get names of employees from employee table who has '%' in Last_Name. Tip : Escape character for special characters in a query.
Select FIRST_NAME from employee where Last_Name like '%?%%'  //oracle
Select FIRST_NAME from employee where Last_Name like '%\%%'  //mysql

Get department wise average salary from employee table order by salaryascending
select DEPARTMENT,avg(SALARY) AvgSalary from employee group by DEPARTMENT order by AvgSalary asc

Get department wise maximum salary from employee table order by salaryascending
select DEPARTMENT,max(SALARY) MaxSalary from employee group by DEPARTMENT order by MaxSalary asc

Select department,total salary with respect to a department from employee table where total salary greater than 800000 order by Total_Salary descending
Select DEPARTMENT,sum(SALARY) Total_Salary from employee group by DEPARTMENT having sum(SALARY) >800000 order by Total_Salary desc

Select employee details from employee table if data exists in incentive table ?
select * from EMPLOYEE where exists (select * from INCENTIVES)

Select 20 % of salary from John , 10% of Salary for Roy and for other 15 % of salary from employee table
SELECT FIRST_NAME, CASE FIRST_NAME WHEN 'John' THEN SALARY * .2 WHEN 'Roy' THEN SALARY * .10 ELSE SALARY * .15 END "Deduced_Amount" FROM EMPLOYEE

Delete employee data from employee table who got incentives in incentive table
delete from EMPLOYEE where EMPLOYEE_ID in (select EMPLOYEE_REF_ID from INCENTIVES)

Update incentive table where employee name is 'John'
update INCENTIVES set INCENTIVE_AMOUNT='9000' where EMPLOYEE_REF_ID=(select EMPLOYEE_ID from EMPLOYEE where FIRST_NAME='John' )

Select first_name, incentive amount from employee and incentives table for those employees who have incentives and incentive amount greater than 3000
Select FIRST_NAME,INCENTIVE_AMOUNT from employee a inner join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID and INCENTIVE_AMOUNT >3000

Select first_name, incentive amount from employee and incentives table for all employes even if they didn't get incentives
Select FIRST_NAME,INCENTIVE_AMOUNT from employee a left join incentives B on A.EMPLOYEE_ID=B.EMPLOYEE_REF_ID

Select TOP N salary from employee table
select * from (select * from employee order by SALARY desc) where rownum <N + 1 //oracle
select * from employee order by salary desc limit N //mysql

Select Nth Highest salary from employee table
select min(salary) from (select * from (select * from employee order by SALARY desc) where rownum <N + 1)
select min(SALARY) from (select * from employee order by salary desc limit N) a

Sunday, 9 August 2015

SQL Notes

These components invovlved in SQL resultgeneration are Query Dispatcher, Optimization Engines, Classic Query Engine and SQL Query Engine, etc. Classic query engine handles all non-SQL queries but SQL query engine won't handle logical files
DDL Commands: CREATE, ALTER, DROP
DML Commands: SELECT, INSERT, UPDATE, DELETE
DCL Commands: GRANT    , REVOKE
Commonly used constraints available in SQL:
NOT NULL Constraint: Ensures that a column cannot have NULL value.
DEFAULT Constraint: Provides a default value for a column when none is specified.
UNIQUE Constraint: Ensures that all values in a column are different.
PRIMARY Key: Uniquely identified each rows/records in a database table.
FOREIGN Key: Uniquely identified a rows/records in any another database table.
CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain conditions.
INDEX: Use to create and retrieve data from the database very quickly.
Following categories of the data integrity exist with each RDBMS:
Entity Integrity: There are no duplicate rows in a table.
Domain Integrity: Enforces valid entries for a given column by restricting the type, the format, or the range of values.
Referential integrity: Rows cannot be deleted, which are used by other records.
User-Defined Integrity: Enforces some specific business rules that do not fall into entity, domain or referential integrity.

Syntax:
Important point to be noted is that SQL is case insensitive, which means SELECT and select have same meaning in SQL statements, but MySQL makes difference in table names.
SQL SELECT Statement:
SELECT column1, column2....columnN
FROM   table_name;
SQL DISTINCT Clause:
SELECT DISTINCT column1, column2....columnN
FROM   table_name;
SQL WHERE Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  CONDITION;
SQL AND/OR Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  CONDITION-1 {AND|OR} CONDITION-2;
SQL IN Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  column_name IN (val-1, val-2,...val-N);
SQL BETWEEN Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  column_name BETWEEN val-1 AND val-2;
SQL LIKE Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  column_name LIKE { PATTERN };
SQL ORDER BY Clause:
SELECT column1, column2....columnN
FROM   table_name
WHERE  CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY Clause:
SELECT SUM(column_name)
FROM   table_name
WHERE  CONDITION
GROUP BY column_name;
SQL COUNT Clause:
SELECT COUNT(column_name)
FROM   table_name
WHERE  CONDITION;
SQL HAVING Clause:
SELECT SUM(column_name)
FROM   table_name
WHERE  CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQL CREATE TABLE Statement:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
SQL DROP TABLE Statement:
DROP TABLE table_name;
SQL CREATE INDEX Statement :
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
SQL DROP INDEX Statement :
ALTER TABLE table_name
DROP INDEX index_name;
SQL DESC Statement :
DESC table_name;
SQL TRUNCATE TABLE Statement:
TRUNCATE TABLE table_name;
SQL ALTER TABLE Statement:
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
SQL ALTER TABLE Statement (Rename) :
ALTER TABLE table_name RENAME TO new_table_name;
SQL INSERT INTO Statement:
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
SQL UPDATE Statement:
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE  CONDITION ];
SQL DELETE Statement:
DELETE FROM table_name
WHERE  {CONDITION};
SQL CREATE DATABASE Statement:
CREATE DATABASE database_name;
SQL DROP DATABASE Statement:
DROP DATABASE database_name;
SQL USE Statement:
USE database_name;
SQL COMMIT Statement:
COMMIT;
SQL ROLLBACK Statement:
ROLLBACK;

SQL  Data types and Operators //Refer to tutorials point

SQL - Expressions
SQL - Boolean Expressions:
SELECT column1, column2, columnN
FROM table_name
WHERE SINGLE VALUE MATCHTING EXPRESSION;
SQL - Numeric Expression:
SELECT numerical_expression as  OPERATION_NAME
[FROM table_name
WHERE CONDITION] ;
SQL> SELECT COUNT(*) AS "RECORDS" FROM CUSTOMERS;
SQL - Date Expressions:
SQL>  SELECT CURRENT_TIMESTAMP;
SQL>  SELECT  GETDATE();

More Syntax:
CREATE DATABASE DatabaseName;
DROP DATABASE DatabaseName;
USE DatabaseName;
SHOW DATABASES;
CREATE TABLE table_name(
   column1 datatype,
   column2 datatype,
   column3 datatype,
   .....
   columnN datatype,
   PRIMARY KEY( one or more columns )
);
DESC TABLE;
DROP TABLE table_name;
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)] 
VALUES (value1, value2, value3,...valueN);
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);
INSERT INTO first_table_name [(column1, column2, ... columnN)]
   SELECT column1, column2, ...columnN
   FROM second_table_name
   [WHERE condition];
SELECT column1, column2, columnN FROM table_name;
SELECT * FROM table_name;
SELECT column1, column2, columnN
FROM table_name
WHERE [condition]
//specify a condition using comparison or logical operators like >, <, =, LIKE, NOT, etc
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
SELECT column1, column2, columnN
FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
DELETE FROM table_name
WHERE [condition];
DELETE FROM table_name; //ALL RECORDS
SELECT FROM table_name
WHERE column LIKE '%XXXX%'
SELECT FROM table_name
WHERE column LIKE '_XXXX_'
//The percent sign represents zero, one, or multiple characters. The underscore represents a single number or character.
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE [condition]
//The SQL TOP clause is used to fetch a TOP N number or X percent records from a table.All the databases do not support TOP clause. For example MySQL supports LIMIT clause to fetch limited number of records and Oracle uses ROWNUM to fetch limited number of records used after WHERE
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
//The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default. To fetch the rows with own preferred order, the SELECT query would as follows(ordered according to delhi, bhopal, kota etc):
SQL> SELECT * FROM CUSTOMERS
    ORDER BY (CASE ADDRESS
    WHEN 'DELHI'      THEN 1
    WHEN 'BHOPAL'      THEN 2
    WHEN 'KOTA'      THEN 3
    WHEN 'AHMADABAD' THEN 4
    WHEN 'MP'     THEN 5
    ELSE 100 END) ASC, ADDRESS DESC;
//The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause. This is useful as it allows you to summarize information.  For instance you can use aggregate functions such as SUM and AVERAGE to calculate values.
SELECT column1, column2
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2
//The SQL DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]

Advanced SQL Syntax:
//Constraints can be specified when a table is created with the CREATE TABLE statement or you can use ALTER TABLE statement to create constraints even after the table is created.
ALTER TABLE tablename DROP CONSTRAINT columnname;
ALTER TABLE tablename DROP PRIMARY KEY;
JOINS:
The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each. Several operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE, and NOT; they can all be used to join tables.
SELECT ID, NAME, AGE, AMOUNT
        FROM CUSTOMERS, ORDERS
        WHERE  CUSTOMERS.ID = ORDERS.CUSTOMER_ID;
There are different types of joins available in SQL:
INNER JOIN: returns rows when there is a match in both tables.
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the tables.
SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.
UNION:
The SQL UNION clause/operator is used to combine the results of two or more SELECT statements without returning any duplicate rows. To use UNION, each SELECT must have the same number of columns selected, the same number of column expressions, the same data type, and have them in the same ordER
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
UNION
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
The UNION ALL operator is used to combine the results of two SELECT statements including duplicate rows. use UNION ALL instead of UNION in above syntax
SQL INTERSECT Clause: is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement.
SQL EXCEPT Clause : combines two SELECT statements and returns rows from the first SELECT statement that are not returned by the second SELECT statement.
 Alias:
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a temporary change and the actual table name does not change in the database.
SELECT column1, column2....
FROM table_name AS alias_name
WHERE [condition];
SELECT column_name AS alias_name
FROM table_name
WHERE [condition];
Indexes:
CREATE INDEX index_name ON table_name;
CREATE INDEX index_name
on table_name (column1, column2);
DROP INDEX index_name;
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.
ALTER TABLE:
ALTER TABLE table_name ADD column_name datatype;
ALTER TABLE table_name DROP COLUMN column_name;
ALTER TABLE table_name MODIFY COLUMN column_name datatype;
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
ALTER TABLE table_name
DROP CONSTRAINT MyUniqueConstraint;
TRUNCATE TABLE:
The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.
TRUNCATE TABLE  table_name;
Views:
A view is nothing more than a SQL statement that is stored in the database with an associated name.
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition]
WITH CHECK OPTION;
DROP VIEW view_name;
 The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs satisfy the condition(s) in the view definition. You can use view name instead of table name for select, update, insert, delete. However these operations require certain conditions be fulfilled
Having Clause:
The HAVING clause enables you to specify conditions that filter which group results appear in the final results.The WHERE clause places conditions on the selected columns, whereas the HAVING clause places conditions on groups created by the GROUP BY clause.
SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2
Transactions:
The COMMIT command is the transactional command used to save changes invoked by a transaction to the database.
COMMIT;
The ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database.
ROLLBACK;
A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without rolling back the entire transaction.
SAVEPOINT SAVEPOINT_NAME;
ROLLBACK TO SAVEPOINT_NAME;
The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.
RELEASE SAVEPOINT SAVEPOINT_NAME;
The SET TRANSACTION command can be used to initiate a database transaction.
SET TRANSACTION [ READ WRITE | READ ONLY ];
Date Functions: Refer to tutorials point
Temporary Tables:
The most important thing that should be known for temporary tables is that they will be deleted when the current client session terminates.utomatically when the script finishes executing. If you are connected to the MySQL database server through the MySQL client program, then the temporary table will exist until you close the client or manually destroy the table.
CREATE TEMPORARY TABLE temporarytablename(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
DROP TABLE temporarytable;
Sub Queries:
A Subquery or Inner query or Nested query is a query within another SQL query and embedded within the WHERE clause.A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
SELECT column_name [, column_name ]
FROM   table1 [, table2 ]
WHERE  column_name OPERATOR
      (SELECT column_name [, column_name ]
      FROM table1 [, table2 ]
      [WHERE])
INSERT INTO table_name [ (column1 [, column2 ]) ]
           SELECT [ *|column1 [, column2 ]
           FROM table1 [, table2 ]
           [ WHERE VALUE OPERATOR ]
UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME)
   [ WHERE) ]
DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME)
   [ WHERE) ]
Sequences:
CREATE TABLE tablename(
column1 datatype AUTO_INCREMENT,
column2 datatype,
column3 datatype,
PRIMARY KEY (column1)
);
There may be a case when you have deleted many records from a table and you want to resequence all the records. If you determine that resequencing an AUTO_INCREMENT column is unavoidable, the way to do it is to drop the column from the table, then add it again.
ALTER TABLE  tablename DROP column1;
mysql> ALTER TABLE tablename
    -> ADD column1 INT UNSIGNED NOT NULL AUTO_INCREMENT FIRST,
    -> ADD PRIMARY KEY (column1);
By default, MySQL will start sequence from 1 but you can specify any other number as well at the time of table creation using AUTO_INCREMENT = number(10 or 100)

Thursday, 6 August 2015

C Interview Questions

Explain i = (j++, k++) and while (i = (rand() % 100), i != 50)
Here, the comma operator is used to execute three expressions in one line: assign k to i, increment j, and increment k. The value that i receives is always the rightmost expression.
In while: the comma operator separates two expressions, each of which is evaluated for each iteration of the while statement. The first expression, to the left of the comma, assigns i to a random number from 0 to 99.The second expression, which is more commonly found in a while statement, is a conditional expression that tests to see whether i is not equal to 50.


How can you tell whether a loop ended prematurely?
Generally, loops are dependent on one or more variables. Your program can check those variables outside the loop to ensure that the loop executed properly


What is the difference between goto and long jmp( ) and setjmp()?
A goto statement implements a local jump of program execution, and the longjmp() and setjmp() functions implement a nonlocal, or far, jump of program execution.When your program calls setjmp(), the current state of your program is saved in a structure of type jmp_buf. Later, your program can call the longjmp() function to restore the program's state as it was when you called setjmp(). Unlike the goto statement, the longjmp() and setjmp() functions do not need to be implemented in the same function.However, there is a major drawback to using these functions: your program, when restored to its previously saved state, will lose its references to any dynamically allocated memory between the longjmp() and the setjmp(). This means you will waste memory for every malloc() or calloc() you have implemented


Can an array be an lvalue?
Is an array an expression to which we can assign a value? The answer to this question is no, because an array is composed of several separate array elements that cannot be treated as a whole for assignment purposes.It should be noted here that unlike arrays, structures can be treated as lvalues.


Is left-to-right or right-to-left order guaranteed for operator precedence?
The simple answer to this question is neither. The C language does not always evaluate left-to-right or right-to-left. Generally, function calls are evaluated first, followed by complex expressions and then simple expressions.Additionally, most of today's popular C compilers often rearrange the order in which the expression is evaluated in order to get better optimized code. You therefore should always implicitly define your operator precedence by using parentheses.


Can a variable be both const and volatile?
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler.Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested. The const modifier means that this code cannot change the value of the variable, but that does not mean that the value cannot be changed by means outside this code(hardware). For instance, the timer structure was accessed through a volatile const pointer


How can you determine the maximum value that a numeric variable can hold?
The easiest way to find out how large or small a number that a particular type can hold is to use the values defined in the ANSI standard header file limits.h.


When should a type cast be used?
The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers.


What is meant by "bit masking"?
Bit masking means selecting only certain bits from byte(s) that might have many bits set. To examine some bits of a byte, the byte is bitwise "ANDed" with a mask that is a number consisting of only those bits of interest.


Are bit fields portable?
Bit fields are not portable. Because bit fields cannot span machine words, and because the number of bits in a machine word is different on different machines, a particular program using bit fields might not even compile on a particular machine.


What is meant by high-order and low-order bytes?
We generally write numbers from left to right, with the most significant digit first.The byte holding the least significant 8 bits is called the least significant byte, or low-order byte. The byte containing the most significant 8 bits is the most significant byte, or high- order byte.


Why should I prototype a function?
A function prototype tells the compiler what kind of arguments a function is looking to receive and what kind of return value a function is going to give back. This approach helps the compiler ensure that calls to a function are made correctly(same argument types in same order) and that no erroneous type conversions are taking place. prototype: int some_func(int, char*, long);


What is a static function?
A static function is a function whose scope is limited to the current source file.


Is it possible to execute code even after the program exits the main() function?
The standard C library provides a function named atexit() that can be used to perform "cleanup" operations when your program terminates. You can set up a set of functions you want to perform automatically when your program exits by passing function pointers to the atexit() function.the LIFO method is used. The atexit() function can come in handy when you want to ensure that certain functions (such as closing your program's data files) are performed before your program terminates.


What does a function declared as PASCAL do differently?
A C function declared as PASCAL uses a different calling convention than a "regular" C function. Normally, C function parameters are passed right to left; with the PASCAL calling convention, the parameters are passed left to right.Functions that use the PASCAL calling convention are more efficient than regular C functions—the function calls tend to be slightly faster. Microsoft Windows is an example of an operating environment that uses the PASCAL calling convention


What is a macro, and how do you use it?
A macro is a preprocessor directive that provides a mechanism for token replacement in your source code. Macros are created by using the #define statement. Here is an example of a macro: #define VERSION_STAMP "1.02"


What will the preprocessor do for a program?
The preprocessor reads in all of your include files and the source code you are compiling and creates a preprocessed version of your source code.A preprocessor directive is a statement (such as #define) that gives the preprocessor specific instructions on how to modify your source code.


What is the benefit of using #define to declare a constant?
it is best to put #define statements in an include file so that several modules can use the same constant value.it also takes up the least memory. Constants defined in this manner are simply placed directly into your source code, with no variable space allocated in memory


What is the benefit of using enum to declare a constant?
constants declared with enum are automatically generated by the compiler. constants declared with enum tend to be more readable to the programmer.  enumerated constants can usually be inspected during a debugging session


How are portions of a program disabled in demo versions?
If you are distributing a demo version of your program, the preprocessor can be used to enable or disable portions of your program.
#if DEMO_VERSION
     printf("Sorry! You can't save documents using the DEMO version of
             this program!\n");
     return(0);
#endif
As a better alternative, you could define DEMO_VERSION in your compiler options when compiling and avoid having to change the source code for the program.


How can type-insensitive macros be created?
A type-insensitive macro is a macro that performs the same basic operation on different data types. This task can be accomplished by using the concatenation operator to create a call to a type-sensitive function based on the parameter passed to the macro. The following program provides an example:
#include <stdio.h>
#define SORT(data_type) sort_ ## data_type
void sort_int(int** i);
void sort_long(long** l);
void sort_float(float** f);
void sort_string(char** s);


What is a pragma?
The #pragma preprocessor directive allows each compiler to implement compiler-specific features that can be turned on and off with the #pragma statement. For instance, your compiler might support a feature called loop optimization. This feature can be invoked as a command-line option or as a #pragma directive using pragma loop_opt(on)


What is #line used for?
The #line preprocessor directive is used to reset the values of the __LINE__ and __FILE__ symbols, respectively. This directive is commonly used in fourth-generation languages that generate C language source files.


What is the difference between a string copy (strcpy) and a memory copy (memcpy)? When should each be used?
The strcpy() function is designed to work exclusively with strings. It copies each byte of the source string to the destination string and stops when the terminating null character (\0) has been moved. On the other hand, the memcpy() function is designed to work with any type of data.Because not all data ends with a null character, you must provide the memcpy() function with the number of bytes you want to copy from the source to the destination.


How can I pad a string to a known length?
printf("%-10.10s", data);


How can I convert a number to a string?
The standard C library provides itoa(),ltoa(), ultoa() for converting numbers of all formats (integers, longs, floats, and so on) to strings and vice versa.
itoa(num, str, 10); //the third is the base, or radix, to be used when converting the number
You can use atof(),atoi(),atol() for conversion from strings


Can the sizeof operator be used to tell the size of an array passed to a function?
No. There's no way to tell, at runtime, how many elements are in an array parameter just by looking at the array parameter itself. Remember, passing an array to a function is exactly the same as passing a pointer to the first element


Is it better to use a pointer to navigate an array of values, or is it better to use a subscripted array name?
It's easier for a C compiler to generate good code for pointers than for subscripts.


Can you assign a different address to an array tag?
No,An array is an object; the array tag is a pointer to the first element in that object For an external or static array, the array tag is a constant value known at link time. An array tag is not a pointer.In one special case, it looks as if you can change an array tag:
void  f( char a[ 12 ] ){
       ++a;
    }
The trick here is that array parameters aren't really arrays. They're really pointers.


What is the difference between array_name and &array_name?
One is a pointer to the first element in the array; the other is a pointer to the array as a whole.


What is indirection?
If you declare a variable, its name is a direct reference to its value. If you have a pointer to a variable, or any other object in memory, you have an indirect reference to its value. If p is a pointer, the value of p is the address of the object. *p means "apply the indirection operator to p";


 What is a void pointer?
A void pointer is a C convention for "a raw address." The compiler has no idea what type of object a void pointer "really points to." If you write void *p p doesn't point to a void. A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.
 void *memcpy( void *addr1, void *addr2, size_t n ) void pointers here mean that this is raw memory being copied. NUL characters (zero bytes) aren't significant, and just about anything can be copied.


Is NULL always equal to 0(zero)?
The answer depends on what you mean by "equal to." If you mean "compares equal to," then yes, NULL is always equal to 0. That's the whole point of the definition of a null pointer. If you mean "is stored the same way as an integer zero," the answer is no, not necessarily. That's the most common way to store a null pointer.
What does it mean when a pointer is used in an if statement?
Any time a pointer is used as a condition, it means "Is this a non-null pointer?" A pointer can be used in an if, while, for, or do/while statement, or in a conditional expression.


Can you add pointers together?
No, you can't add pointers together. The only time the addition of pointers might come up is if you try to add a pointer and the difference of two pointers: p = p + p2 - p1;


Can the size of an array be declared at runtime?
No. In an array declaration, the size must be known at compile time. You can't specify a size that's known only at runtime. For example, if i is a variable, you can't write code like this: char array[i];  Some languages provide this latitude. C doesn't. 


Difference between  malloc() or calloc()?
The major difference is that malloc() doesn't initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. calloc() fills the allocated memory with all zero bits. That means that anything there you're going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array


What is the heap?
The heap is where malloc(), calloc(), and realloc() get memory.Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory isn't deallocated automatically; you have to call free().If memory is allocated from the heap, it's available until the program ends. That's great if you remember to deallocate it when you're done. If you forget, it's a problem. A "memory leak" is some allocated memory that's no longer needed but isn't deallocated


What is the difference between NULL and NUL?
NULL is a macro defined in <stddef.h> for the null pointer.NUL is the name of the first character in the ASCII character set. It corresponds to a zero value.


What is a "null pointer assignment" error? What are memory faults, and core dumps?
If the program tries to write to the area where the NULL pointer points to, it will overwrite the data put there by the compiler. When the program is done, code generated by the compiler examines that area. If that data has been changed, the compiler-generated code complains with null pointer assignment.core dumped and Memory fault are messages meaning that a pointer or an array subscript was wildly out of bounds.They aren't restricted to null pointer problems.


How do you print an address?
The safest way is to use printf() (or fprintf() or sprintf()) with the %P specification. That prints a void pointer (void*) printf( "%P\n", (void*) buffer );


What is a stream and how to redirect and restore a standard stream?
A stream is a continuous series of bytes that flow into or out of your program. Input and output from devices such as the mouse, keyboard, disk, screen, modem, and printer are all handled with streams. In DOS, redirection is accomplished using the redirection characters, < and >. C:>PRINTIT < STRINGS.TXT. you can redirect a standard stream from within your program by using the standard C library function named freopen(): freopen("output.txt", "w", stdout); 


By using the standard C library functions named dup() and fdopen(), you can restore a standard stream such as stdout to its original state. The dup() function duplicates a file handle. You can use the dup() function to save the file handle corresponding to the stdout standard stream. The fdopen() function opens a stream that has been duplicated with the dup() function.


What is the difference between text and binary modes?
Text streams are interpreted, with a maximum length of 255 characters. With text streams, carriage return/line feed combinations are translated to the newline \n character and vice versa. Binary streams are uninterpreted and are treated one byte at a time with no translation of characters. 


How do you determine whether to use a stream function or a low-level function?
you should always use buffered stream functions when accessing nonshared files, and you should always use the low-level functions when accessing shared files.


How do you list a file's date and time?
The file attributes are stored in the find_t.attrib structure member. A file's date and time are stored in the find_t structure returned from the _dos_findfirst() and _dos_findnext() functions.The date and time stamp of the file is stored in the find_t.wr_date and find_t.wr_time structure members. 


How do you view the PATH?
Your C compiler library contains a function called getenv() that can retrieve any specified environment variable. It has one argument, which is a pointer to a string containing the environment variable you want to retrieve. It returns a pointer to the desired environment string on successful completion.


How can I open a file so that other programs can update it at the same time?
Your C compiler library contains a low-level file function called sopen() that can be used to open a file in shared mode. Beginning with DOS 3.0, files could be opened in shared mode by loading a special program named SHARE.EXE.The sopen() function takes four parameters: a pointer to the filename you want to open, the operational mode you want to open the file in, the file sharing mode to use, and, if you are creating a file, the mode to create the file in.by using the SH_DENYWR shared flag you instruct the compiler that your program is going to deny any writing or reading attempts by other programs.


What is the difference between a free-standing and a hosted environment?
Embedded systems don't necessarily have any sort of file system, or much of an operating system at all. The ANSI/ISO standard calls these "free-standing" systems, and it doesn't require them to provide anything except the language itself. The alternative is a program running on a PC or a mainframe or something in-between; that's a "hosted" environment.


How do I determine whether a character is numeric, alphabetic, and so on?
The header file ctype.h defines various functions for determining what class a character belongs to


What are multibyte characters?
Multibyte characters are another way to make internationalized programs easier to write. Specifically, they help support languages such as Chinese and Japanese that could never fit into eight-bit characters.

Monday, 3 August 2015

DBMS Basic Interview Questions

What is a Database system?
The database and DBMS software together is called as Database system.

Describe the three levels of data abstraction?
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire database.

Define the "integrity rules"?
Entity Integrity: States that "Primary key cannot have NULL value"
Referential Integrity: States that "Foreign Key can be either a NULL value or should be Primary Key value of other relation.

What is extension and intension?
Extension: It is the number of tuples present in a table at any instance. This is time dependent.
Intension: It is a constant value that gives the name, structure of table and the constraints laid on it.

What is Data Independence?
The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Physical Data Independence: Modification in physical level should not affect the logical level.
Logical Data Independence: Modification in logical level should affect the view level.

What is an Entity?
It is a 'thing' in the real world with an independent existence.Entity type is a collection (set) of entities that have same attributes.Entity set is a collection of all entities of particular entity type in the database.An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. An attribute is a particular property, which describes the entity.

What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, ..., An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn).Degree of a Relation is the number of attribute of its relation schema.
Relationship set-The collection (or set) of similar relationships.
Relationship type-Relationship type defines a set of associations or a relationship set among a given set of entity types.
degree of Relationship type-is the number of entity type participating.

Define:
SQL -Structured Query Language
SDL - Storage Definition Language
DML - Data Manipulation Language

What is Record-at-a-time?
The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time.

What is Set-at-a-time or Set-oriented?
The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented.

What is normalization?
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties
(1).Minimizing redundancy, (2). Minimizing insertion, deletion and update anomalies

What is Functional Dependency?
Functional dependency (FD) is a set of constraints between two attributes in a relation. Functional dependency says that if two tuples have same values for attributes A1, A2,..., An, then those two tuples must have to have same values for attributes B1, B2, ..., Bn. Functional dependency is represented by an arrow sign (→) that is, X→Y, where X functionally determines Y. 

What is Fully Functional dependency?
A functional dependency X Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more.

What is Lossless join Decomposition?
 It is the ability to ensure that any instance of the original relation can be identified from corresponding instances in the smaller relations.
Let R = (A, B, C, D) be the relation schema, with A, B, C and D attributes.
Let F = { A -> BC } be the set of functional dependencies.
Decomposition into R1 = (A, B, C) and R2 = (A, D) is lossless under F because R1 intersection R2 = (A), A is a superkey in R1 ( A -> BC ) so R1  intersection R2 -> R1.

Normal Forms:

First Normal Form (1NF):
Every attribute must have value. It should not be empty. In RDBMS a column without
value has NULL value that can be manipulated or accesses like a normal value
Everyattribute must have atomic value that cannot be shorten further. For example:
Name is non-atomic attribute as it can be broken into First Name, Middle Name
and Surname

Second Normal Form (2NF):
An entity must be in First Normal Form
Entity must have a Primary Key or Composite Primary Key
Every attribute must be fully and functionally dependent upon Primary Key

Third Normal Form (3NF):
An entity must be Second Normal Form
There must not be any dependency among non-key attributes (other that Primary Key

Boyce-Codd Normal Form (BCNF):
An entity must be in Third Normal Form
If the entity has a Composite Primary Key &amp; Alternate Primary Key with one or
more attribute common to both, in such case entity must be broken into three
entities

Fourth Normal Form (4NF):
An entity must be in Boyce-Codd Normal Form
If an attribute is based on Value List must be taken out as a separate entity

Fifth Normal Form (5NF):
An entity must be in Fourth Normal Form
If an attribute is multi-valued attribute then it must be taken out as a separate entity

What is Domain-Key Normal Form?
A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation.

What are partial, alternate,, artificial, compound and natural key?
Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator.
Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key.
Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key.
Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.

What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found. 
Types:
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing

ACID properties − 
Atomicity − This property states that a transaction must be treated as an atomic unit, that is, either all of its operations are executed or none. There must be no state in a database where a transaction is left partially completed. States should be defined either before the execution of the transaction or after the execution/abortion/failure of the transaction.
Consistency − The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.
Durability − The database should be durable enough to hold all its latest updates even if the system fails or restarts. If a transaction updates a chunk of data in a database and commits, then the database will hold the modified data. If a transaction commits but the system fails before the data could be written on to the disk, then that data will be updated once the system springs back into action.
Isolation − In a database system where more than one transaction are being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.

What is a Phantom Deadlock?
In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts.

What do you mean by Correlated subquery?
Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery.

What are the unary operations in Relational Algebra?
PROJECTION and SELECTION.

Are the resulting relations of PRODUCT and JOIN operation the same?
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.

Name the sub-systems of a RDBMS.
I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management.

What is the job of the information stored in data-dictionary?
The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location.

Name the three major set of files on disk that compose a database in Oracle.
There are three major sets of files on disk that compose a database. All the files are binary. These are
1.) Database files 
2.) Control files
3.) Redo logs

What is database Trigger?
A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted.

What are stored-procedures?
A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

Managers:
Buffer Manager: It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory.
Transaction Manager:It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting.
File Manager: It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk.
Authorization and Integrity manager: It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.

What are cursors give different types of cursors?
PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors
1.) Implicit Cursors: Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when there is no explicit cursor for the statement.
2.) Explicit Cursors: Explicit cursors are programmer defined cursors for gaining more control over the context area.

What is cold backup and hot backup (in case of Oracle)?
Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy. If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost.
Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.

What is meant by Proactive, Retroactive and Simultaneous Update.
Proactive Update: The updates that are applied to database before it becomes effective in real world.
Retroactive Update: The updates that are applied to database after it becomes effective in real world.
Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world.

Core Java Technical Questions

What is the difference between a JDK and a JVM?
JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

What is the base class of all classes?
java.lang.Object and java.lang package is imported by default even without a package declaration.

Is Java a pure object oriented language?
Java uses primitive data types and hence is not a pure object oriented language.

Are arrays primitive data types?
In Java, Arrays are objects.

Tuesday, 28 July 2015

Operating System Notes

OS is a software which manages hardware. An operating System controls the allocation of resources and services such as memory, processors, devices and information.

Following are some of important functions of an operating System:
Memory management refers to management of Primary Memory or Main Memory. Main memory provides a fast storage that can be access directly by the CPU. So for a program to be executed, it must in the main memory.
In multiprogramming environment, OS decides which process gets the processor when and how much time. This function is called process scheduling.
I/O Operation: I/O subsystem comprised of I/O devices and their corresponding driver software. Drivers hides the peculiarities of specific hardware devices from the user as the device driver knows the peculiarities of the specific device.
A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. Operating System does the file management.
Program execution: Operating system handles many kinds of activities from user programs to system programs like printer spooler, name servers, file server etc. Each of these activities is encapsulated as a process.
 Security -- By means of password and similar other techniques, preventing unauthorized access to programs and data.
Control over system performance -- Recording delays between request for a service and response from the system.
Job accounting -- Keeping track of time and resources used by various jobs and users.
Error detecting aids -- Production of dumps, traces, error messages and other debugging and error detecting aids.
Coordination between other softwares and users -- Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems.

Types of Operating System:
Batch operating system: The users of batch operating system do not interact with the computer directly. Each user prepares his job on an off-line device like punch cards and submits it to the computer operator. The operator then sorts programs into batches with similar requirements.
Time-sharing operating systems: Time sharing is a technique which enables many people, located at various terminals, to use a particular computer system at the same time.Multiple jobs are executed by the CPU by switching between them, but the switches occur so frequently. Thus, the user can receives an immediate response.
Distributed operating System: Distributed systems use multiple central processors to serve multiple real time application and multiple users. These processors are referred as sites, nodes, computers and so on.
Network operating System: Network Operating System runs on a server and and provides server the capability to manage data, users, groups, security, applications, and other networking functions. Examples: Microsoft Windows Server 2003
Real Time operating System: Real time system is defines as a data processing system in which the time interval required to process and respond to inputs is so small that it controls the environment. Real time processing is always on line whereas on line system need not be real time. example: Air traffic control system etc.
Hard real-time systems: Hard real-time systems guarantee that critical tasks complete on time. In hard real-time systems secondary storage is limited or missing with data stored in ROM
Soft real-time systems: Soft real time systems are less restrictive. Critical real-time task gets priority over other tasks and retains the priority until it completes. For example, Multimedia, virtual reality,

Operating System - Properties:
Batch processing: Batch processing is a technique in which Operating System collects one programs and data together in a batch before processing starts. OS defines a job which has predefined sequence of commands, programs and data as a single unit. When job completes its execution, its memory is released and the output for the job gets copied into an output spool for later printing or processing.
Multitasking: Multitasking refers to term where multiple jobs are executed by the CPU simultaneously by switching between them. Switches occur so frequently that the users may interact with each program while it is running.
Multiprogramming: When two or more programs are residing in memory at the same time, then sharing the processor is referred to the multiprogramming. Multiprogramming assumes a single shared processor. Multiprogramming increases CPU utilization by organizing jobs so that the CPU always has one to execute.
Interactivity: Interactivity refers that a User is capable to interact with computer system.
Real Time System: Real time systems represents are usually dedicated, embedded systems. Operating Systems typically read from and react to sensor data.
Distributed Environment: Distributed environment refers to multiple independent CPUs or processors in a computer system.
Spooling: Spooling is an acronym for simultaneous peripheral operations on line. Spooling refers to putting data of various I/O jobs in a buffer. This buffer is a special area in memory or hard disk which is accessible to I/O devices.

Process:
A process is a program in execution. The execution of a process must progress in a sequential fashion
Object Program: Code to be executed.
Data: Data to be used for executing the program.
Resources: While executing the program, it may require some resources.
Status: Verifies the status of the process execution.A process can run to completion only when all requested resources have been allocated to the process.
Program:
Program contains the instructions to be executed by processor. A program takes a space at single place in main memory and continues to stay there.
New - The process is being created.
Ready - The process is waiting to be assigned to a processor. Ready processes are waiting to have the processor allocated to them by the operating system so that they can run.
Running: Process instructions are being executed (i.e. The process that is currently being executed).
Waiting: The process is waiting for some event to occur (such as the completion of an I/O operation).
Terminated: The process has finished execution.
Process Control Block:
Each process is represented in the operating system by a data structure  called process control block (PCB) or task control block.
Pointer: Pointer points to another process control block. Pointer is used for maintaining the scheduling list.
Process State: Process state may be new, ready, running, waiting and so on.
Program Counter: Program Counter indicates the address of the next instruction to be executed for this process.
CPU registers: CPU registers include general purpose register, stack pointers, index registers and accumulators etc.
Memory management information: This information may include the value of base and limit registers, the page tables etc. This information is useful for deallocating the memory when the process terminates.
Accounting information: This information includes the amount of CPU and real time used, time limits, job or process numbers, account numbers etc.

Process Scheduling:
The process scheduling is the activity of the process manager that handles the removal of the running process from the CPU and the selection of another process on the basis of a particular strategy.
Scheduling queues refers to queues of processes or devices. When the process enters into the system, then this process is put into a job queue. Device queue is a queue for which multiple processes are waiting for a particular I/O device
A newly arrived process is put in the ready queue. Once the CPU is assigned to a process, then that process will execute. The process could issue an I/O request and then it would be placed in an I/O queue.
Schedulers: Schedulers are special system softwares which handles process scheduling in various ways
Long Term Scheduler: It is also called job scheduler. Job scheduler selects processes from the queue and loads them into memory for execution. Time-sharing operating systems have no long term scheduler.
Short Term Scheduler: It is also called CPU scheduler. CPU scheduler selects process among the processes that are ready to execute and allocates CPU to one of them. Short term scheduler also known as dispatcher
Medium Term Scheduler: Medium term scheduling is part of the swapping. Running process may become suspended if it makes an I/O request. Suspended processes cannot make any progress towards completion. It removes the processes from the memory. It reduces the degree of multiprogramming.
Context Switch: A context switch is the mechanism to store and restore the state or context of a CPU in Process Control block so that a process execution can be resumed from the same point at a later time. Using this technique a context switcher enables multiple processes to share a single CPU.

Scheduling algorithms:
Throughput: number of processes that complete their execution per time unit
Turnaround time: amount of time to execute a particular process ie, The sum total of waiting time & execution time
Waiting time: amount of time a process has been waiting in the ready queue. ie, Service Time - Arrival Time
Response time: amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment)
First Come First Serve (FCFS):
Jobs are executed on first come, first serve basis. Easy to understand and implement. Poor in performance as average wait time is high.
Shortest Job First (SJF):
Processer should know in advance how much time process will take.  This algorithm associates with each process the length of the process's next CPU burst.When the CPU is available, it is assigned to the process that has the smallest next CPU burst. If the next CPU bursts of two processes are the same, FCFS scheduling is used.
The SJF algorithm can be either pre-emptive or nonpreemptive. The choice arises when a new process arrives at the ready queue while a previous process is still executing. The next CPU burst of the newly arrived process may be shorter than what is left of the currently executing process. A pre-emptive SJF algorithm will preempt the currently executing process, whereas a nonpreemptive SJF algorithm will allow the currently running process to finish its CPU burst.
Priority Based Scheduling:
A priority is associated with each process, and the CPU is allocated to the process with the highest priority. Equal-priority processes are scheduled in FCFS order. Generally the larger the CPU burst, the lower the priority, and vice versa.
Internally defined priorities use some measurable quantity or quantities to compute the priority of a process. External priorities are set by criteria outside the OS, such as the importance of the process, the type and amount of funds being paid for computer use.
A pre-emptive priority scheduling algorithm will preempt the CPU if the priority of the newly arrived process is higher than the priority of the currently running process. A nonpreemptive priority scheduling algorithm will simply put the new process at the head of the ready queue.
A major problem with priority scheduling algorithms is indefinite blocking, or starvation. A priority scheduling algorithm can leave some low priority processes waiting indefinitely.
A solution to the problem of indefinite blockage of low-priority processes is aging. Aging is a technique of gradually increasing the priority of processes that wait in the system for a long time.
Round Robin Scheduling:
Each process is provided a fix time to execute called quantum. We keep the ready queue as a FIFO queue of processes.New processes are added to the tail of the ready queue. Once a process is executed for given time period. Process is preempted and other process executes for given time period. Context switching is used to save states of preempted processes.
Multi Queue Scheduling:
Multiple queues are maintained for processes. The processes are permanently assigned to one queue, generally based on some property of the process, such as memory size, process priority, or process type. Each queue has absolute priority over lower-priority queues and also each queue has its own scheduling algorithm.

Multi-Threading:
A thread is a flow of execution through the process code, with its own program counter, system registers and stack. A thread is also called a light weight process. Threads provide a way to improve application performance through parallelism.Threads are implemented in following two ways
User Level Threads -- application manages thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application begins with a single thread and begins running in that thread.
Kernel Level Threads --  thread management done by the Kernel. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process.Kernel threads are generally slower to create and manage than the user threads.
Multithreading Models -- Some operating system provide a combined user level thread and Kernel level thread facility. Solaris is a good example of this combined approach. In a combined system, multiple threads within the same application can run in parallel on multiple processors and a blocking system call need not block the entire process. Multithreading models are three types
Many to Many Model -- In this model, many user level threads multiplexes to the Kernel thread of smaller or equal numbers. In this model, developers can create as many user threads as necessary and the corresponding Kernel threads can run in parallels on a multiprocessor.
Many to One Model -- Many to one model maps many user level threads to one Kernel level thread. Thread management is done in user space. Only one thread can access the Kernel at a time,so multiple threads are unable to run in parallel on multiprocessors.
One to One Model -- There is one to one relationship of user level thread to the kernel level thread. It also another thread to run when a thread makes a blocking system call. It support multiple thread to execute in parallel on microprocessors.

Memory Management:
Memory management keeps track of each and every memory location either it is allocated to some process or it is free. Memory management provides protection by using two registers, a base register and a limit register. The base register holds the smallest legal physical memory address and the limit register specifies the size of the range.
Instructions and data to memory addresses can be done in Compile time, Load time orExecution time
Dynamic Loading: In dynamic loading, a routine of a program is not loaded until it is called by the program. The main program is loaded into memory and is executed. Other routines methods or modules are loaded on request.
Dynamic Linking: Linking is the process of collecting and combining various modules of code and data into a executable file that can be loaded into memory and executed. When it combines the libraries at load time, the linking is called static linking and when this linking is done at the time of execution, it is called as dynamic linking.In static linking, libraries linked at compile time, so program code size becomes bigger whereas in dynamic linking libraries linked at execution time so program code size remains smaller.
Logical versus Physical Address Space: An address generated by the CPU is a logical address whereas address actually available on memory unit is a physical address. Virtual and physical addresses differ in execution-time address-binding scheme.The run-time mapping from virtual to physical address is done by the memory management unit (MMU) which is a hardware device
Swapping: Swapping is a mechanism in which a process can be swapped temporarily out of main memory to a backing store , and then brought back into memory for continued execution.
Main memory usually has two partitions - Low Memory -- Operating system resides in this memory and High Memory -- User processes then held in high memory.
memory allocation mechanism:
Single-partition allocation     In this type of allocation, relocation-register scheme is used. Relocation register contains value of smallest physical address whereas limit register contains range of logical addresses. Each logical address must be less than the limit register.
Multiple-partition allocation     In this type of allocation, main memory is divided into a number of fixed-sized partitions where each partition should contain only one process. When a partition is free, a process is selected from the input queue and is loaded into the free partition.
Fragmentation: As processes are loaded and removed from memory, the free memory space is broken into little pieces. It happens after sometimes that processes can not be allocated to memory blocks considering their small size and memory blocks remains unused. This problem is known as Fragmentation.
External fragmentation : Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.
Internal fragmentation : Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.
Paging: External fragmentation is avoided by using paging technique. Paging is a technique in which physical memory is broken into blocks of the same size called pages (size is power of 2, between 512 bytes and 8192 bytes). When a process is to be executed, it's corresponding pages are loaded into any available memory frames. Address generated by CPU is divided into
Page number (p) -- page number is used as an index into a page table which contains base address of each page in physical memory.
Page offset (d) -- page offset is combined with base address to define the physical memory address.
Segmentation: Segmentation is a technique to break memory into logical pieces where each piece represents a group of related information. Segmentation can be implemented using or without using paging. Address generated by CPU is divided into
Segment number (s) -- segment number is used as an index into a segment table which contains base address of each segment in physical memory and a limit of segment.
Segment offset (o) -- segment offset is first checked against limit and then is combined with base address to define the physical memory address.
Virtual Memory:
Virtual memory is a technique that allows the execution of processes which are not completely available in memory. Virtual memory is commonly implemented by demand paging. It can also be implemented in a segmentation system or Demand segmentation
Demand Paging:
A demand paging system is quite similar to a paging system with swapping. Rather than swapping the entire process into memory, however, we use a lazy swapper called pager. When a process is to be swapped in, the pager guesses which pages will be used before the process is swapped out again. Thus, it avoids reading into memory pages that will not be used in anyway, decreasing the swap time and the amount of physical memory needed.
Hardware support is required to distinguish between those pages that are in memory and those pages that are on the disk using the valid-invalid bit scheme. Access to a page marked invalid causes a page-fault trap. This trap is the result of the operating system's failure to bring the desired page into memory. It is handled by modern os
Page Replacement Algorithm: Page replacement algorithms are the techniques using which Operating System decides which memory pages to swap out, write to disk when a page of memory needs to be allocated. Paging happens whenever a page fault occurs and a free page cannot be used for allocation purpose
Reference String: The string of memory references is called reference string. Reference strings are generated artificially or by tracing a given system and recording the address of each memory reference.
First In First Out (FIFO) algorithm:  Oldest page in main memory is the one which will be selected for replacement. Easy to implement, keep a list, replace pages from the tail and add new pages at the head.
Optimal Page algorithm: An optimal page-replacement algorithm has the lowest page-fault rate of all algorithms. when a page needs to be swapped in, the operating system swaps out the page whose next use will occur farthest in the future.
Least Recently Used (LRU) algorithm: Page which has not been used for the longest time in main memory is the one which will be selected for replacement. Easy to implement, keep a list, replace pages by looking back into time.
Page Buffering algorithm: To get process start quickly, keep a pool of free frames.On page fault, select a page to be replaced.Write new page in the frame of free pool, mark the page table and restart the process.Now write the dirty page out of disk and place the frame holding replaced page in free pool.
Least frequently Used(LFU) algorithm: Page with the smallest count is the one which will be selected for replacement.This algorithm suffers from the situation in which a page is used heavily during the initial phase of a process, but then is never used again.
Most frequently Used(MFU) algorithm: This algorithm is based on the argument that the page with the smallest count was probably just brought in and has yet to be used.

I/O Hardware:
Computers operate on many kinds of devices. A device communicates with a computer system by sending signals over a cable or even through the air.The device communicates with the machine via a connection point termed a port (for example, a serial port).
A bus is a set of wires and a rigidly defined protocol that specifies a set of messages that can be sent on the wires.When device A has a cable that plugs into device B, and device B has a cable that plugs into device C, and device C plugs into a port on the computer, this arrangement is called a daisy chain.
Controller: A controller is a collection of electronics that can operate a port, a bus, or a device. The SCSI bus controller is often implemented as a separate circuit board (a host adapter) that plugs into the computer.
I/O port: An I/O port typically consists of four registers, called the status , control, data-in, and data-out registers.
Polling: Polling is a process by which a host waits for controller response.It is a looping process, reading the status register over and over until the busy bit of status register becomes clear
I/O Devices can be categorized into following category.
Human Readable devices are suitable for communicating with the computer user. Examples are printers, video display terminals, keyboard etc.
Machine Readable devices are suitable for communicating with electronic equipment. Examples are disk and tape drives, sensors, controllers and actuators.
Communication devices are suitable for communicating with remote devices. Examples are digital line drivers and modems.
Direct Memory Access (DMA):
A special control unit is used to transfer block of data directly between an external device and the main memory, without intervention by the processor. This approach is called Direct Memory Access(DMA). DMA can be used with either polling or interrupt software.
When used with an interrupt, the CPU is notified only after the entire block of data has been transferred. For each byte or word transferred, it must provide the memory address and all the bus signals controlling the data transfer.Handshaking is a process between the DMA controller and the device controller. It is performed via wires using terms DMA request and DMA acknowledge.
Device Controllers:
network card, graphics adapter, disk controller, DVD-ROM controller, serial port, USB, sound card

I/O Softwares:
Interrupts: The CPU hardware uses an interrupt request line wire which helps CPU to sense after executing every instruction. When the CPU checks that a controller has put a signal on the interrupt request line, the CPU saves a state, such as the current value of the instruction pointer, and jumps to the interrupt handler routine at a fixed address. The interrupt handler part determines the cause of the interrupt, performs the necessary processing and executes a interrupt instruction to return the CPU to its execution state.
Most CPUs have two interrupt request lines:
non-maskable interrupt - Such kind of interrupts are reserved for events like unrecoverable memory errors.
maskable interrupt - Such interrupts can be switched off by the CPU before the execution of critical instructions that must not be interrupted.
Application I/O Interface: Application I/O Interface represents the structuring techniques and interfaces for the operating system to enable I/O devices to be treated in a standard, uniform way.
Following are the characteristics of I/O interfaces with respected to devices.
Character-stream / block, Sequential / random-access, Synchronous / asynchronous, Sharable / dedicated, Speed of operation, Read-write, read only, or write only
Clocks: Clocks are also called timers. The clock software takes the form of a device driver though a clock is neither a blocking device nor a character based device. The clock software is the clock driver.
Kernel I/O Subsystem: Kernel I/O Subsystem is responsible to provide many services related to I/O such as Scheduling, Buffering, Caching, Spooling and Device Reservation, Error Handling
Device driver: Device driver is a program or routine developed for an I/O device. A device driver implements I/O operations or behaviours on a specific class of devices. In the layered structure of I/O system, device driver lies between interrupt handler and device independent I/O software.

File System:
File: A file is a named collection of related information that is recorded on secondary storage such as magnetic disks, magnetic tapes and optical disks.In general, a file is a sequence of bits, bytes, lines or records whose meaning is defined by the files creator and user.
File Structure: File structure is a structure, which is according to a required format that operating system can understand.
File Type: File type refers to the ability of the operating system to distinguish different types of file such as text files source files and binary files etc.
Ordinary files: These are the files that contain user information.
Directory files: These files contain list of file names and other information related to these files.
Special files: These files represent physical device like disks, terminals, printers, networks, tape drive etc. These files are of two types - Character special files [terminals or printers] and Block special files [disks and tapes]
File Access Mechanisms: File access mechanism refers to the manner in which the records of a file may be accessed.
Sequential access: The information in the file is processed in order, one record after the other. Example: Compilers usually access files in this fashion.
Direct/Random access: Each record has its own address on the file with by the help of which it can be directly accessed for reading or writing.The records need not be in any sequence within the file and they need not be in adjacent locations on the storage medium.
Indexed sequential access: An index is created for each file which contains pointers to various blocks. Index is searched sequentially and its pointer is used to access the file directly.
Space Allocation: Files are allocated disk spaces by operating system.
Contiguous Allocation: Each file occupy a contiguous address space on disk. Assigned disk address is in linear order. External fragmentation is a major issue with this type of allocation technique.
Linked Allocation: Each file carries a list of links to disk blocks. Directory contains link / pointer to first block of a file. Effectively used in sequential access file. Inefficient in case of direct access file.
Indexed Allocation: Provides solutions to problems of contigous and linked allocation. A index block is created having all pointers to files. Each file has its own index block which stores the addresses of disk space occupied by the file. Directory contains the addresses of index blocks of files.

Security:
Security refers to providing a protection system to computer system resources such as CPU, memory, disk, software programs and most importantly data/information stored in the computer system.
Authentication:
Authentication refers to identifying the each user of the system and associating the executing programs with those users. Operating Systems generally identifies/authenticates users using following three ways:
Username / Password, User card/key, User attribute [fingerprint/ eye retina pattern/ signature]
One Time passwords:
In One-Time Password system, a unique password is required every time user tries to login into the system. Once a one-time password is used then it can not be used again. One time password are implemented in various ways.
Random numbers, Secret key (User are provided a hardware device which can create a secret id mapped with user id), Network password (Some commercial applications send one time password to user on registered mobile/ email)
Program Threats:
Operating system's processes and kernel do the designated task as instructed. If a user program made these process do malicious tasks then it is known as Program Threats. Following is the list of some well known program threats.
Trojan Horse - Such program traps user login credentials and stores them to send to malicious user who can later on login to computer and can access system resources.
Trap Door - If a program which is designed to work as required, have a security hole in its code and perform illegal action without knowledge of user then it is called to have a trap door.
Logic Bomb - Logic bomb is a situation when a program misbehaves only when certain conditions met otherwise it works as a genuine program. It is harder to detect.
Virus - Virus as name suggest can replicate themselves on computer system .They are highly dangerous and can modify/delete user files, crash systems.
System Threats:
System threats refers to misuse of system services and network connections to put user in trouble. System threats can be used to launch program threats on a complete network called as program attack. Following is the list of some well known system threats.
Worm -Worm is a process which can choked down a system performance by using system resources to extreme levels.
Port Scanning - Port scanning is a mechanism or means by which a hacker can detects system vulnerabilities to make an attack on the system.
Denial of Service - Denial of service attacks normally prevents user to make legitimate use of the system.
Computer Security Classifications:
Type A     Highest Level. Uses formal design specifications and verification techniques.
Type B     Provides mandatory protection system. Have all the properties of a class C2 system. Attaches a sensitivity label to each object.It is of three types.
B1 - Maintains the security label of each object in the system.
B2 - Extends the sensitivity labels to each system resource, such as storage objects, supports covert channels and auditing of events.
B3 - Allows creating lists or user groups for access-control to grant access or revoke access to a given named object.
Type C     Provides protection and user accountability using audit capabilities. It is of two types.
 C1 - Incorporates controls so that users can protect their private information and keep other users from accidentally reading / deleting their data. UNIX versions are mostly Cl class.
C2 - Adds an individual-level access control to the capabilities of a Cl level system
Type D     Lowest level. Minimum protection. MS-DOS fall in this category.

Linux:
Linux is one of popular version of UNIX operating System. Components of Linux System
Kernel - Kernel is the core part of Linux. It is responsible for all major activities of this operating system. It is consists of various modules and it interacts directly with the underlying hardware.
System Library - System libraries are special functions or programs using which application programs or system utilities accesses Kernel's features. These libraries implements most of the functionalities of the operating system and do not requires kernel module's code access rights.
System Utility - System Utility programs are responsible to do specialized, individual level tasks.
Architecture:
Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).
Kernel - Core component of Operating System, interacts directly with hardware, provides low level services to upper layer components.
Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes commands from user and executes kernel's functions.
Utilities - Utility programs giving user most of the functionalities of an operating systems.