Wednesday, March 30, 2022

this vs super in Java

1 comment:

 this vs super

  • this can be used to read all members declared within the class
  • this can all be used to read all inherited members in the direct parent class
  • this can be used in an instance method, constructor and instance block
  • this cannot be used in a static method or static initializer block
  • super can read only inherited members declared in the parent class
  • super excludes any members found in the current class
  • super always refer to the direct parent
  • this() can be used to invoke current class constructor
  • super() invokes constructor of the parent class
  • if we choose to call this() or super() , it must be the first statement in the constructor body. There can be only one call.
  • this refers to an instance of the class, while this() refers to a constructor call within the class
  • Java compiler automatically inserts a call to the no-argument constructor super() if we do not explicitly call this() or super() as the first line of a constructor.
  • static methods do not have reference to this or super

Constructor in Java

No comments:

 

Constructor

  • A special method that matches the name of the class and has no return type
  • Constructors are executed when a new instance of the class is created (new Main()). This process is called instantiation, because it creates a new instance of the class.
  • The method name and the class name should be exactly same (note that Java is case sensitive)
  • Constructors can include parameters, like arrays, primitive types or generics. But cannot include var. The below constructor will not compile.

      class Main {
        public Main( var number ) {
    
        }
      }
    
  • There can be multiple constructors in a class, provided that the constructor parameters are distinct.
  • Declaring multiple constructors with different signatures is reffered to as constructor overloading.
  • Every class in Java will have a constructor. If you didn't code it Java will include the default no-argument constructor automatically during compilation process.
  • Private Constructor is a special constructor which is declared as private. Having private constructors prevents other classes from the class. It is generally used when the class has only static methods.

      class Main {
        private Main() {
    
        }
      }
    
  • Classes with a private constructor can be extended only by an inner class, because an inner class is the only one that can access a private constructor by calling super().

Monday, March 28, 2022

Memory Management Problems

2 comments:
On a system using paging and segmentation, the virtual address space consists of upto 16 segments where each segment can be upto 2^16 bytes long. The hardware pages each segment into 512 byte pages. How many bits in the virtual address specify the following?
a) Segment Number
b) Page Number
c) Offset within page
d) Entire virtual address

Solution:
a) 4
Its given that the virtual address space consists of 16 segments. Hence 4 bits (2^4 = 16) are needed to specify the segment number.

b) 7
Given that 1 segment  = 2^16 bytes long
Also given that 1 page = 512 bytes = 2^9 bytes

Therefore 2^16 / 2^9 = 2^7 pages is there in 1 segment. Hence 7 bits are needed to specify the page number.

c) 9
Given that 1 page = 512 bytes = 2^9 bytes. Therefore to get the offset within a page we need 9 bits.

d) 20
4 + 7 + 9 = 20 bits for entire virtual address. 

or we can also explain like this. We have 16 segments and each segments can be 2^16 bytes long. Therefore, Total Virtual Address Space = 16 x 2^16 = 2^4 x 2^16 = 2^20


Taken from 

GATE Questions - DBMS - File Structures and Indexing

No comments:
Previous GATE questions with solutions on DBMS (File Structures and Indexing) - CS/IT

GATE-2013
1. An index is clustered, if
(a) it is on a set of fields that form a candidate key.
(b) it is on a set of fields that include the primary key.
(c) the data records of the file are organized in the same order as the data entries of the index.
(d) the data records of the file are organized not in the same order as the data entries of the index.

Ans: option (c)
Explanation :
With a clustered index the physical records (rows) are stored on the disk in the same order as that of index. Hence every table can have exactly one clustered index.

GATE - 2015
2. With reference to the B+ tree index of order 1 shown below, the minimum number of nodes (including the root node) that must be fetched in order to satisfy the following query: “Get all records with a search key greater than or equal to 7 and less than 15” is ________.
Ans: 5
Explanation:
In a B+ tree, data pointers are stored only at the leaf nodes. The leaf nodes contain the value of the search field as well as a pointer to the record/block that contains the record.In order to provide ordered access, the leaf nodes have been linked.
In the above question, in order to fetch all records with key values greater than or equal to 7 and less than 15, we first need to locate the leaf node that stores 7.To reach the node with key 7,we start from root with key value 9,follow left pointer to arrive at a node with key 5 (since search key 7 is less than 9). From node with key 5, we follow the right pointer to reach the leaf node with key value 7. Now we move from 7 till 15 sequentially towards right, thus traversing another 2 nodes.
Thus total number of nodes fetched in order to satisfy the query is 5.

GATE - 2015
3. A file is organized so that the ordering of data records is the same as or close to the ordering of data entries in some index. Then that index is called
(a) Dense
(b) Sparse
(c) Clustered
(d) Unclustered

Ans: option (c)
Explanation:
With a clustered index the physical records (rows) are stored on the disk in the same order as that of index . Hence every table can have exactly one clustered index.

A binary operation ⊕ on a set of integers is defined as x ⊕ y = x2 + y2 . Which one of the following statements is TRUE about ⊕?

No comments:
Q1. A binary operation ⊕ on a set of integers is defined as x ⊕ y = x2 + y2 . Which one of the following statements is TRUE about ⊕?
(A) Commutative but not associative (B) Both commutative and associative
(C) Associative but not commutative (D) Neither commutative nor associative

Ans: option (A)
Explanation:
A binary operation is said to be commutative if changing the order of the operands does not change the result. For example: 
Addition is commutative => (5 + 4 = 9  and  4 + 5 = 9). Similarly multiplication also.
Subtraction is not commutative => (5 - 4 = 1  and  4 - 5 = -1). Similarly division is also not commutative.

Associative Property:
Within an expression containing two or more occurrences in a row of the same associative operator, the order in which the operations are performed does not matter as long as the sequence of the operands is not changed. That is, rearranging the parentheses in such an expression will not change its value. Consider, for instance, the following equations:

For example: Addition is said to have associative property.
(5 + 3) + 1 = 5 + (3 + 1) = 9

So coming back to our problem:
Checking Commutative Property:
x ⊕ y = x2 + y2
y ⊕ x = y2 + x2
Since addition is commutative x ⊕ y = y ⊕ x
Consider x=2 and y=3
x ⊕ y = y ⊕ x = 13

Checking Associative Property:
(x ⊕ y) ⊕ z = (x ⊕ y)2 + z2
x ⊕ (y ⊕ z) = x2 + (y ⊕ z)2

Considering x=2, y=3 and z=1
(2 ⊕ 3) ⊕ 1 = (2 ⊕ 3)2 + 12 = 132 +1 = 170
2 ⊕ (3 ⊕ 1) = 22 + (3 ⊕ 1)2 = 4 + 102 = 104

Therefore ⊕ operation satisfies commutative property but not associative property.


ISRO Questions - Database Management Systems

No comments:

INDIAN SPACE RESEARCH ORGANISATION
Recruitment Entrance Test for Scientist/Engineer
Previously asked questions on Database Management Systems


ISRO 2007
1. Which commands are used to control access over objects in relational database?
(a) CASCADE & MVD
(b) GRANT & REVOKE
(c) QUE & QUIST
(d) None of these

Ans: option(b)
Explanation:
GRANT, REVOKE, and DENY are the commands which are used to control access over objects in relational data. We user the term Data Control Language (DCL) to represent these commands. 
CREATE, ALTER, DROP, TRUNCATE comes under Data Definition Language (DDL) used for defining database schemas.
CASCADE is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is either deleted or updated when the parent data is deleted or updated.
QUIST (Query lmprovement through Semantic Transformation) is a system for semantic query optimization in relational databases.
MVD means multivalued dependency - Refer: https://en.wikipedia.org/wiki/Multivalued_dependency

ISRO 2007
2. Which of the following is aggregate function in SQL?
(a) Avg
(b) Select
(c) Ordered by
(d) distinct

Ans: option(a)
Explanation:
An aggregate function allows you to perform a calculation on a set of values to return a single scalar value. Most commonly used aggregate functions are:
AVG – calculates the average of a set of values.
COUNT – counts rows in a specified table or view.
MIN – gets the minimum value in a set of values.
MAX – gets the maximum value in a set of values.
SUM – calculates the sum of values.

ISRO 2007
3. A view of database that appears to an application program is known as
(a) Schema
(b) Subschema
(c) Virtual table
(d) None of these

Ans: option (b)
Explanation:
Database schema is the design or structure or skeleton of a database. There exist schema at each level of DBMS architecture. At internal level, there exist one schema known as Physical schema, which describes how data is actually stored in memory. This is of low abstraction and it is not visible. At logical level, there exists Logical Schema which describes the structure of database and relationships in the database. Visible to or used by data base administrators or programmers.
At external level we have Sub-schema which describes the actual view of data seen by end users. This level hides many irrelevant data to users.

ISRO 2007
4. Which operation is used to extract specified columns from a table?
(a) Project
(b) Join
(c) Extract
(d) Substitute

Ans: option (a)
Explanation:
To extract specific rows or tuples from a table that satisfy a condition we use Select operation. Select operation is denoted by Greek letter sigma(σ).
For example:
σprice>1000(Products)
The above operation specifies the action of finding all tuples from Products table with price greater than 1000.

If we want to select the values of a few attributes (or fields), rather than selecting all attributes of the Table (Relation) we use project operation. Project operation is denoted by uppercase Greek letter pi().
For example:
product_name,price(Products)
The above query lists all product name and price. Note: Project operation produces a relation and since relation is a set, any duplicate rows are eliminated.

ISRO 2007
5. BCNF is not used for cases where a relation has
(a) Two (or more) candidate keys
(b) Two candidate keys and composite
(c) The candidate key overlap
(d) Two mutually exclusive foreign keys

Ans: option(d)
Explanation:

Note:
A candidate key is a column/attribute, or set of columns/attributes, in a table that can uniquely identify any database record/row/tuple. Each table may have one or more candidate keys.
Composite Key: When a key is composed of more than one column, it is known as a composite key.
Overlapping candidate keys are composite candidate keys with at least one attribute/column in common. For example if X,Y is a candidate key and X,Z is another candidate key then we can say that X,Y and X,Z are overlapping candidate keys because they share X attribute in common.

Comparable vs Comparator in Java

No comments:

Comparable Interface

is used to sort the objects of a user defined class. It contains only one method: compareTo()

public interface Comparable<T>{
  int compareTo(T o);
}

We can implement the logic of the sorting into the compareTo() method (an example is given below). compareTo() method must returns an integer based on the following rules:

  • 0 is returned when current object is equal to the argument object
  • -1 is returned when current object is smaller than the argument object
  • 1 is returned when current object is greater than the argument object
class Employee implements Comparable<Employee> {
    private String empCode;
    private String name;
    private int age;
    //not including getters, setters, constructor etc
    @Override
    public String toString() {
        return "Emp{" + name + "," + age + "," + empCode + "}";
    }

    @Override
    public int compareTo(Employee o) {
        int result = this.name.compareTo(o.getName());
        if (result != 0) return result;
        return this.getAge() - o.getAge();
    }
}

public class Main {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("402", "anu", 35));
        employees.add(new Employee("399", "binoy", 32));
        employees.add(new Employee("400", "anu", 31));
        //printing before sort
        System.out.println(employees); //outputs [Emp{anu,35,402}, Emp{binoy,32,399}, Emp{anu,31,400}]
        Collections.sort(employees);
        //printing after sort
        System.out.println(employees); //outputs [Emp{anu,31,400}, Emp{anu,35,402}, Emp{binoy,32,399}]
    }
}

Comparator Interface

Comparator is also an interface which is used to sort the objects of a user defined class. It contains compare() method. Using Comparable interface we can implement only one sorting logic. What if we need to implement sorting logic based on other data members also. At that time Comparator becomes handy. In the above example, of Comparable interface, if we need to sort the employees based on their employee code (empCode). Then we can implement it by modifying the main code as shown below:

//sorting based on empCode
Comparator<Employee> comparatorByEmpCode = (e1, e2) -> e1.getEmpCode().compareTo(e2.getEmpCode());
Collections.sort(employees, comparatorByEmpCode);
System.out.println(employees); //outputs [Emp{binoy,32,399}, Emp{anu,31,400}, Emp{anu,35,402}]

We can also combine the comparators to get a particular sorting sequence. For example say we need to display the employee based on their name. But when name is same then the employee with smallest age will be listed first. Find the example below:-

Comparator<Employee> comparatorByName = Comparator.comparing(Employee::getName);
Comparator<Employee> comparatorByAge = Comparator.comparing(Employee::getAge);
Comparator<Employee> comparatorCombined = comparatorByName.thenComparing(comparatorByAge);
Collections.sort(employees, comparatorCombined);
System.out.println(employees);

Comparable vs Comparator

As seen above both are used for sorting purposes. The differences between them are as follows:

  • Comparable provides only a single sorting logic whereas with the help of Comparator we can implement multiple sorting logic.
  • Comparable has compareTo() method with a single parameter. Comparator has compare() method with two parameters
  • Comparable is present in java.lang package while Comparator is present in java.util package
  • To implement sorting using Comparable we need to modify the class, but in the case of Comparator we do not need to modify the class.
  • If a class implements Comparable interface then collection of that object can be sorted using Collections.sort() or Arrays.sort() method. They will be sorted based on the logic defined by compareTo() method.