-->

Sunday, December 28, 2014

Create an Object using New Operator: Java

New operator is used to create a new object of an existing class and associate the object with a variable that names it. Basically new operator instantiates a class by allocating memory for a new object and returning reference to that memory.
Every class needs an object to use its member and methods by other classes. Programmer have to create that object using new operator to use functionality provided by that class. Following is the syntax to create new object of an existing class:

Class_variable =new Class_Name();

This syntax basically describes some points about new operator as below:
  • Allocates memory to class_variable for new object of class.
  • It invokes object constructor.
  • Requires only single postfix argument which calls to constructor.
  • Returns reference to memory which is usually assigned to variable of appropriate type.
Following statement will create an object of city class and allocate memory to this newly created object:

City metro;
metro = new City();

The equivalent code for the above statement that can be written in single line is:

City metro = new City();

So new operator does two things overall i.e. it first allocates memory somewhere to hold an instance of the type, and then calls a constructor to initialize an instance of the type in that newly allocated memory.

After creating new object for a class, that object can use all the members and methods defined in that class. You can assign all the properties for that class and operate available or new functions on those properties.

Monday, June 9, 2014

Managing indexes with pre-defined Query: SQL Server

In addition to creating indexes in sql server, database developer also need to maintain them to ensure their continued optimal performance. The common index maintenance tasks include disabling, enabling, renaming, and dropping an index. As a database developer, you need to regularly monitor the performance of the index and optimize it.

Disabling Indexes

When an index is disabled, the user is not able to access the index. If a clustered index is disabled then the table data is not accessible to the user. However, the data still remains in the table, but is unavailable for Data Modification Language (DML) operations until the index is dropped or rebuilt.

To rebuild and enable a disabled index, use the ALTER INDEX REBUILD statement or the CREATE INDEX WITH DROP_EXISTING statement.

The following query disables a non-clustered index, IX_EmployeeID, on the Employee table.

ALTER INDEX IX_EmployeeID
ON Employee DISABLE

Enabling Indexes

After an index is disabled, it remains in the disabled state until it is rebuilt or dropped. You can enable a disabled index by rebuilding it through one of the following methods:

  • Using the ALTER INDEX statement with the REBUILD clause
  • Using the CREATE INDEX statement with the DROP_EXISTING clause
  • Using the DBCC DBREINDEX

By using one of the preceding statements, the index is rebuilt and the index status is set to enable. You can rebuild a disabled clustered index, when the ONLINE option is set to ON.

Renaming Indexes

You can rename the current index with the help of the sp_rename system stored procedure.
The following statement renames the IX_JobCandidate_EmployeeID index on the JobCandidate table to IX_EmployeeID.

EXEC sp_rename
‘HumanResources.JobCandidate.IX_JobCandidate_EmployeeID’,
‘IX_EmployeeID’, ‘index’

Dropping Indexes

When you no longer need an index, you can remove it from a database. You cannot drop an index used by either a PRIMARY KEY or UNIQUE constraint, except by dropping the constraint.

The following statement drops the IDX_Employee_ManagerID index on the Employee table:

DROP INDEX IDX_Employee_ManagerID
ON Employee

How to Create Partition Scheme and Clustered Index: SQL Server

After creating the partition function, programmer needs to create a partition scheme to associate it with the partition function. Based on the boundary values defined in the partition function, there will be five partitions. The data of each partition is stored in a filegroup. You should have the same number of filegroups as partitions. If there are five partitions, you need to create five filegroups: fg1, fg2, fg3, fg4, fg5.

The following statements create the PSOrderDate partition scheme, associating it with the PFOrderDate partition function:

CREATE PARTITION SCHEME PSOrderDate
AS PARTITION PFOrderDate
TO (fg1, fg2, fg3, fg4, fg5)

The partition scheme, PSOrderDate, created in the preceding statement directs each partition to a separate filegroup.

Creating a Clustered Index

After creating the partition scheme, you need to associate it with a clustered index. As the clustered index is created on the attribute having unique and non-null values, you can create the index on the SalesOrderID column of the SalesOrderHeader table. To create the partitioned index, you need to associate the clustered index with the partition scheme as follows:

CREATE CLUSTERED INDEX ix_SalesOrderID
ON Sales.MySalesOrderHeader (SalesOrderID)
ON PSOrderDate (OrderDate)

The preceding statement will distribute the table data into five filegroups based on the yearly data of orders stored in the OrderDate column.

How to Create Partitioned Indexes in SQL Server

In SQL Server, indexes can also be partitioned based on the value ranges. Similar to the partitioned tables, the partitioned indexes also improve query performance. Partitioning enables you to manage and access subsets of data quickly and efficiently. When indexes become very large, you can partition the data into smaller, more manageable sections as the data is spread across file groups in a database.

Consider an example. In the Adventure Works database, the SalesOrderHeader table contains the details about the order received by Adventure Works, Inc. As the data in this table is large, the query takes a long time to execute. To solve this problem, you can create a partitioned index on the table. Partitioning an index will distribute the data in the table into multiple filegroups, thereby partitioning the table. This will enable the database engine to read or write data quickly. This also helps in maintaining the data efficiently.

Partitioning is allowed only in the Enterprise Edition of SQL Server. To create a partitioned index, you need to perform the following tasks:

Creating a Partition Function

Similar to creating a partitioned table, you need to create a partition function to create a partitioned index. The partition function will determine the boundary values for creating partitions.

Consider an example. The queries on the SalesOrderHeader table are mostly base on the OrderData column. The sales manager of Adventure Works requires the details of the orders received, on a yearly basis. The table contains the details of orders for the last five years beginning from 2001. Based on this information, you can create a partition function as follows:

CREATE PARTITION FUNCTION PFOrderDate (date time)
AS RANGE RIGHT FOR VALUES (‘2002-01-01’, ‘2003-01-01’, ‘2004-01-01’, ‘2005-01-01’)

The preceding statement creates a partition function, PFOrderDate, by using the date time data type. It specifies four boundary values. Therefore, there will be five partitions. As range right is specified for partitioning, the first partition will contain data less than the first boundary value, 2002-01-01. The second partition will contain data greater than or equal to 2002-01-01 and less than or equal to 2003-01-01. Similarly, other partitions will store data.

Monday, May 26, 2014

How to Retrieve XML Data Using XQuery

In addition to FOR XML, SQL Server allows programmer to extract data stored in variables or columns with the XML data type by using XQuery. XQuery is a language that uses a set of statements and functions provided by the XML data type to extract data. As compared to the FOR XML clause of the SELECT statement, the XQuery statements allow you to extract specific parts of the XML data.

Each XQuery statement consists of two parts, prolog and body. In the prolog section, you declare the namespaces. In addition, schemas can be imported in the prolog. The body parts specifies the XML nodes to be retrieved. The XQuery language includes the following statements:

  • For: Used to iterate through a set of nodes at the same level as in an XML document.
  • Let: Used to declare variables and assign values.
  • Order by: Used to specify a sequence.
  • Where: Used to specify criteria for the data to be extracted.
  • Return: Used to specify the XML returned from a statement.

The XQuery statements also use the following functions provided by the XML data type:

Query: Used to extract XML from an XML data type. The XML to be retrieved is bicycle is manufactured at AdventureWorks, it passes through a series of work centre locations. Each work centre location produces a different cycle component. Therefore, the number of production steps varies between different work centres.

To analyse the production process, the management of AdventureWorks needs to retrieve a list of the location IDs of all the work centers, which have more than four steps. You need to generate the list displaying the location ids in the ascending order of the steps included in the work centres.

To perform this task, the database developer can create the following query:

SELECT Instructons.query
(‘ declare namespace
ns=http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions:
for $work in /ns:root/ns:Location
where count(#work/ns:step) > 4
order by count ($work/ns:step)
return
count($work/ns:step)’) AS Result
FROM Production.ProductModel
WHERE Instructions IS NOT NULL

Value: Used to return a single value from an XML document. To extract a single value, you need to specify an XQuery expression that identifies a single node and a data type of the value to be retrieved.

For example, the management of AventureWorks, Ins. Wants a list containing the product model id, product name, machine hours, and labour hours. However, not all product have production instructions. As a database developer, you have stored this data in the XML format in the ProductModel table. You can create the following query to display the results:

SELECT ProductModelID, Name, Instructions.value (‘declare namespace ns=”http//schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductManuInstructions”;
(/ns:root/ns:Location/@LaborHours) [1]’, ‘float’)AS
LaborHours,
Instructions.value(declare namespace
Ns=”http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/ProductModelManuInstructions”;
(/ns:root/ns:Location/@MachineHours) [1]’, ‘float’) AS MachineHours
FROM Production.ProductModel
WHERE Instructions IS NOT NULL

Exist: Used to check the existence of a node in an XML data. The function returns I if the specified node exists else it returns 0. For example, the management of AdventureWorks, wants the details of all the customers in the city ‘NJ’. The details of all the customers are stored in an XML format in the CustDetails table. You can use the following query to display the results:

SELECT Cust_ID, Cust_Details.exist
(‘Customer[@City=’NJ”]’) AS ‘True’ FROM CustDetails

Retrieve XML data from DataSet

How to Define Methods with Behavior: Java

Objects have behavior that is implemented by its methods. Other objects can ask an object to do something by invoking its methods. This section tells you everything you need to know about writing methods for your Java classes.

In Java, you define a class’s methods in the body of the class for which the method implements some behavior. Typically, you declare a class’s methods after its variables in the class body although this is not required.

Implementing Methods

Similar to a class implementation, a method implementation consists of two parts: the method declaration and the method body

methodDeclaration {
        methodBody
}

The Method Declaration

At minimum, a method declaration has a name and a return type indicating the data type of the value returned by the method:

returnType methodName( ) {
. . .
}

This method declaration is very basic. Methods have many other attributes such as arguments, access control, and so on.

Objects as Instances of Class

A class defines only a blueprint and its concrete version comes into effect only through objects that implement the functionality as defined by class. Recall our class example of City class. The objects created from this class will have two variables: name and population; and they will be able to represent cities. The object of City class will also have a method namely display ( ). An object of a class is typically named by a variable of the class type. For example, the program CityTrial in Example 4.7 declares the two variables metl1 and metro2 to be of type City, as follows;

City metro1, metro2;

This gives us variables of the class City, but so far there are no objects of the class. Objects are class value that are named by the variables. To obtain an object you must use the new operator to create a “new” object. For example, the following creates an object of the class City and names it with the variable metro1:

Metro = new city ( );

For now you need not go into details, simply note that the statement like:

Class-variable = new class-Name ( );

Creates a new object of the specified class and associates it with the class type variables. Since the class variable now names an object of the class, we will often refer to the class variable as an object of the class. (This is really the same usage as when we refer to an int variable n as “the integer n”, even though the integer is strictly speaking not n but the value of n.)

Unlike what we did in previous lines, the declaration of a class type variable and the creation of the object are more typically combined into one statement as follows:
City metro1 = new City( );
To instantiate an object, Java uses the keyword new.

How to Declare Member Variables in Classes: JAVA

A class’s state is represented by its member variables. You declare a class’s member variables in the body of the class. Typically, programmer declare a class’s variables before you declare its methods, although this is not required.

classDeclaration {
        member variable declarations
        method declarations
}
To declare variables that are members of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method i.e., available and accessible only inside the method.

Types


  • Class variable (static variable): A data member that is declared once for a class. All objects of the class type, share these data members, as there is single copy of them available in memory. The class variables are declared by adding keyword static in front of a variable declaration.
  • Instance variable: A data member that is created for every object of the class. For example, if there are 10 objects of a class type, there would be 10 copies of instance variables, one each for an object.
Consider the following code.


Public class sample {
        int anInt; // instance variable
        float aFloat; // instance variable
        static float anotherFloat; // class variable
};

Suppose there are five objects created for class type Sample. Then there would be five copies of variables anInt and aFloat but there would be one copy of variable anotherFloat which all five objects can share.

Notice that class variables are declared by adding a keyword static before the variable declaration. Keyword static in the variable declaration makes it class variable.

Method are similar: your classes can have instance methods and class methods. Instance methods operate on the current object’s instance variables but also have access to the class variables. Class methods (also called static methods), on the other hand, cannot access the instance variables declared within the class (unless they create a new object and access them through the object). Also, class methods can be invoked on the class, you don’t need an instance to call a class method.

A class method can be invoked by:

  • Just its name within its own class e.g., check( ).
  • Class-name.method-name outside its class e.g., Sample.check ( )

In above two lines, we assume that method check( ) is a static method in class Sample.

Implement Object-Oriented in JAVA

Sunday, May 18, 2014

How to Declare Classes with Members: JAVA

In order to bring a class into existence in Java program, it should be declared. A class is declared using keyword class. The generic syntax for class declaration in Java is:

Class   <class_name>
{
    Statements defining class come here
}

The angle-brackets < > mean these names are to be provided by the programmer and [ ] brackets mean, this part is optional. The class name must be provided while declaring a class. This is used to refer to the class whenever an instance (the object) of the class is created. The class name must be a legal identifier in Java. While naming classes, generally nouns are used and the first letter is given in uppercase e.g., City or Date etc. the curly brackets { } mark the beginning of a class and/or a method. The curly brackets are also used to specify block statements.

A class is a blueprint or prototype that you can use to create many objects. The implementation of a class is comprised of two components: the class declaration and the class body.

classDeclaration   {
    // classBody
}

When a class is declared, no memory space is allotted to it. This is because a class is simply a blueprint or logical placeholder containing objects and method. Memory space is allocated when objects of a class type are created.

The Class Declaration

The class declaration component declares the name of the class along with other attributes such as whether the class is public or not.

The Class Body

The class body follows the class declaration and is embedded with in curly braces ‘{‘ and ‘}’. The class body contains declaration for all instance variable and class variable (known collectively as member variable) for the class. In addition, the class body contains declarations and implementations for all instance methods and class methods (known collectively as methods) for the class. The following template shows the form of a class definition that is most commonly used; however, it is legal to intermix the method definitions and the instance variable declaration.
Public class class_Name    {
Instance_Variable_Declaration_1
Instance_Variable_Declaration_2
. . . . . .
Instance_Variable_Declaration_Last
Method_Definition_1
Method_Definition_2
     . . . . .
    Method_Definition_Last
}

How to Implement Object Oriented Design in JAVA

The basic unit of object-orientation in Java is the class. The class is often is described as a blueprint for an object. You can think of an object as an entity having a unique identity, characteristics and behaviour. For instance, a ceilingFan is an object : it has a unique identity ; its characteristics are : it has 3 or 4 blades, it has a motor, a colour etc. ; its behaviour is : it rotates the air at some specific speed. Similarly, a Student is an object. Its characteristics are: its rollno, name class, marks etc. Its behaviour is: it takes test, it attends classes etc.

To create an object in Java, you need a class. It allows a programmer to define all of the properties (i.e. characteristics) and methods (i.e. behaviour) that internally define an object, all of the API (Application programming interface) method that externally define an object. Therefore, we can say that a class is the BLUEPRINT of an object. A class define the types of shared characteristics, such as:
  • The set of attributes i.e. characteristics through data.
  • The set of behaviour i.e. behaviour through method/functions
In its role as a blueprint, the class specifies what an actual object will look like. But it is not an object. Objects are actually instances of classes. You can think of a class as a cookie cutter and an instance as an actual cookie. Similarly, you can think of a class as a blueprint of a house and an instance as an actual house.

Class as Basis of all Computation 

In Java, the class forms, the basis of all computation. Anything that has to exist as a part of a Java program has to exist as a part of class, whether that is a variable or a function or any other code-fragment. Unlike other OOP languages such as C++ that allows the existence of variables and functions outside any class. The reason being that Java is a pure Object Oriented Language. Here all functionality revolves around classes and object, as in real world. Therefore, if you want to use certain variable and functions in Java, you have to make them part of a class. ALL JAVA programs consist of objects (data and behaviour) that “interact” with each other by calling methods. All data is stored within objects which are instances of a class.

See, without classes can be no objects and without objects, no computation can take place in Java. Thus, classes form the basis of all computation in Java.

Defining Classes

A Java program consists of objects, from various classes, interacting with one another. Before we go into the details of how you can define classes, let’s review some of the general properties of classes. A value of class type is called an object. An object is usually referred to as an instance of the class rather than as a value of the class, but it is a value of the class type. An object is a value of the class type much like a value, such as 5, of a primitive type, like int, is a value of a variable of that type. 

However, an object typically has multiple pieces of data and has methods (action) it can take. Each object can have different data but all objects of the class have the same types of data and all objects in a class have the same methods. We generally say that data and methods belong to the object, and that is an acceptable point of view. The data certainly does belong to the object, but since all objects in a class have the same methods, it also would be correct to say that the methods actually belong to the class.
In this section we are going to learn about how to define classes in Java. Now consider the code fragment shown below that defines a class called City.

Public class City {
String name ;    // variable name will be name of the city
Long population ;    // will hold City’s population
Void display( )    {
Label1.setText(“city name :” + name) ;
Label2.setText(“population :” + population) ;
}
}

Let us examine this code line by line. The firstline Public class City Defines the name of the class which is City. The keyword class ensures that it is a class and the keyword public means it is available in entire program. When you add a top-level container frame in your GUI application, then a public class having the frame name is created in your application. In other words, the top-level frame is represented through a public class.

The brace following the public Class City
    { marks the beginning of class’ block.

The next two lines
    String name;
    Long population;
declares the data members of the class to define its characteristics.
Each of these lines declares one instance variable name. You can think of and object of the class as a complex item with instance variables inside of it. So, you can think of an instance variable as a smaller variable inside each object of the class. In this case, the instance variables are called name and population.
The copy of instance variables is created for each object of the class. The next four lines
    void display ( )
    {
        Label1.setText(“City name :” + name);
        Label2.setText(“population :” + population);
    }

Define a method of the class which defines the behaviour of the class. The name of the method is display( ). By looking at its code, you can easily make out what its functionality is like. The last line
    }
marks the end of the class’ block.

Null Statement and Character Manipulation in JAVA

In Java programs, statements are terminated with a semicolon (;). The simplest statement of them all is the empty, or null statement.
; it is a null statement

A null statement is useful in those instances where the syntax of the language requires the presence of a statement but where the logic of the program does not. We will see it in loops and their bodies.

Character Manipulation

Consider the following code. What does it print?
        :
System.out.print(“H” + “a”);
System.out.print(‘H’ + ‘a’);
        :

Aren’t you thinking that it would produce output as:    HaHa
But if you the program, you’ll find that the output produced is:    Ha169

As expected, the first call to System.out.print prints Ha. Its argument is the expression “H” + “a”, which performs the obvious string concatenation.
The second call to system.out.print is another story. Its argument is the expression ‘H’ + ‘a’. The problem is that ‘H’ and ‘a’ are char literals. Because neither operand is of type string, the + operator performs addition rather than string concatenation. Thus it adds ‘H”s value i.e. 72 and ‘a”s value I.e. 97 and gives 169. (A-Z have values 65-90; a-z have values 97-122).
You can force the + operator to perform string concatenation rather than addition by ensuring that at least one of its operands is a string. The common idiom is to begin a sequence of concatenations with the empty string (“ “), as follows:
    System.out.print(“ “ + ‘H’ + ‘a’) ;

But this approach can lead to some confusions also. Can you guess what the following statement prints?
    System.out.println(“2 + 2 = “ + 2 + 2);
---------------------------------------------------

Yes, you are right. It produces:    2 + 2 = 22
To perform the addition of expression 2+2 shown above, you need to convert it to Expression by enclosing it in parenthesis i.e. as
(2+2): System.Out.Println(“2+2 = ”+ (2+2));
The + operator performs string concatenation if and only If at least one of its operands is of type string: otherwise, it performs addition with primitive types.

Type of Statements used in JAVA

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( ; )
  • Assignment expressions
  • Any use of ++ or - -
  • Method calls
  • Object creation expressions
These kinds of statement are called expression statement. Here are some example of expression statements :

Avalue = 8933.234;                                          // assignment statement
Avalue++ ;                                                        // increment statement
System . out . println (avalue);                         // method call statement
Integer integerobject = new integer (4);           // object creation statement

In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. You’ve seen many examples of declaration statement.
Double avalue = 8933.234;            // declaration statement

A control flow statement regulates the order in which statements get executed. For loop and  if statements are both examples of control flow statements.

Block

A block is group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed. The following listing shows two blocks.
If  (character . I suppercase(achar))
{
    Labe l1 . settext (“the character” + achar + “is upper case .”) ;
}
Else
{
    Labe l1. Settext (“the character” + achar + “is lower case .”) ;
    Label2. Settext(“thank you”) ;
}

Character.isLowerCase( )    tests whether a character is in lowercase.
Character.isUpperCase( )        tests whether a character is in uppercase.
Character.toLowerCase( )        converts the case of a character to lowercase
Character.toUpperCase( )        converts the case of a character to uppercase


First Block:
 If (character.isUpperCase(achar))
{            // block1 begins
    Label1.Settext (“ The character “ + achar + “ is upper case.”) ;
}            // end of block 1
Else
 
Another Block:
{            // block2 begins
Label1.Settext(“ The character “ + achar + “ is lower case . “) ;
}            // end of block2

See, the beginning and end of blocks have been marked.
A Block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.
In this book, we shall be following conventional style where opening brace of the block is not put in a separate line, rather it is placed in continuation with the previous statement (whose part the block is).
For instance, rather than showing
If (a > b) { : }
We shall be writing
If (a > b)   {     :  }
Opening brace of the block in continuation with previous statement

Tuesday, May 13, 2014

Expression Evaluation and Compound Expression in JAVA

As discussed in earlier articles, expressions can either be pure expressions or mixed expressions. Pure expressions have all operands of same datatypes, contrary to mixed expressions that have operands of mixed datatypes.

Evaluating Pure Expressions

Pure expressions produce the result having the same datatypes as that of its operands e.g.

Int a = 5, b = 2, c;
a + b will produce result 7 of int type.
a/b will produce result 2 of int type.
Notice that it will not produce 2.5, it will produce 2.

Evaluating Mixed Expressions

In Java, when a mixed expression is evaluated, it is first divided into component sub-expressions up to the level of two operands and an operator. Then the type of sub-expression is decided keeping in mind general conversion rules. Using the results of sub-expressions, the next higher level of expression is evaluated and its type is determined. This process is continued till you get the final result of the expression.

Boolean (Logical) Expressions

The expressions that result into false or true called Boolean expressions. The Boolean expressions are combination of constants, variables and logical and relational operators. The rule for writing Boolean expressions states :
A Boolean expression may contain just one signed or unsigned variable or a constant, or it may have two or more variable or/and constant, or two or more expressions joined by valid relational and/or logical operators. Two or more variable or operators should not occur in continuation.
The following are examples of some valid Boolean expressions :
(i) x > y (ii) (y + z) >= (x/z)
(iii) (a + b) > c&& (c + d) > a (iv) (y > x) || (z<y)
(v) x||y && z (vi) (x)
(vii) (-y) (viii) (x-y)
(ix) (x > y) && ( !y < z) (x) x <= !y && z

Compound Expression

A compound expression is the one which is made up by combining two or more simple expressions with the help of operator. For example,
(a +b)  / (c +d)
Is a compound expression.
(a > b)  || (b > c)
Is example of another compound expression.

Type Conversion and its Types used in JAVA

An implicit type conversion is a conversion performed by the compiler without programmer’s intervention. An implicit conversion is applied generally whenever differing data types are intermixed in an expression (mixed mode expression), so as not to lose information.

The Java compiler converts all operands up to the type of the largest operand, which is called type promotion. This is done operation by operation, as described in the following type conversion rules
If either operand is of type double, the other is converted to double.

  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

Once these conversion rules have been applied, each pair of operands is of same type and the result of each operation is the same as the type of both operands.
The implicit type conversion wherein datatypes are promoted is known as Coercion.
Although coercion exempts the user from worrying about different datatype of operands, yet it has one disadvantage. Coercions decrease the type error detection ability of the compiler. You have already used the implicit type conversion unknowingly. Recall that you use “ “ + <number> (e.g., “ “ +5) to convert it to string.

Explicit type conversion

An explicit type conversion is user-defined that forces an expression to be specific type. The explicit conversion of an operand to a specific Type Casting. Type casting in Java is done as shown below :

(type) expression Where type is a valid Java data type to which the conversion is to be done. For example, to make sure that the expression (x + y/2) evaluates to type float, write it as: (float) (x +y /2)

Casts are often considered as operators. As an operators, a cast is unary and has the same precedence as any other unary operator.

Below is a table that indicates to which of the other primitive types a given primitive data type can be cast. The symbol C indicates that an explicit cast is required since the precision is decreasing. The symbol A indicates that the precision is increasing so an automatic cast occurs without the need for an explicit cast. N indicates that the conversion is not allowed.

Type Conversion and its Types used in JAVA

The * asterisk indicates that the least significant digits, may be lost in the conversion even though the target type allows for bigger numbers. For example, a large value in an int type value that uses all 32 bits will lose some of the lower bits when converted to float since the exponent uses 8 bits of the 32 provided for float value.

Assigning a value to a type with a greater range (e.g. from short to long) poses no problem, however, assigning a value of larger data type to a smaller data type (e.g., from double to float) may result in losing some precision.
Programmer cannot typecast a Boolean type to another primitive type and viceversa. So, we cannot cast a primitive type to an object reference, or viceversa.  

Expressions and its types used in JAVA

An expressions is composed of one or more operations. The objects of the operation(s) are referred to as operands. The operations are represented by operators. Therefore, operators, constants, and variables are the constituents of expressions.

An Expression in Java is any valid combination of operators, constants, and variables are the constituents of Java tokens. The expression in Java can be of any type
  • Arithmetic expression
  • Compound expression
  • Relational (or logical) expression
Type of operators used in an expression determine the expression type. For instance, if an expression is formed using arithmetic operator, it is an arithmetic expression; if an expression has relational and/or Boolean operators, it is a Boolean expression. An arithmetic expression always results in a number (integer or real) and a logical expression always results in a logical value i.e., either true or false.

Arithmetic Expressions

Expressions and its types used in JAVA

Arithmetic expressions can either be pure integer expressions or pure real expressions. Sometimes a mixed expression can also be formed which is a mixture of real and integer expressions.
In pure expressions, all the operands are of same type. And in mixed expressions, the operands are of mixed or different data types.
Integer expressions are formed by connecting integer constants and/or integer variables using integer arithmetic operators.  The following are valid integer expression:

final int count = 30
int I, J, K, X, Y, Z
– J, K – X, K + X – Y + count, – J + K * Y, J/Z, Z % X

Real expression are formed by connecting real constants and/or real variables using real arithmetic operators. The following are valid real expression:

final float bal = 250.3f:
float qty, amount value;
double fin, inter;

Rule for these arithmetic expressions is the same and it states that:
An arithmetic expression may contain just one numeric variable or a constant, or it may have two or more variables or/and constants, or two or more expressions joined by valid arithmetic operators. Two or more variables or operators should not occur in continuation.

Apart from variables, constants and arithmetic operators, an arithmetic expression may consist of Java’s mathematical functions that are part of Java standard library and are available through Math class defined in java.lang package. The following image lists various math functions that are defined in the Math class of Java.lang package.

You can use these math functions as per following syntax:
Math.Function_name (argument list) ---- The arguments are the values required by a function to work upon. For example, to calculate ab, you may write: math.pow(a, b)

Following are examples of valid arithmetic expressions :
Given     int a, b, c ;  float, p, q, r ; double x, y, z ;
a/b, p/q +a-c, x/y + p*a/b, Math .sqrt (b)*a) – c, Math.ceil (p) + a)/c, Math. Max (c,b) +x/y – z/q +c  

Following are example of invalid arithmetic expressions :
Given int , a, b, c ;  float, p, q, r ;   double x, y, z ;
x + * r      two operators on continuation.
q(a + b – z/4)   operator missing between q and parenthesis.
Math.pow (0, - 1)  Domain error because if base = 0 then exp should not be <= 0.
n *log (-3) + p/q  Domain error because logarithm of negative number is not possible.

Sunday, May 4, 2014

Operator Precedence and Associativity to Evaluate Expression: JAVA

Operator precedence determines the order in which expressions are evaluated. This, in some cases, can determine the overall value of the expression. For example, take the following expression:
 Y  =  6  + 4/2

Depending on whether the 6+4 expression or the 4/2 expression is evaluated first, the value of y can end up being 5 or 8. Operator precedence determines the order in which expression are evaluated, so you can predict the outcome of an expression. In general, increment and decrement expression are evaluated before arithmetic expression; arithmetic expression are evaluated before comparisons, and comparisons are evaluated before logical expression. Assignment expression are evaluated are evaluated last.

Operator Precedence and Associativity to Evaluate Expression: JAVA


Above Table shows the specific precedence of the various operators in Java. Operators further up in the table are evaluated first; operator on the same line have the same precedence and are evaluated left to right based on how they appear in the expression itself. For example, given that same expression
Y = 6 + 4/2

You now known, according to this table, that division is evaluated before addition, so the value of y will be 8.

You always can change the order in which expressions are evaluated by using parentheses around the expressions you want to evaluate first. You can nest parentheses to make sure that expressions evaluate in the order you want them to (the innermost parenthetical expressions is evaluated first.

Consider the following expression:
y = (6 + 4)/2

This results in a value of5, because the 6+4 expression is evaluated first, and then the result of that expression (10) is divided by 2.

Parentheses also can be useful in cases where the precedence of an expressions isn’t immediately clear. In other words, they can make your code easier to read. Adding parentheses doesn’t hurt, so if they help you figure out how expressions are evaluated, go ahead and use them.

Operator Associativity

There is a linked term – Operator Associativity. Associativity rules determine the grouping of operands and operators in an expression with more than one operator of the same precedence. When the operations in an expression all have the same precedence rating, the associativity rules determine the order of the operators.

For most operators, the evaluation is done left to right, e.g.
X  = a + b – c

Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c is subtracted. Again, parentheses can be used to overrule the default associativity, e. g.
X = a + (b-c);

However, the assignment and unary operators, are associated right to left, e.g.,
X += y -= -4; equivalent to X  += (y  -= (-(4) ) );

Assignment and Remaining operators 

Other Remaining Operators used in JAVA Programming

All other remaining operators except assignment operators are listed in this article. Like instance of, shift operators, bitwise and many more described with example in the article.

The following table lists the other operators that the Java programming language supports.

Remaining operators used in java

In the following lines, we are discussing some of these operators. Discussion of all these operators may be large task here.

Conditional operator ?:

Java offers a shortcut conditional operator (?:) that store a value depending upon a condition. This operator is ternary operator i.e., it requires three operands. The general form of conditional operator ?: is as follows:
expressiona1 ? expression2 : expression3

If expression1 evaluates to true i.e., 1, then the value of the whole expression is the value of expression2, otherwise, the value of whole expression is the value of expression3. For instance
result = marks >= 50  ?  ‘P’ : ‘F’ ;

The identifier result will have value ‘P’ if the test expression marks >= 50 evaluates to true otherwise result eill have value ‘F’. Following are some more examples of conditional operator ? :

6 > 4 ? 9 : 7 evaluates to 9 because test expression 6 > 4 is true.
4 == 9 ? 10 : 25 evaluates to 25 because test expression 4 == 9 is false.

The conditional operator might be fascinating you but certainly one tip regarding ? :, we would like all of you to keep in mind and which is being told in form of following tip.
Beware that the conditional operator has a low precedence.The conditional operator has a lower precedence than most other operators that may produce unexpected results sometimes. Consider the following code:
n = 500;
bonus = n + sales > 15000 ? 250 : 50 ;

The above code is trying to add n and the value 250 or 50 depending upon whether sales > 15000 is true or false. But this code will not work in the desired manner. The above code will be interpreted as follows:
bonus = (n + sales) > 15000 ? 250 : 50;

Because operator ‘+’ has higher precedence over > and ?:
Therefore, for the desired behaviour the conditional expression should be enclosed in parentheses as shown below:
bonus = n + (sales > 15000 ? 250 : 50) ;

The [ ] Operator

The square brackets are used to declare arrays, to create arrays, and to access a particular element in an array. Similar data items, such as marks of 20 student or sales of 30 salesmen etc., are combined together in the form of arrays. Here’s an example of an array declaration
Float [ ] arrayofFloats = new float[10] ;

The previous code declares an array that can hold ten floating point numbers. Here’s how you would access the 7th item in that array :
arrayOfFlooats[6];

Please note that first element of array is referred to as array-named[0] i.e., to refer to first item of array namely arrayOfFloats, we shall write arrayOfFloats[0]. We are not going into further details of arrays right now.

The . Operator

The dot (.) operator accesses instance members of an object or class members of a class.

The ( ) Operator

When declaring or calling a method, the method’s arguments are listed between parenthesis ( and ). You can specify an empty argument list by using ( ) with nothing between them.

The ( type ) Operator

This operator casts ( or “ convent “ ) a value to the specified type. You’ll see the usage of this operator a title later in this chapter, under the topic Type Conversion.

The new Operator

You can use the new operator to create a new object or a new array. You’ll find examples highlighting the usage of new operator in a later section – Objects as instances of class – in this chapter.

The instance of Operator

The instanceof operator tests whether its first operand is an instance of second.
Op1  instanceof   op2

Op1 must be the name-of-an-object and op2 must be the name -of -a –class. An object is considered to be an instance of a class if that object directly or indirectly descends from that class.

Assignment and Shorthand Assignment Operators used in JAVA with Example

Java provides some assignment and shorthand operators listed in the article with example of each. The article also explains a table with all these assignment operators provided by JAVA Programming.

Like other programming languages, Java offers an assignment operator =, to assign one value to another e.g.
int x, y, z;
x = 9;
y = 7;
z = x + y;
z = z * 2;

Java shorthand Operators

Java offers special shorthand operators that simplify the coding of a certain type of assignment statement. For example,
a = a + 10; may be written as a += 10;

The operator pair += tells the compiler to assign to a value of a + 10. This shorthand works for all the binary operators in Java (those that require two operands). The general form of Java shorthand is
var = var operator expression same as var operator = expression

Following are some examples of Java shorthands:
X   -= 10; equivalent to x = x-10;
X*=3; equivalent to x=x*3;
X /=2; equivalent to x=x/2;
X%=z; equivalent to x=x%z;

Thus, we can say (=,*=, /=, %=, -=) are assignment operators in Java. The operators (*=, /=, %=, += and -=) are called arithmetic assignment operators. One important and useful thing about such arithmetic assignment operators of Java is that they combine an arithmetic operator and an assignment operator, and eliminate the repeated operand thereby facilitate a condensed approach.

The following table lists some shortcut assignment operators and their lengthy equivalents:

Shorthand assignment operators in java


Sunday, April 27, 2014

Solve Decision-Making Expression using Logical Operators in JAVA

Relational operators often are used with logical operators (also known as conditional operators sometimes) to construct more complex decision-making expression. The Java programming language supports six conditional operators-five binary and one unary-as shown in the following image.


The logical OR operator (||)

The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to Boolean true if either of its operands evaluate to true.

This principle is used while testing evaluating expressions. Following are some examples of logical OR operation:

  • (4= =4) || (5 = =8)    results into true because first expression is true.
  • 1 = = 0 || 0 > 1         results into false because neither expression is true (both are false).
  • 5 > 8 || 5 < 2            results into false because both expression are false.
  • 1 < 0 || 8 > 0            results into true because second expression is true.

The operator || (logical OR) has lower precedence than the relational operators, thus, we don’t need to use parenthesis in these expressions.

The logical AND operator (&&)

The logical AND operator, written as &&, also combines two expressions into one. The resulting expression has the value true only if both of the original expression (its operands) are true. Following are some examples of AND operator (&&).

  • (6 == 3) && (4 == 4)           results into false because first expression is false.
  • (4 == 4) && (8 == 8)           results into true because both expressions are true.
  • 6 < 9 && 4 > 2                     results into true because both expressions are true.
  • 6 > 9 && 5 < 2                     results into true because both expressions are false.

Because logical AND operator (&&) has lower precedence than the relational operators, we don’t need to use parentheses in these expressions.

The logical NOT operator (!)

The logical NOT operator, written as "!", works on single expression or operand i.e. it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e. if the expression is true, then expression is false, and vice versa.

Following are some examples of logical NOT operation:

  • ! (5 ! = 0) results into false because 5 is non zero (i.e., true)
  • ! (5 >2) results into false because the expression 5>2 is true.
  • !(5>9)  results into true because the expression 5>9 is false.

The logical negation operator "!" has a higher precedence then any of the relational or arithmetic operators. Therefore, to negate an expression, you should enclose the expression in parentheses:

!( x > 5 ) will reverse the result of the expression x > 5
    Whereas! x > 5 is equivalent to ( ! x ) > 5

i.e., it will first reverse the truth value of x and then test whether the reverse of x’s truth value is greater than 5 or not.

Relational Operators in JAVA

Compare Values using Relational Operators in JAVA

In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands.

Java provides six relational operator for comparing numbers and characters. But they don’t work with strings. If the comparison is true, the relational expression results into the Boolean value true and to Boolean value false, if the comparison is false. The six relational operators are:

  • < (less than)
  • <= (less than or equal to)
  • == (equal to)
  • > (greater than)
  • >= (greater than or equal to) and
  • != (not equal to)

Summarizes the action of these relational operators.

Compare Values using Relational Operators in JAVA

t represents true and f represents false.
The relational operators have a lower precedence than the arithmetic operators. That means the expression
a + 5 > c – 2  ...expression 1
Corresponds to
( a + 5 ) > ( c – 2 ) ...expression 2
And not the following
a + ( 5 > c ) -2  …expression 3

Though relational operators are easy to work with, yet while working with them, sometimes you get unexpected results and behavior from your program. To avoid so, we would like you to know certain tips regarding relational operators.
Do not confuse the = and the = = operators.
A very common mistake is to use the assignment operators (=) in place of the relational operator (==). Do not confuse the testing the operator (==) with the assignment operator (=). For instance, the expression
Value = 3
Tests whether value is equal to 3? The expression has the Boolean value true if the comparison is true and Boolean false if it is false.

But the expression
Value = 3
Assigns 3 to value. The whole expression, in the case, has the value 3 because that’s the value of the left-hand side.
Avoid equality comparisons on floating-point numbers.
Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 X 5 is exactly 15, but 3.25 X 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 X 5.25 is 17.0625.

Therefore, after any calculation involving floating-point numbers, there may be a small residue error. Because of this error, you should avoid the equality and inequality comparisons on floating-point number.
The relational operators group Left-to-right i. e., a <b<c means (a <b) < c and not a < ( b < c ).

Postfix version of operators 

Thursday, March 13, 2014

How to use Default Constraint on Column in SQL

A default constraint can be used to assign a constant value to a column, and the user need not insert value for such a column. Only one default constraint can be created for a column but the column cannot be an identity column. The system-supplied values, such as USER, CURRENT_USER, and user-defined values can be assigned as defaults.

The syntax of applying the default constraint while creating a table is:

CREATE TABLE table_name
(
Col_name [CONSTRAINT constraint_name] DEFAULT (constant_expression|NULL)
(col_name [, col_name [, …]])
.
)
Where,

  • Constraint_name specifies the name of the constraint to be created.
  • Constant_expression specifies an expression that contains only constant values. This can contain a NULL value.

In the example of creating the EmployeeLeave table, you can insert a default constraint to add a default value for the LeaveType column. You can set the default leave type as PL. You can use the following statement to create the default constraint:

CREATE TABLE HumanResources.EmployeeLeave
(
EmployeeID int CONSTRAINT fkEmployeeID FOREIGN KEY REFERENCES Humanresources.Employe (EmployeeID),
LeaveStartDate datetime CONSTRAINT cpkLeaveStartDate PRIMARY LeaveEndDate datetime NOT NULL,
LeaveReason varchar(100),
LeaveType char(2) CONSTRAINT chkLeave CHECK (LeaveType IN (‘ CL’, ‘SL’, ‘PL’)) CONSTRAINT chkDefLeave DEFAULT ‘PL’)

The preceding command creates the EmployeeLeave table with a default constraint on the LeaveType column, where the default value is specified as PL. The name of the constraint is chkDefLeave.

Check on Constraints
© Copyright 2013 Computer Programming | All Right Reserved