Category Archives: Programming language

Programming language is a formal language designed to perform processes that can be carried out by machines

Programming language

Programming language

A programming language can be any artificial language that can be used to define a sequence of instructions for processing on a machine (industrial machinery, a computer, a tablet, a mobile)

It is generally assumed that the translation of the instructions into a code comprising the machine must be completely systematic. It is usually the machine that performs the translation

Low level language

At a very low level, microprocessors exclusively process binary electronic signals. Giving a microprocessor instruction actually involves sending series of a few and zeros spaced in time in a given way. This sequence of signals is called machine code

The code typically represents data and instructions for manipulating it. An easier way to understand machine code is by giving each statement a mnemonic, such as STORE, ADD, or JUMP. This abstraction results in the assembler, a very low-level language that is specific to each microprocessor

The low level languages allow you to create programs that are very fast, but difficult to understand. The most important thing is the fact that programs written in low level are practically specific to each processor. If you want to run the program on another machine with other technology, you will need to rewrite the program from scratch

High level language

Machines are generally thought to perform calculation or word processing tasks. The description above is just a very schematic way to see how they work. There is a high level of abstraction between what the machine is asked to do and what it really understands. There is also a complex relationship between high level languages and machine code

The high level languages are easier to understand than machine code because they are made up of elements of natural languages, such as English. In BASIC (one of the high-level languages best known for their simplicity of learning), commands such as 'IF COUNTER s 10 THEN STOP' can be used to ask the machine to stop if the COUNTER variable is equal to 10. Unfortunately for many people this way of working is a little frustrating, given that even though machines seem to understand natural language, they actually do so in a rigid and systematic way

Interpreters and compilers

Translating a series of assembly language statements (source code) into machine code (or object code) is not a very complicated process and is typically performed by a special program called a compiler. The translation of high level source code into machine code is also done with a compiler, in this case this program will be more complex, or by an interpreter

A compiler creates a list of machine code instructions, the object code, based on a source code. The resulting object code is an executable program that can already work on the machine, but that can cause it to crash if it is not well designed

The interpreters, on the other hand, they are slower than compilers because they do not produce an object code, but run through the source code one line at a time. Each line is translated into machine code and executed. When the line is read a second time, as in the case of programs where parts of the code are reused, it must be recompiled. Although this process is slower, it is less likely to cause unwanted locks on the machine

Assembler

Assembler

The assembly language is a low level language whose instructions usually correspond one by one to the instructions of the computer, and with the possibility to be able to define, for example, macroinstrucciones

This language is totally dependent on the processor model

To be able to study this language with a real microprocessor has been chosen the 8086, as it is one of the most used today on PC type computers

The main feature of that microprocessor is that it is capable of working with 16 bit operands

PC-type computers use the basic 16 bit operations of the 8086, and if the processor is 32 bit, a new repertoire of 32 bit operations is added to it. If it is 64 bit then the repertoire of operations included are 16 bit, 32 bit and a new 64 bit repertoire

Basic architecture of the 8086

The internal architecture of the 8086 consists of two distinct parts: the Execution Unit and the Interface Unit with the bus

The main task of the Execution Unit is to execute the statements it extracts from the queue, where they arrive from the MP (Main Memory)

The main job of the Interface Unit with the bus is to search and bring the MP instructions. To do this you will need to generate the address of the statement to be executed

General records or data

There are 4 registers of 16 bit and each one has a specific utility:

  • AX
    Accumulator record, used with arithmetic operations
  • BX
    Base record, used to access vectors, tables, etc
    Through the use of a base address that indicates which is the first element and a direction of displacement which is the value that is added to the base address in order to reach the desired item
  • CX
    Counter record, used to count in loops and repetitive type instructions
  • DX
    Data logging, has two particular uses

    1. Complement the AX register in the arithmetic operations of multiplication and division
    2. Contains port addresses for input/output instructions

These 4 records have the following common property, although they are 16 bits, each can be considered as 2 separate 8 bit records. In this way we can designate the highest or most significant bits as Hight (the record is renamed with H at the end: AH, BH, CH, DH) and the lowest or least significant ones as Lower (the record is renamed with L at the end: AL, BL, CL, DL)

Segment records: Segmentation

There are 4 registers of 16 bit and each one has a specific utility:

  • CS
    Code segment, is the one that defines the memory zone where the instructions to be executed or program are located
  • DS
    Data segment, is the one that defines the area where the data to be used in the program is located
  • SS
    Stack or stack segment, defines the memory zone to use as a stack
  • It IS
    Extra segment, as the name implies contains the address of the extra segment, which is used when the capacity of 64 kbytes of the data segment is exceeded and to perform certain data transfers between segments

Data Bus: lines that transmit the data

Data bus width: number of bus power lines through which data is transmitted, in 8086 they are 16 bit

Address Bus: lines that transmit the addresses

Address bus width: number of bus power lines through which addresses are transmitted, in 8086 they are 16 bit

Therefore, the addresses should be 16 bits, however, on the 8086 they are 20 bits. This is because the number of different addresses would be 2^{16}=64K, but because they are very few, we are interested in them being 20 bits, since 2^{10}=1M

To calculate the physical direction we need a segment and an offset, always using hexadecimal values, so we will have a first 16 bit record to which a 0 will be added to its right and a second 16 bit record

As the notation is used Segment:Displacement

The calculation of the physical address shall be carried out:
Segment x 10(h) + Offset

Examples of Segment:Displacement

  • 0000:1050\Rightarrow 0000\cdot 10+1050=0150
  • 0010:0F50\Rightarrow 0010\cdot 10+0F50=0150
  • 0100:0050\Rightarrow 0100\cdot 10+0050=0150
  • 0105:0000\Rightarrow 0105\cdot 10+0000=0150

As can be seen in the examples, different combinations of segments and displacements can give us the same physical direction. This situation is not an error, it is because the directions of the segments overlap each other

We can have as many different segment numbers as different combinations can be made with the segment base direction. Since it has 16 bits then we have 2^{16} combinations so that we have 64\cdot K different directions

We can have as many different address numbers in each segment as different combinations can be made with scrolling. Since it has 16 bits then we have 2^{16} combinations so that we have 64\cdot K different directions

You might think that as we have 64\cdot K segments and 64\cdot K addresses, we would have 64\cdot 64=2G physical addresses. However, because the addresses are overlapped this number of addresses is incorrect

Valid segment start addresses have the property of ending in 0. Therefore, since in hexadecimal they are 10, when moving from hexadecimal to decimal we get that the number of addresses is 16

SQL

SQL

To manage the data base data model most commonly used is the relational model and to communicate with the manager can use the SQL language

It is NOT a programming language, but a database management language that has the following characteristics:

  • DDL (Data Definition Language)

    The DDL SQL provides commands for defining relation schemas, deleting and changing relationships schemes relationship

  • DML (Data Manipulation Language)

    The DML SQL includes a query language based on both relational algebra and tuple relational calculation. It also includes commands to insert, delete, and modify tuples

  • Integrity

    The DDL includes commands to specify integrity constraints that must meet the data stored in the database. Updates that violate integrity restrictions are rejected

  • Definition of views

    The SQL DDL includes commands for defining views

  • Transaction control

    SQL includes commands to specify the start and end of transactions

  • Built-in SQL and dynamic SQL

    Built-in SQL and Dynamic SQL define how SQL statements can be incorporated into general-purpose programming languages such as C, C++, Java, PL/L, Cobol, Pascal or Fortran, among others

  • Authorization
    The SQL DDL includes commands to specify access rights to relationships and views

Evolution of SQL

IBM developed the original version of SQL, called Sequel, as part of the System R project in the early 1970s by the San Jose, California

The Sequel language has evolved since then and its name has become SQL (Structured Query Language)

Today, many programming languages support the SQL language and have been set as the standard language for the use of relational databases

1981, IBM released the first commercial SQL-based program

1986, ANSI (American National Standards Institute) published a SQL standard, called SQL-86 or SQL1 and was confirmed by ISO (International Standards Organization) in 1987

1989 ANSI released an extension of the standard for SQL named SQL-89

1992, a new version of the standard called SQL-92 or SQL2 appeared

1999, a new version called SQL:1999 or SQL2000 appeared. In which regular expressions, recursive queries (for hierarchical relationships), triggers, and some object-oriented features were added

2003, a new version called SQL:2003 appeared. In which some XML features, changes in functions, standardization of the sequence object and autonumeric columns were added

2005, a new version called SQL:2005 appeared and corresponds to the ISO/IEC 9075-14:2005 standard. Defining how SQL can be used in conjunction with XML:

  • Import and save XML data into a SQL database, manipulating it within the database and publishing conventional XML and SQL data in XML
  • Facilities that allow applications to integrate into their SQL code the use of XQuery, XML query language published by the World Wide Web Consortium (W3C) for concurrent access to ordinary SQL data and XML documents

2008, a new version called SQL:2008 appeared. In which the use of the ORDER BY clause was added outside the cursors definitions. Including triggers of the INSTEAD OF type. And the inclusion of the TRUNCATE judgment

2011, a new version called SQL:2011 appeared. In which the temporary data (PERIOD FOR) and improvements in the window functions and the FETCH clause were added

2016, a new version called SQL:2016 appeared. In which the search was added using patterns, polymorphic table functions and compatibility with JSON files

DDL

Data Definition Language (DDL)

Data Definition Language (DDL) is responsible for modifying the structure of database objects

Includes orders to modify, delete, or define relationships (tables) in which database data is stored

There are four basic operations:

Definition of data

The relationship set for each database must be specified in the system in terms of a data definition language (DDL)

The SQL DDL not only allows the specification of a set of relationships, but also information regarding those relationships, including:

  • The outline of each relationship
  • The value domain associated with each attribute
  • Integrity restrictions
  • The set of indexes that must be maintained for each relationship
  • The security and authorization information for each relationship
  • The physical storage structure of each relationship on disk

Basic types of domains

The SQL standard supports a wide variety of predefined domain types:

  • CHAR(n)

    A fixed length character string, with a length n specified by the user. You can also use the full word character

  • VARCHAR(n)

    A variable length character string with a maximum length n specified by the user. The complete form, character varying, is equivalent

  • INT

    An integer (a finite subset of computer dependent integers). The whole word, integer, is equivalent

  • SMALLINT

    A small integer (a computer dependent subset of the entire domain type)

  • NUMERIC(p, d)

    A fixed comma number, the accuracy of which is specified by the user. The number is made up of p digits (plus the sign) and those p digits, d belongs to the decimal part

  • DOUBLE

    A floating-point number and double precision floating point numbers, with computer dependent precision

  • FLOAT(n)

    A floating point number whose accuracy is, at least n digits

  • DATE

    Date type data, with an accuracy of up to second

Basic definition of schemes

CREATE TABLE

Relationships are defined by the command CREATE TABLE:

\text{CREATE TABLE r} (\\ A_1 D_1, \cdots, A_n D_n,\\ \{rest-integrity_1\}, \cdots, \{rest-integrity_k\} )

Where r is the name of relationship, every Ai is the name of an attribute in the relationship scheme r and Di is the domain type of the attribute domain values Ai

There are several valid integrity restrictions

One of the most commonly used is the primary key (primary key), which takes the following form:

\text{primary key}(A_{j1}, \cdots, A_{jm})

The primary key specification determines the attributes A_{j1}, \cdots, A_{jm} form the primary key to the relationship

The attributes of the primary key must be non null and unique; that is, no tuple can have a null value for an attribute of the primary key and no pair of tuples in the relationship can be equal across all attributes of the primary key

Although the primary key specification is optional, it is usually a good idea to specify a primary key for each relationship

The example created a relationship called acount in which the attributes have been defined:

number_acount, you can save a word of up to 10 characters
name_branch, you can save a word of up to 15 characters
balance, you can save a decimal number with 12 integers and 2 decimal places
And with the restriction on number_acount as the primary key to the relationship

If a newly inserted or newly modified tuple in a relationship contains null values for any of the attributes that are part of the primary key, or if they have the same value as another tuple in the relationship, SQL will report the error and prevent the update

The example created another relationship called client in which the attributes have been defined:

number_acount, you can save a word of up to 10 characters
name_client, you can save a word of up to 15 characters
And with the restriction on number_acount as the primary key to the relationship

As can be seen we can create more than one relationship

DROP TABLE

The command is used to delete a relationship from the database DROP TABLE

This command removes all information about the relationship from the database

The example has removed all information about the relationship from the database acount

This command is more drastic than DELETE, which only erases your tuples while maintaining the outline of the relationship

However, DROP, if removed acount, no tuples can be reinserted into that relationship unless it is recreated with the command CREATE TABLE

ALTER TABLE

The command ALTER TABLE is used to add attributes to an existing relationship

As the value of the new attribute, all tuples in the relationship are assigned null value

The example added a new attribute

Where acount is the name of the existing relationship, year is the name of the attribute you want to add and DATETIME is the domain of the added attribute

You can also remove attributes using ALTER TABLE

The example removed the attribute we added earlier

Where acount is the name of the existing relationship and year is the name of the attribute you want to delete

In this case it is not necessary to declare the domain of the attribute to be deleted

Many database systems do not allow the deletion of attributes, although they do allow the deletion of entire tables

TRUNCATE

This command applies only to tables and its function is to clear the entire contents of the specified relationship

The advantage over the command DELETE, is that if you want to erase all the content of the relationship, it is much faster, especially if the relationship is very large

The downside is that TRUNCATE only serves when you want to remove absolutely all tuples, as the clause is not allowed WHERE

While, at first, this statement would appear to be Data Manipulation Language (DML), it is actually a DDL, because internally, the TRUNCATE command clears the table and recreates it and does not execute any transactions

In the example we've deleted all the content of the called relationship acount

DML

Data Manipulation Language (DML)

Data Manipulation Language (DML) is responsible for carrying out the tasks of querying or manipulating the data, organized by the appropriate data model

Includes commands to query, modify, delete, or define tuples (rows) that are stored in the relationships (tables) of the database

There are four basic operations:

Basic definition of schemes

Alias Operation

SQL provides an operation to rename using an alias for both relationships and attributes

It has the following syntax: original_name AS alias

The clause AS it is optional although if we write it will be clearer because it informs us that we are defining an alias

Situations where it is useful to use an alias:

  • Where we have two relationships in the clause FROM who have the same name for their attributes

    In these situations there may be ambiguity and we can use the alias operation to disassemble the attributes and make it clear which relationship they belong to

  • When we have a calculated operation that generates an attribute in the clause SELECT

  • When we have a calculated operation that generates an attribute after applying a aggregation operation

To access its attributes, you must use the alias followed by a period and the attribute name

SELECT

You can use the command SELECT to query the data stored in a database relationship

It will return a set of tuples from that relationship

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1, r_2, \cdots, r_m\\ \text{WHERE} P

Where every Ai represents an attribute, each ri a relationship and P it's a predicate

So an SQL query will have the following equivalent relational algebra expression:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p(r_1 \Theta r_2 \Theta \cdots \Theta r_m) )

If the clause is omitted WHERE, the predicate P it's always True

But unlike relational algebra expression, the result of an SQL query can contain multiple repeated tuples

When we introduce more than one relationship into the aclausula FROM, SQL will form a Cartesian product of all included relationships

The selection of relational algebra is then carried out using the predicate of the WHERE and then projects the result on the attributes of the clause SELECT

SELECT clause

The example resolved the query to get all the accounts in the relationship acount with attributes number_acount, name_branch, balance

In this case, when using DISTINCT we are forcing the repeated to be removed

The example resolved the query to get all the accounts in the relationship acount with attributes number_acount, name_branch, balance

In this case, when using ALL we are forcing the repeated ones not to be eliminated

The example replaced the command ALL by the symbol * and the attributes have been dispensed with, as the result is equivalent

The example resolved the query to get all the accounts in the relationship acount with attributes number_acount, name_branch, with an increase of 1500 in the balance

As can be seen, we can also use arithmetic expressions that operate on attributes

The example created a calculated attribute (non relationship) from those operations, giving it a name or alias to that operation, in this case it's called increase

FROM clause

The clause FROM itself defines a Cartesian product of the relationships that appear in the consultation

Because natural meeting is defined in terms of a Cartesian product, a selection, and a projection, it is relatively easy to write an SQL expression for the natural meeting

We have to write it in relational algebra as:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (r_1 \Theta r_2 \Theta \cdots \Theta r_m)

The example resolves the query to get all customers who have an account at the 'Navacerrada

For this purpose, relationships have been introduced acount (you have been assigned the alias c) and client (you have been assigned the alias cl)

Only with the clause FROM we couldn't solve the query

Since the Cartesian product is made on each of the possible couples that can be formed with the relationship acount and client

Giving us repeated results and also all those who were not from the branch of 'Navacerrada

That's why the condition that relates both relationships, the attribute, has been added number_acount

After adding it, we will have only the values that belong to the relationship, although it can still have been repeated

And equality for the attribute name_branch with the value 'Navacerrada

JOIN Clause

The example used the clause JOIN that will give us back an equivalent result

The clause JOIN allows meeting operations, which take two relationships and return another relationship

The clause can normally be used FROM for external meetings or for any situation where a meeting can be used

To distinguish whether the meeting is external, the keyword will be used OUTER and for the intern INNER

Both are optional, although it makes it clearer what kind of meeting we're using

There are four types of meeting:

  • INNER JOIN

    Returns all tuples when there is at least one match in both relationships

    The example used the clause INNER JOIN that will give us back an equivalent result

    Because as we said, the keyword INNER was optional

    However, we now have clearer that the meeting was internal

  • LEFT OUTER JOIN

    Returns all tuples in the left relationship, and the matching tuples of the right relationship

    The example used the clause LEFT JOIN that will return a result that is no longer equivalent, as they will appear nulls values

    We've dispensed with the keyword OUTER because the result is equivalent

    In this case LEFT JOIN It keeps all tuples in the left relation (acount)

    The tuples of the right relationship (client) will be displayed if there is a match with those on the left

    If values exist in the left relationship but not in the right relationship, it will display null

  • RIGHT OUTER JOIN

    Returns all tuples in the relationship on the right, and the matching tuples of the relationship on the left

    The example used the clause RIGHT JOIN that will return a result that is no longer equivalent, as they will appear nulls values

    We've dispensed with the keyword OUTER because the result is equivalent

    In this case RIGHT JOIN keeps us all the tuples of the right relationship (client)

    The tuples of the left relationship (acount) will be displayed if there is a match with those on the right

    If there are values in the right relationship but not in the left relationship, it will display null

  • FULL OUTER JOIN

    Returns all tuples of the two relationships, left and right

    The example used the clause FULL JOIN that will return a result that is no longer equivalent, as they will appear nulls values

    We've dispensed with the keyword OUTER because the result is equivalent

    In this case FULL JOIN returns all rows in the left table (acount) and the right table (client)

    It combines the outcome of the LEFT JOIN and RIGHT JOIN

    Null will appear on each of the tables alternately when there is no match

The type of assembly defines how to treat tuples of each relation that do not marry the tuple of the other relation

There are three types of conditions that apply to the meetings:

  • meeting NATURAL

    It is used when the attributes which meet relationships have the same name

    The example used the clause NATURAL JOIN which will return an equivalent result without using the condition ON

    Since the attribute number_acount It called equal relations acount and client

  • condition ON

    Its use is similar to that of the clause WHERE, but it specializes in comparing attributes of both relations

  • condition USING

    Its use is similar to that of the meeting NATURAL, because it is used when the attributes which meet relationships have the same name

    However, only return a result of the meeting, not all as the meeting does NATURAL

    The example used condition USING with the attribute number_acount, which will return a result that is no longer equivalent

    It will only return only the first match of each pair of the relationship, not all

Using conditions is mandatory meeting at external meetings, but is optional on the internal (if omitted, a Cartesian product is obtained)

WHERE clause

In the example, the query get resolved only accounts of the relationship acount that meet the condition introduced in this case in its attribute balance have a value less than 100

To achieve this we have used the clause WHERE, thanks to which we can filter the query to admitting a condition using the logical comparison operator <

Logical comparison operators
Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
= Like
<> Other than that

In the example, the query get resolved only accounts of the relationship acount that meet the condition introduced in this case in its attribute balance have a value equal to 'Navacerrada' and its attribute balance have a value less than 100

To achieve this we have used the logical connector AND

Logical connection operators
Operator Description
AND It's true if and only if the two operands are true
OR It's true if and only if the one or both operands are true
NOT Reverses the value of the operand
BETWEEN Operator

In the example, the query get resolved only accounts of the relationship acount that meet the condition introduced in this case in its attribute name_branch have a value equal to 'Navacerrada' and its attribute balance they have a value between 100 and 1000

The example used an equivalent query, using the comparison operator BETWEEN, which simplifies us some clauses WHERE

In the example it used a query negating the comparison operator NOT BETWEEN, which will return those values ​​outside that range

LIKE operator

In the example, the query get resolved only accounts of the relationship acount that meet the condition introduced in this case in its attribute name_branch have a value equal to 'Navacerrada

The example used an equivalent query, using the comparison operator LIKE, which simplifies us some clauses WHERE on allowing the use of patterns with strings

For the description of patterns we can use two special characters:

  • %

    The percentage matches any substring

  • _

    Underlining matches any character

These patterns can be combined to obtain different types of queries:

In the example it used the comparison operator LIKE using the pattern % after the text, which will return the values ​​that begin with the string 'Nava

In the example it used the comparison operator LIKE using the pattern % before and after the text, which will return values ​​that include as substring 'Nava

In the example it used the comparison operator LIKE using the pattern _ repeated three times, which will return values ​​that are exactly three characters

In the example it used the comparison operator LIKE using the pattern _ repeated three times and pattern %, Which will return to those values ​​that have the least three characters

In the example it used the comparison operator LIKE using the pattern % together with the special escape character '\' which will return those values ​​containing 'Nava%rrete

The escape character (which can be anything we choose) is used before special characters pattern to indicate that this character be treated as a normal character and not as a pattern

It is defined using the keyword escape

In the example it used the comparison operator NOT LIKE using the pattern %, which will return those values ​​that do not contain 'Nava%rrete

In this way we can also look for inconsistencies, but denying the operator LIKE

Nulls values

SQL allows the use of null values ​​to indicate the absence of information on the value of an attribute

You can use the special keyword NULL in a predicate to check if a value is null

In the example, the query get resolved all accounts whose name NO branch has been filled

The example resolved the query to get all accounts whose branch name has been filled in

As can be seen, it can also be checked the absence of nulls using the logical operator NOT

Since the predicate clauses WHERE may include Boolean operations such as AND, OR and NOT on the results of the comparisons, values NULL Boolean operations expand

AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL
OR TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL
NOT TRUE FALSE NULL
FALSE TRUE NULL

ORDER BY clause

Sometimes we need to return the information of the tuples in a certain order

SQL allows you to sort the attributes by using the clause ORDER BY

In the example it used the comparison operator ASC with clause ORDER BY for the attribute name_branch, Which will return the values ​​sorted in ascending order (in alphabetical order because it was an alphanumeric attribute) by the attribute name_branch

In the example it used the comparison operator DESC with clause ORDER BY for the attribute name_branch, Which will return the values ​​sorted in descending order (in alphabetical order because it was an alphanumeric attribute) by the attribute name_branch

The sort type returned by the comparison operators ASC and DESC depend on the type of the attribute because not ordered in the same way a number, a string or a date

If you need to order more than one attribute, we'll separated by commas and followed the comparison operator (ASC or DESC )

The default sorting method is ASC, is optional and could do without writing

Operations on sets

SQL allows operations on sets of relational algebra union \cup, intersection \cap and difference \neg

To use them we will have the only restriction that the names of the attributes of the relationships involved must be equal

UNION operation

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{UNION}\\ \text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a union will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \cup \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

The example query resolved all account numbers that exist in the bank or have a customer associated with them

Unlike the clause SELECT the operation UNION eliminates duplicate values

For this reason it is good idea to use operation UNION to create keys, because with SELECT would not get unique keys (allows repeated)

The example query resolved all account numbers that exist in the bank or have a customer associated with them

In the use operator ALL in conjunction with the operation UNION, we are allowing it to behave like a SELECT, as it supports repeated

INTERSECT operation

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{INTERSECT}\\ \text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains an intersection will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \cap \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

The example query resolved all account numbers that exist in the bank and have a customer associated with them

The operation INTERSECT eliminates duplicate values ​​and returns only those values ​​that match the relationship acount and in client at once, not just one of them

The example query resolved all account numbers that exist in the bank and have a customer associated with them

In the use operator ALL in conjunction with the operation INTERSECT, we are allowing it to behave like a SELECT, as it supports repeated

EXCEPT operation

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{EXCEPT}\\ \text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a difference will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \cap \neg (\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) ) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

The example query resolved all account numbers that exist in the bank and do not have a customer associated with them

The operation EXCEPT eliminates duplicate values ​​and returns only those values ​​that match the relationship acount but do not match client

The example query resolved all account numbers that exist in the bank and do not have a customer associated with them

In the use operator ALL in conjunction with the operation EXCEPT, we are allowing it to behave like a SELECT, as it supports repeated

IN operation

SQL lets you check the membership of tuples to a relation which is equivalent to check the membership of a set of relational algebra

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{IN}\\ (\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q)

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a membership will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \in \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

The example resolves the query to get all customers who have an account at the 'Navacerrada

Previously we solved it using the clause JOIN

But as you can see, we can also solve it using set theory

Membership will return the values and if there are none, it will show null

Resolves example query to get all customers who do not have accounts on the branch 'Navacerrada

To deny membership will return all other values ​​and should be none, will show null

The example resolves the query to get all customers who have an account at the 'Logroño‘ ó ‘Navacerrada

As can be seen, belonging or not belonging apart from a subquery as in the previous examples, also it supports sets listed

Whenever these sets are listed in the same domain as the attribute that you want to check membership

Comparison operators

SQL provides the ability to compare sets using subqueries

SOME operator

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{SOME}\\ (\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q)

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a membership will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \approx \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

Example resolves the query to get a client who has an account on the branch 'Navacerrada

Previously we solved using the operation IN

But as can be seen, we can also solve using a comparison of sets

In this case using the symbol = in front of the operator SOME to denote that they are equal

Example resolves the query to get a client who does not have an account at the branch 'Navacerrada

Although it might seem that is equivalent to the previous example NOT INT, the result may not be the same

We can also use the rest of the logical comparison operators

ANY operator

The operator can also be used ANY since it is equivalent to SOME

Early versions of SQL only allowed the operator ANY, but was added SOME to be more asemejase to natural language, as created any ambiguity in the English language

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{ANY}\\ (\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q)

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a membership will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \approx \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

We can also use the rest of the logical comparison operators

Example resolves the query to get a client who has an account on the branch 'Navacerrada

Previously we solved using the operation SOME

As seen is fully equivalent and would use only for compatibility with older versions of SQL

ALL operator

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE} P\\ \text{ALL}\\ (\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} Q)

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query that contains a membership will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_1) ) \forall \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (r_2) )

If the clause is omitted WHERE, the predicate P or Q (It depends on what is omitted), it is always true

We can also use the rest of the logical comparison operators

Resolves example query to get all customers who have accounts in the following branches'Navacerrada' (alphabetical)

Actually the use the symbol > in front of the operator ALL we are denoting that we look for all values that have an alphabetical order greater than 'Navacerrada

Repeated control

SQL lets you control whether a subquery has repeated tuples in its result

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_1\\ \text{WHERE UNIQUE}\\ (\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2, \cdots, r_n\\ \text{WHERE} P)

Where every Ai represents an attribute, each ri a relationship and P is preached

So a SQL query that contains a membership will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma \exists \prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r_2, \cdots, r_n) ) (r_1) )

If the clause is omitted WHERE, the predicate P, es siempre cierto

Formally assessment UNIQUE on a relationship is defined as false if and only if the ratio of two tuples ri and rk such that rik

Like checking ri = rk it is false if any attribute ri or rk is zero, it is possible that the outcome of UNIQUE is true even if several duplicates of the same tuple

Provided that at least one of the attributes of the tuple is null

Resolves example query to get all customers who have at most one account at the branch 'Navacerrada

This has been introduced relations account (has been assigned the alias c) and client (has been assigned the alias cl)

Only with the clause FROM we couldn't solve the query

We could have used the clause JOIN, although there may still be repeated

Why it has added the operator UNIQUE relating the two relationships with the attribute number_acount and equality for the attribute name_branch with the value 'Navacerrada

After adding them, we only values ​​pertaining to the relationship

Resolves example query to get all customers who have more than one account at the branch office 'Navacerrada

As can be seen, the denial of UNIQUE we can check more than one repeated

Aggregation functions

The aggregation functions are functions that take a collection (a set or multiset) value as input and return a single value

SQL allows for five aggregation functions:

  • AVG

    Allows the arithmetic mean of the collection, which must be numeric

    If there are nulls values at the entrance, they are ignored

    In the example query is resolved to obtain the arithmetic mean of the balance of all accounts

    It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called average

  • MIN

    It allows determine minimum value of the collection, which is not required to be numerical

    If there are nulls values at the entrance, they are ignored

    In the example query is resolved to obtain the lowest balance of all accounts

    It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called less

  • MAX

    It allows determine the maximum value of the collection, which is not required to be numerical

    If there are nulls values at the entrance, they are ignored

    In the example query is resolved to obtain the highest balance of all accounts

    It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called greater

  • SUM

    Allows the sum of the collection, which must be numeric

    If there are nulls values at the entrance, they are ignored

    In the example query is resolved to obtain the total balance of all accounts

    It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called liquid

  • COUNT

    Counts the number of elements that make up the collection, which is not required to be numerical

    If there are nulls values at the entrance, they are taken as 0

    In the example, the query get resolved many accounts are there altogether

    It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called total

GROUP BY clause

There are circumstances in which it would be desirable to apply the aggregation functions not only to a single set of tuples, but also a group of sets of tuples

In SQL we can specify by clause GROUP BY

The most common form of consultation will be:

\text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r\\ \text{WHERE} P\\ \text{GROUP BY} A_1, \cdots, A_2, \cdots, A_n\\ \text{HAVING} Q

Where every Ai represents an attribute, each ri a relationship and P, Q are predicates

So a SQL query containing a group will have the following equivalent expression of relational algebra:

\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma q (\prod_{A_1, \cdots, A_2, \cdots, A_n} (\sigma p (r) ) )

If the provisions are omitted WHERE or HAVING, the predicate P or Q (It depends on what is omitted), it is always true

In the example, the query get resolved there are many accounts in total for each branch

It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called total

In order for the grouping operation can be performed without errors we use the same order of attributes in both the clause SELECT as in GROUP BY

In case you are not going to intervene in the group, we can omit these attributes placing them on the right of those that will be used

HAVING clause

Sometimes we need a condition that applies to groups rather than tuples

To express such queries use the clause HAVING

In the example, the query get resolved there are many accounts in total branch 'Navacerrada

It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called total

It has been applied on the attribute condition name_branch with the value 'Navacerrada' using clause HAVING to apply on the grouping and not on the relationship

In the event that a clause would WHERE and one HAVING:

  1. SQL first apply the predicate clause WHERE
  2. The result will be divided into groups that satisfy the predicate clause HAVING

In the example, the query get resolved there are many accounts in total branch 'Navacerrada' and have a balance greater than 100

It was created a calculated attribute (not belonging to the relation) from these operations, assigning a name or alias to that operation, in this case it's called total

It has been applied on the attribute condition name_branch with the value 'Navacerrada

Additionally the condition applied on the attribute balance applying the grouping operation COUNT with the proviso that they are older than 100

Both have been on the clause aplicacadas HAVING

As can be seen, they can be applied without problems aggregation operations within clause HAVING but also they appear in clause SELECT

INSERT

Newly created relationships are initially empty

You can use the command INSERT to add data to the relationship

The most common way to insert query will be:

\text{INSERT INTO r}\\ \text{VALUES} (A_1, A_2, \cdots, A_n)

Where every Ai It represents an attribute, r relationship and each Pi it's a predicate

The example has solved the query to add the C-9732 has the branch 'Navacerrada' with a balance of 1200 €

The values are specified in the order in which the corresponding attributes are related in the relationship schema

The example has changed the order in which the corresponding attributes are related in the relationship schema and that is why the data has been entered in a mandatory manner, in the new order that we have specified

In this way we can choose in what order we enter the data

In the case of not introducing an attribute, SQL will try to enter a default or null value and if the primary key, notify the error and prevent the update

In the example, the query has decided to add the client 'Pedro Almodovar' for all account numbers that exist in the branch'Navacerrada' and they do not have a client associated with them

Instead of specifying a tuple it has been used as a subquery clause SELECT will allow us to specify a set of tuples

The most common form of subquery for insertion will be:

\text{INSERT INTO} r_1\\ \text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_2\\ \text{WHERE} P

Where every Ai It represents an attribute, ri relationships and P it's a predicate

The clause is evaluated first SELECT and are inserted in the relation client tuples obtained from the subquery

We must be careful to the nested subqueries use, since abusing them, could create an infinite loop subqueries and insertion would be made infinitely, being locked data base

Luckily management systems databases have mechanisms or tools for mass insertion in a controlled manner avoiding blocking of the database

UPDATE

You can use the command UPDATE to modify the values ​​of a set of tuples existing relationship

The most common form of update query is:

\text{UPDATE r}\\ \text{SET} A_1 = P_1, A_2 = P_2, \cdots, A_n = P_n

Where every Ai It represents an attribute, r relationship and each Pi it's a predicate

In the example it has been updated relationship called acount, in particular to the attribute balance we have changed their value 100

The command will update all tuples of the relationship acount

In the example they have been updated only tuples that satisfy the condition introduced in this case in its attribute number_acount have a value equal to 'C-9732

Case operator

The order of two instructions UPDATE It is important because if the order of the upgrade instructions changes we can get inconsistent data

To solve this problem we have the operator CASE

The most common form of update query is:

\text{UPDATE r}\\ \text{SET} A_1 = P_1, A_2 = P_2, \cdots, A_n = P_n

Where every Ai It represents an attribute, r relationship and each Pi is a predicate which can be replaced by the following predicate Q:

\text{CASE}\\ \text{WHEN} P_1 \text{THEN} r_1\\ \text{WHEN} P_2 \text{THEN} r_2\\ \cdots\\ \text{WHEN} P_n \text{THEN} r_n\\ \text{ELSE} r_0\\ \text{END}

Where every Pi each predicate can be satisfied, each ri the result to be used in updating

If not met any of the predicates, the result would apply r0

In the example it has been resolved update query to add 0.05 to the balance when it is less than or equal to 100 with a modification of 0.05, when it is equal to 500 with a change of 0.07 when it is greater than 1000 with a modification of 0.25 and a change of 0.01 in any other case

Clause has been used CASE to solve for the equate with the attribute balance which it was the value update

DELETE

You can use the command DELETE to erase tuples from a relationship

The example has deleted the relationship called acount

The command will clear all tuples from the relationship acount

And only in this relationship, because it is not able to work on several

The most common form of consultation will be deleted:

\text{DELETE FROM r}\\ \text{WHERE} P

Where r It represents the relationship and each P it's a predicate

In the example, only tuples that meet the introduced condition have been deleted, in this case those in their attribute balance have a value less than 100

It should be borne in mind that the command DELETE first check each tuple of the relation acount and then erase all tuples that meet the condition

It is important to perform all checks before erasing since the order in which tuples are processed can vary the erase operation

Views

Views

The views are used in situations where for safety or performance, we want to hide certain data to users

In the example, a client needs to know the number of a loan operation to its name, the 'C-9732' and the name of the branch that has processed, but for that operation does not need to see the balance or more related data

With the above query we solved what the client needed, but we gave more data than necessary and may put the bank in a situation that could be unsafe

Relationships that are not part of the logical model but are visible to users through virtual relationships are called views

Basic definition of views

CREATE VIEW

Relationships are defined by the command CREATE VIEW:

\text{CREATE VIEW v} AS r

Where r is a query expression and v is the name of the view

The example has created a view that tries to solve the problem of the above example

However, even though we have improved safety to the user not show balances, does not solve the problem, we should still do the following subquery to solve:

The example has treated the view as if it were a more

However, for the management system database it is a virtual connection being a view

Being a virtual relationship we can do query operations SELECT

But we can not do update operations as INSERT, UPDATE or DELETE

In the example we have created a view called loan(name_branch, total) that allows you to get the names of all branches and the total balance they have

As shown, it is possible to return any attribute and usually work with queries

In this case the attribute has been returned name_branch and it used the aggregation function COUNT after using clause GROUP BY with attributes name_branch and balance

In the example it defined a view from another to solve the query that retrieves all account numbers branch 'Navacerrada

So we've used the view named all_accounts

Since it is taken as a virtual relationship management system for the database to be a view

Keep in mind that nest views on themselves can produce a recursive effect and if ill defined block database falling into an infinite loop

Updating views

Generally a view can not be updated, however a management database system can allow make in individual cases

You have to consult the manual system manager databases to know what specific cases permits and how to solve it

In the event that updating is permitted, the view must meet:

  • The clause FROM only has a relationship
  • The clause SELECT only contains names of attributes of the relationship without alias, added value without specifying DISTINCT
  • Any attribute that does not appear in clause SELECT should be defined as null
  • The query must not contain aggregate functions (GROUP BY clause, HAVING clause)

DROP VIEW

You can use the command DROP VIEW to remove a view

And only from that view, as he is not able to work on several

The most common form of view deletion query will be:

\text{DROP VIEW v}

Where v is the name of the view

In the example it has deleted the view named all_accounts

WITH clause

The clause WITH was introduced in SQL: 1999 standard and allows you to define a temporary view

This temporary view can only be used in the query which has been defined

The most common way is:

\text{WITH} v \text{AS} r_0\newline\\ \text{SELECT} A_1, \cdots, A_2, \cdots, A_n\\ \text{FROM} r_0, r_1, r_2, \cdots, r_m, r\\ \text{WHERE} P

Where every Ai represents an attribute, each ri a relationship (r0 is a query), P is a predicate and v is the name of the temporary view

This example is equivalent to the view that we saw in a previous example

Only this time we have not used a defined view in the database

We have used a defined time view with clause WITH

Transactions

Transactions

The transactions They are a sequence of instructions to query or update

The SQL standard specifies that a transaction implicitly begins when a SQL statement is executed

At the end of the instruction must run one of the following SQL statements:

  • COMMIT WORK

    Validates updates made: so far and done so to become permanent in the database

    A complete turn, automatically starts the next transaction

    In the example we have created a relationship called acount and we populated with 7 tuples

    The query or update instructions are separated from each other by the symbol ; indicating that SQL is a new instruction

    At the end we have implemented COMMIT so that the changes are saved to the database

  • ROLLBACK WORK

    Causes the current transaction to be aborted, that is, it cancels all operations performed on the database

    The database returns to the initial state, before the first instruction of the transaction

    In the example we have created a relationship called acount and we populated with 7 tuples

    The query or update instructions are separated from each other by the symbol ; indicating that SQL is a new instruction

    At the end we have implemented ROLLBACK so that the changes will not be kept in the database

The key word WORK is optional in both directions, so we could skip in the examples

Use ROLLBACK It is useful when an error is detected and it is necessary to a stable state of the database

Once it executed COMMIT, it is not possible to make a ROLLBACK, as data changes become permanent

Therefore, when the database systems detect a failure (either a voltage drop, a drop of the system, a bad connection in the network), internally perform one ROLLBACK it is denied the use of the COMMIT, to prevent the loss of information

In the special case of the system crash, the ROLLBACK will be done when the system restarts

Starting with the SQL:1999 standard, the contents of a transaction can be enclosed in the following format:

\text{BEGIN}\\ S_1;\\ S_2;\\ \cdots;\\ S_n;\\ \text{END}

Where si it's a consultation instruction or an update

The example is similar to that shown above for COMMIT

However, on this occasion we have locked up the transaction in the format of the SQL:1999 standard

This way we can tell where different transactions start and end without having to look for instructions COMMIT or ROLLBACK

Java

Java

Java is a language that is purely object oriented, all code must be included in any class

It was defined by the company Sun Microsystems, which was acquired in 2009 by Oracle Corporation, formerly part of Silicon Valley, a maker of semiconductors and software; but the language remains in the public domain. In particular, Oracle offers in their website, for free, a JDK (Java Development Kit) which allows you to compile, debug, and run Java programs

If we have a program in a file programa.java we can compile it from the command line with:

This generates a collection of files extension .class, one for each class that appears in programa.java and with the name of the corresponding class

Only in one of the classes (in the active environment) must have a method called main (the main method); suppose that is in the class program, we will be able to run the program from the command line:

In the previous case, the extension would be optional

For this to work correctly, we have installed the JDK and make sure that the path stored in the variable CLASSPATH is in the path by default of the system

Normally the programs are developed in an environment of comprehensive programming that contains in addition to the functionality of the JDK, at least a program editor. Sun offers on their website an integrated environment for Java: Netbeans

The result of the compilation a java program (the files .class) is expressed in an intermediate language called bytecode

The bytecode is interpreted by the Java virtual machine (JVM), which is a program that is invoked by the command java in the command line

The different modern browsers include a JVM, so that it can run Java programs from the browser through Applets embedded within html pages

Although the Google Chrome browser has restricted its use for safety and the JVM is not included by default, in the event that the user wishes to use them, you should install a pluging to any third party or use a dedicated server for Java applications as for example Tomcat

Differences between Java and C++

The syntax of Java is inspired by C and is superficially very similar to C++ for that reason. But it also has important differences

Access modes in Java:

  • Each attribute or method is associated with a permission
  • In addition public and private (both without the two dots) is the mode by default package

In contrast, in C++, the default access mode is private

To use something by default in Java you use the package (packets), which is a simulation of the notion of namespace C++

To create or extend a package using the package:

  • Must be in the 1st line of the source file (everything in that file belongs to the package)
  • Will be followed by the name of the package that you want to use

If you want to use from a package, classes, attributes, methods from another package, use the command import (it is very similar to the using namespaces C++)

If the programmer does not define any package explicitly, the system creates one by default without name, that will contain all the names of the files (that do not have package explicit) that belong to that operating system directory

In conclusion, in case of the absence of packages explicit, the default access mode for a class, an attribute or a method, it is accessible from all files in a same directory

The classes in Java also have a mode of access: public, private, or default

If we find public when you define a class, has two consequences:

  • It is accessible from any point, regardless of the packages
  • Your name must be the file .java-what it contains; there can be only one public class per file

Comments

Java has three kinds of comments:

  • The // he says until the end of the line
  • The /* he says to the first */ (no nesting)
  • The /** he says to the first **/

Packages

Packages

As you incorporate third-party class increases the possibility to find classes with the same name

The possibilities are even greater in Java, where classes of millions of programmers have to travel through the network

The solution that provides Java are the packages (packages)

To specify the desired class simply indicate the name of the package to which it belongs

Sun gave in its day some recommendations for the names of the packages were unique:

  • If you are going to use within the company will be able to use any convention internal

  • If you are going to use outside the company should be used as a prefix in the Internet domain of the company invested (this ensures it is unique), for example com.sun.graphics3D

  • The standard classes are reserved for prefixes java and javax

The entire class must belong to some package

The Java classes are distributed in several basic packages:

Package
java javax
java.applet javax.accessibility
java.awt javax.activation
java.beans javax.activity
java.io javax.annotation
java.lang javax.crypto
java.math javax.imageio
java.net javax.jws
java.nio javax.lang
java.rmi javax.management
java.security javax.naming
java.sql javax.net
java.text javax.print
java.util javax.rmi
javax.script
javax.security
javax.smartcardio
javax.sound
javax.sql
javax.swing
javax.tools
javax.transaction
javax.xml

The name of a class includes a prefix of the package to which it belongs

In the example, the Vector class is inside the java package.util

In the example we have used the reserved word import that allows you to indicate the package to which belongs one or more classes, in such a way that you didn't have to repeat it with each use of the same

import does not load any type of file (not equivalent to #include in C / C++)

The package java.lang it is imported automatically

Collision of names

In the case of a repeat of a class name in two imported packages, we would have to use the full name of the class to undo the ambiguity

In the example you have specified the package that you want to take the Vector class, with the asterisk you're saying that you take all the package

In the example you have used an import of the concrete class Vector and another of all the package

Keep in mind that the import of the class will have priority over the import of an entire package

So it could be removed if you do not want to use the rest of the classes of that package, to be redundant

Creation of packages

To indicate that a class belongs to a package, use the clause package

In the example, we have created the package examples contains only the class Example1

If we are to use in another class, the name of the package may be formed by multiple words separated by dot

In this case the class name will be examples.Example1

If you would like to run it to use it in other classes from the command line:

Classpath

Java does not have the concept of executable file (file with extension .EXE or .COM)

Each class generates a file class independent

To run a program you need to specify the name of a class that contains at least a main function

The rest of the classes will be loaded dynamically on demand

You can have multiple classes with main but there can only be one main that is the main

In the case of local applications you will locate the code of the classes:

  • The JVM adds the name of the class the extension class to form the name of the file

  • To locate this file using the environment variable CLASSPATH

  • CLASSPATH indicates a series of locations in which to find the classes that can be:

    • A directory
    • A file ZIP or JAR (Java Archive Resource)

In the example we have used Windows command line to define the CLASSPATH

The class Test would look for (in this order):

  1. c:\examples\Test.class
  2. inside the file
  3. c:\java\lib\classes.zip and nowhere else

When using classes made by third parties it is necessary to include its directory (or ZIP, JAR) in the CLASSPATH for the JVM to be able to find them

Packages and Classpath

In the JDK there is a relationship between the package of a class and the directory in which it is located

All the classes in a package must be in a directory with the same name

If a package name has multiple words, each word corresponds with the name of a subdirectory

For example, the classes in the package ur.my.examples would be in the directory ur/my/examples

This directory must be accessible from any of the locations CLASSPATH

The mechanism of the JVM of the JDK to locate the implementation of a class at runtime is:

  1. adds .class the full name of the class
  2. transforms the points into directory separators \
  3. adds the resulting string to each of the locations CLASSPATH
  4. if it is not found in any of them produces a runtime error

Let us follow the process with an example in which we want to load in the JDK class UR.examples.example1:

  1. We define the CLASSPATH as:

  2. The JVM searches for the class in the file UR\examples\example1.class

  3. The file will be searched in the locations of the CLASSPATH c:\programs\UR\examples\example1.class and c:\temp\UR\examples\example1.class

  4. If the class is not found in either of these two sites, will result in a runtime error

Primitive types in Java

Primitive types

The primitive types are divided into:

  • Characters
    • char
    • String
  • boolean
  • Numeric
    • Integers
      • byte
      • short
      • int
      • long
    • Real
      • float
      • double
  • Arrays

The primitive types are characterized by having defined a same size on all platforms (unlike the C / C++)

The literal real are of type double unless you include the suffix F

3.14 it is not of the same type 3.14 Fthe first will be double and the second float

When you want to cause a conversion uses the operator cast

It has the following syntax:

Using the cast, you can perform those conversions that the compiler does not by default

In the example, has carried out a casting of the double 5.4 a int to store it in the variable i

The result of that operation will be the compiler to take only the integer part of the double, that is to say, will keep on i the value 5

In the second operation example, it is divided 5 by 2, this operation will return its result as a double, but if the result would not have decimal places, would be saved as a whole

To make a casting in the denominator, we force the compiler to store the result of the division as a double even if you have no decimal

Keep in mind, that a casting does not correct the error of division by 0, should be controlled by the use of exceptions

Wrappers

A wapper is a wrap that is applied to a primitive type concrete

There are a class wrapper is associated to each primitive type

In the example, we have redefined the wrappers for int (it is Integer) and for double (it is Double) to be able to add the primitive data int and double in the class Vector

The class Wrapper have a second functionality

Are used to locate all those services of the primitive types that they represent

Some methods of wrappers are important:

Wrappers
Integer Character
MAX_VALUE chaValue()
MIN_VALUE equals(Object)
Integer(int) getType(char)
Integer(String) isDigit(char)
byteValue() isIdentifierIgnorable(char)
doubleValue() isJavaIdentifierPart(char)
equals(Object) isJavaIdentifierStart(char)
floatValue() isJavaLetterOrDigit(char)
intValue() isLetter()
longValue() isLetterOrDigit(char)
parseInt(String) isLowerCase(char)
parseInt(String, int) isUpperCase(char)
shortValue() isWhitespace(char)
toBinaryString(int) toLowerCase(char)
toHexString(int) toString()
toOctalString(int) toUpperCase(char)
toString(int, int) toString(int, int)

Characters

A character it is a symbol that follows the ASCII standard which we use to generate the texts of our programs

A string of characters it is an array of characters that allow you to save texts or phrases

char

It is a letter that follows the ASCII standard and is the smallest unit of string

Its size is 8 bit

Its value could be considered a small integer since its range is -128 to 127

Values char are associated with the class Character

Is initialized with single quotation marks

In the example initialized the variable ch as a string and as you can see has been saved to the ASCII symbol that corresponds to the letter to uppercase

String

The character strings are not a primitive type

However Java provides special classes for your treatment

Strings are objects that are manipulated using the classes String and StringBuffer

Is used String when the string will not be modified

Use StringBuffer when you want to manipulate the string

It is recommended to use typically the String (to be constant) to be more efficient

Initialization of a String

The strings are between double quotation marks, and character with single quotation marks

When the compiler encounters a string literal, it will create a String object with the text of the same

In the example, we have initialized two variables that might be equivalent

s1 has been initialized using only the double quotation marks

s2 has initializing the constructor for objects of the String class, passing it as an argument the value with double quotation marks

Both initializations are valid and the contents of the variables s1 and s2 will be in both Hello

The only difference is that to be different objects, their reference in memory will also be different

Basic methods

length

The method length returns the number of characters in a string

In the example, we have asked two strings of characters number of characters

In the first you have used double quotation marks, and in the second the String object s1 of the above example

The two previous expressions would be equivalent, return an integer with the number of characters in the string

charAt

The method charAt returns the character at the specified position

If the argument of charAt is not a number between 0 and length – 1 will cause an exception

In the example you have created a function that given a String str and char are looking for, you search for the character in that string and if found, the return value will be greater than 0

To achieve this they have used the method charAt has passed the value of i that represents the position of a character read up to the time

As returns the character read in that time we have been able to compare it with the character search that we passed as an argument

Search methods

Methods to perform searches in strings return the position of the searched item or -1 if not found:

  • indexOf(int ch)
  • indexOf(int ch, int start)
  • indexOf(String str)
  • indexOf(String, int start)
  • lastIndexOf(int ch)
  • lastIndexOf(int ch, int start)
  • lastIndexOf(String str)
  • lastIndexOf(String str, int start)

In the example we have used each of the methods and discussed its return value to be able to understand them better

Comparison of strings

To compare strings does not serve the = = operator, because in reality we are comparing objects

The String class has several methods for comparing strings

Two strings will be equal if they have the same length and the same characters Unicode (to and unto are different)

The most common methods are:

  • equals
  • equalsIgnoreCase

    distinguishes between uppercase and lowercase

  • compareTo

    in addition to allowing us to find out if two strings are the same, it also tells us which one is greater than the two:

    • Equal to 0

      They were the same

    • Greater than 0

      The second value was greater

    • Less than 0

      The second value was less

In the example we have used each of the methods and discussed its return value to be able to understand them better

Methods for comparing prefixes and suffixes

  • boolean starsWith(String)
  • boolean starsWith(String, int start)
  • boolean endsWith(String)

In the example we have used each of the methods and discussed its return value to be able to understand them better

Extraction of strings

There are a number of methods that return a new string that is the result of manipulating the original string

The original string is not modified (a new instance of the string is created, that is, another memory position is used)

  • String concat(String)
  • String replace(char, char)
  • String replaceAll(String, String)
  • String substring(int start)
  • String substring(int start, int end)
  • String toLowerCase()
  • String toUpperCase()
  • String trim()

In the example we have used some of the methods and discussed its return value to be able to understand them better

String conversions

The primitive types can be converted automatically to strings

To convert strings to primitive types, use one of the following functions:

  • boolean new Boolean(String).booleanValue()
  • int Integer.parseInt(String)
  • long Long.parseLong(String)
  • float Float.parseFloat(String)
  • double Double.parseDouble(String)

Other methods

  • char[] toCharArray()
  • void getChars(int srcBegin, int srcEnd, char[] dest, int destBegin)
  • int hashCode()
  • String valueOf(boolean)
  • String valueOf(int)
  • String valueOf(long)
  • String valueOf(float)
  • String valueOf(double)
  • String[] split(String)

As you can see in the example, we'll use split to slice strings using a token, in this case we've used space

This method is quite useful for working with text files in CSV format, since the symbol is usually used; (or other token symbol) to separate the different columns or cells

StringBuffer

Although the String class is the most common it is not appropriate for strings that need to be changed frequently

The example creates four String objects of which only one will be used, admiration1 or admiration2

The class StringBuffer lets you modify the original string without the need to create intermediate objects as done in the example

Initialization of a StringBuffer

Supports the following constructors:

  • StringBuffer()
  • StringBuffer(int i)
  • StringBuffer(String str)

Methods of modification

Supports the following modification methods:

  • append(Objetc obj)
  • append(String str)
  • append(char str[] )
  • append(boolean b)
  • append(int i)
  • append(long l)
  • append(float f)
  • append(double d)
  • append(char ch)
  • insert(int offset, Object obj)
  • insert(int offset, String str)
  • insert(int offset, char str[] )
  • insert(int offset, boolean b)
  • insert(int offset, int i)
  • insert(int offset, long l)
  • insert(int offset, float f)
  • insert(int offset, double d)
  • insert(int offset, char ch)
  • setCharAt(int index, char c)
  • setLength(int longitud)

In the example we have used some of the methods and discussed its return value to be able to understand them better

Basic methods

length

It is similar to the String

charAt

It is similar to the String

toString

Performs the conversion of the BufferString to String

Operador +

Java allows concatenation of strings using the +

In the example, internally the compiler uses a StringBuffer instead of a String

So this example is completely compatible with the previous

In the example we concatenated the string with another type (integer), the latter is automatically converted to string (the compiler implicitly invokes the toString() method of the StringBuffer class)

boolean

Its size is 1 bit

Its value could be considered a small integer since its range is 0 to 1

Being the value 0 equal to FALSE and 1 equal to TRUE

The boolean values are associated to the class Boolean

Basic methods

booleanValue

Returns the value of the boolean

toString

Converts the boolean type to a string

Numeric

Are all types that allow you to work with numbers and can be distinguished according to whether they are integers or decimals, or as to its accuracy

Integers

They are all types that allow you to work with integers, there are several types depending on their accuracy and the range of numbers that can be handled

byte

Its size is 8 bit

Its value could be considered an unsigned small integer since its range is 0 to 255

The byte values are associated with the class Byte

short

Its size is 16 bits

Its value could be considered an unsigned integer since its range is 0 to 65535

The values short are associated to the class Short

int

Its size is 16 bits

Its value could be considered a signed integer since its range is -32768 to 32767

The int values are associated to the class Integer

long

Its size is 32 bits

Its value could be considered a large integer as its range is -2147483648 to 2147483647

The long values are associated with the class Long

Real

They are all types that allow you to work with decimal numbers, there are several types depending on their accuracy and the range of numbers they can handle

float

Its size is 32 bits

Its value would be a decimal smaller as their range is 3.4 E-38 to 3.4 E+38

The float values are associated with the class Float

double

Its size is 64 bits

Its value could be considered as a decimal great since its range is 1.7 E-308 to 1.7 E+308

The double values are associated to the class Double

Arrays

An array is a grouping of elements of the same type

Arrays in Java are objects

Therefore, a reference will be needed to manipulate them

In the example we can see that like any other object, it is initialized with new

Classic array notation (using an index) is used to access array elements (using an index)

If the maximum value of the index is not specified, the compiler will take it as a dynamic array

We can consider that the rating is equivalent to send a message to the array to view an item or edit it

The range of an array is between 0 and N-1 (N being the size of the array)

If you have access to a position out of range an exception will be thrown

In the example we have initialized the array to then be able to view all its contents by screen

As can be seen, Java allows you to initialize the array in its declaration

The operator length allows you to find out the size of an array

In the example we have initialized an array of references in your statement

As can be seen, both statements are equivalent

Arrays two dimensional

A two dimensional array can have multiple rows, and in each row there does not have to be the same number of elements or columns

In the example we have declared and initialized two dimensional array of doubles array then walk it and display it on the screen

The first row has four elements {1,2,3,4}

The second row has two elements {5,6}

The third row has six elements {7,8,9,10,11,12}

The fourth row has an element {13}

array.length gives us the number of rows which in this case is

matrix [i] .length gives us the number of elements in each row

We show the elements of a row separated by a tab using the print function

Once a row is passed to the next by using println

Example of identity matrix

To show the power of a two dimensional matrix, this example builds a dimension identity matrix 4

A identity matrix is the one whose elements are zero except those of the main diagonal, i= =j, which are some

Using a double for loop we loop through the elements of the array specifying its row i and its column j by population the matrix with 1 or 0 depending on whether i and j match

Using a double for loop we go through the elements of the array by specifying its row i and its column j

We show the elements of a row separated by a tab using the print function

Once a row is passed to the next by using println