Category Archives: Programming language

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

Classes in Java

Classes in Java

In Java, every object (classes) is manipulated through a reference

This reference saves the identifier of the object

And is responsible for sending messages to the object associated

The type of the reference indicates what type of messages you can send

Access modifiers

When you create classes, the need arises to indicate the use of their attributes and methods

Some attributes will be internal:

  • Must not be modified

  • It is not necessary to know of its existence

The same goes for methods:

  • Should not be invoked from outside the class

  • Do not need to know about its usefulness

The access modifiers control the visibility of class members

Indicate which of them are of interest to the outside

Java offers four access modifiers:

  • private

    is visibility more restrictive

    Only allows the invocation from the class itself

  • public

    is visibility less restrictive

    Enables the invocation from any class

  • package

    is the visibility by default

    Only allows the invocation from the classes that they belong to the same package

  • protected

    is the visibility associated with the inheritance

    Only allows the invocation from derived classes

Builders

When a class does not declare any constructor, it automatically creates a default constructor

In the example the constructor has been called from the main method and is responsible for leaving the object in an initial state in which we can work with him

Since we haven't created the constructor, the default constructor was automatically used

In the example, we've defined a class called Person that has only the attribute name that is private

The constructor was used to initialize it and to access it (as it is private it is not directly accessible) the get and set methods have been added

In case you have not used the constructor to initialize it with new, by using p we would have obtained a value null, since the object would not yet be defined in memory

To refer to an attribute of the class itself, we use the reserved word this

In this case, it has been used to refer to the attribute name

Constructor with parameters

When we need to add external information, we can use parameter builders

A constructor can declare the parameters that are needed to create the object

This example is very similar to the previous one, however we now have two constructors, a default constructor and a parameterted constructor

In the event that we have the same name in a parameter and an attribute, we can distinguish them if we use the reserved word this

We did with the parameter name and the attribute name, when using this have become unambiguated

A constructor can also be overloaded, that is, it receives different types of arguments to have different behavior

In this example we have defined classes Point and Rectangle

By defining multiple constructors with parameters of different types to the class Rectangle

So we have overloaded the constructor to be getting different results in the main method

Attributes static

A class describes the attributes of each object (instance attributes)

Sometimes you need attributes that are shared by everyone: that remain to the class

The reserved word static declares a class attribute

In the example you have declared an attribute static of type int, it's not a class but as you can see you can also use primitive types

To access the attribute static we've given you the name of the class, in this case A

There is No need any class instance to be able to access the attribute

It is created when you load the class and initialize with the values from the default constructor

In the example, we have used the classes Timer and A initializing their attributes in a block static

With static should not create new objects because they are back on track with each new instantiation

The class attributes are initialized using a block static

The blocks static running to load the class

Can be considered as a builder most of the class

In this example I've reduced the code to use an equivalent alternative to initialize in the declaration

Static methods

In the same way that there are attributes static there are methods static

Recommended for use with utility methods that are not performed on any object but about primitive types

For example the class Math it offers the methods static sqrt, random, pow, etc

Are declared by using the word static

In the example you have declared the method static f in the class A

The class name is used to invoke them, in this case the class A

A method static you can only access:

  • attributes static

  • other static methods

In the example a reference has been added to the method static g what that allows us to access the elements of the instance of the class A without being static

Keep in mind that to access instance items must obtain a reference to previously

Inheritance

A derived class can add new operations (expand the number of messages that the object understands)

In the example you have created the classes A and B

As B inherited methods A y por tanto, podía usar methodA without problems

However, A non inherited methods B, that's why it gave us an execution error

In the example we have used a derived class to redefine operations

Redefining one method is to give a different implementation to the same message (which will be treated by another method)

It is important not to confuse the overhead of a method with its redefinition

In the example, has redefined the method methodA of the class A in the class B, reusing it by replacing its implementation

It has been used the reserved word super to refer to the methods of the base class

You can also use the reserved word super to refer to the attributes of the base class

In the example there is a base object Vehicle, two derivatives Car and Bike

A fundamental aspect of inheritance is the relationship between the base type and the derived type

The derived class has at least the operations of the base class

That is, an object of the first class understands all the messages that an object of the second class might understand

Therefore, any reference of the base type can point to an object of the derived type (since it understands all its messages)

Polymorphism

Inheritance allows different classes to share a common set of operations (those in the base class)

Dynamic binding allows that even if two objects accept the same messages they can perform them differently

In the example we can see that thanks to polymorphism, even though v is of type Vehicle it takes into account the type of object pointed

It is important to differentiate the two types that participate in sending a message:

  • The type of reference

    it is the one that determines the messages that it can transmit to its associated object

    Therefore, it can only be associated with objects that understand at least those messages (objects of the same type or of a derived type)

  • The type of the associated object

    it is the one that determines which method is the one that dispatched the message received

Constructors and inheritance

The constructors cannot be inherited

In the example we have declared two constructors for the class A and then it has been inherited in the class B

When you try to use the constructor with integer parameter will give us an error because B did not have an appropriate constructor though A yes that was

A class you can only use the constructors that declare

If you have not declared, none will be assigned the default constructor

In the example we have declared two constructors for the class A and then it has been inherited in the class B

But on this occasion it has made a call to the default constructor of the base class within the constructor of the derived class

Some constructor of the base class is required to be invoked (to ensure its state)

By super you can select the proper builder

super can only appear once and must be the first line of the constructor

Will support only the parameters that support the constructors of the base class

Abstract classes

An abstract class is one which has one or more abstract methods

An abstract method is one that has not been implemented in the base class

Your code will have to be provided in each of the derived classes

To define a class as abstract using the reserved word abstract

In the example we have defined the abstract class Vehicle with two abstract methods

As can be seen, methods are also defined using the reserved word abstract

Abstract classes have the restriction that they cannot be instantiated (because they have undeployed methods)

If a derived class does not redefine all abstract methods, it will in turn be an abstract class

Creating abstract classes:

  • Identify the common operations that have to have objects to manipulate

  • Create with them an abstract class base

  • Identify the operations to redefine and give an implementation to the rest

Use of abstract classes:

  • Their only goal is the derivation

  • The class derived will have to implement the abstract methods

  • Others may be inherited, replaced or expanded

Classes end

You may want a class to be un derived (for security reasons, you do not want anyone to be able to replace it with a derived class)

It uses the reserved word end so that the class can not be derived

In the example we have tried to inherit the class B the class A that was end

As we have defined A as end the interpreter will not allow you to have inherited classes

In the example we have defined a final method and one that is not

There is also an intermediate level: that can be derived from the class but not certain methods

A method you can also use the reserved word end

A final method cannot be redefined

In the example we tried to modify a final attribute, the interpreter will give us an error

Make a class or method final is a major constraint

Should only be done in special situations and putting the utmost care

A final attribute cannot be modified once it has been started

In the example, we have defined two variables called x as a final

If the value of the final attribute is the same for all instances, it is wasting space in memory

In this example, we have used constant variables to solve the problem of the previous example

In Java, constants are declared by combining the reserved words static followed by end

Constants do not take up memory and by convention, they are usually defined with a capitalized name

Downcasting

When a class is not derived explicitly from another class then derived implicitly from the class java.lang.Object

The class Object it's not a primitive type, but it's the class from which all the language classes derive and those that the programmer believes

However, you don't need to use the reserved word extends because it implicitly drifts

Therefore, all kinds of Java is a Object and will inherit the methods of this

Some of the outlined methods of the class Object:

  • boolean equals(Object)
  • void finalize()
  • int hashCode()
  • String toString()

There are occasions in which it is known with certainty that the object is of the appropriate class

In these cases you may be able to force the assignment using a cast

In the example we have used the classes Vehicle and Canoe that inherits from it

To then make a declaration of a Vehicle v for that we have used the constructor Canoe

And has been declared a Canoe c for which the type was previously known (Canoe) por lo que se ha realizado un cast

The cast checks that the object is of the appropriate class and performs the assignment

In the event of not being of the appropriate class or is not able to perform the assignment will throw an exception ClassCastException

Operator instanceof

The operator instanceof allows you to find out if an object belongs to a certain class

In the example, has carried out two checks with instanceof

When we tested with Object will always return True because it is a supertype of the class of the instance

When we tested with Canoe we have checked if the cast can be applied

In this way we avoid having to handle the exception ClassCastException

Interfaces

Interfaces, like classes, are a way to create objects

They are characterized by only one behavior (and/or constants)

  • Have No attributes

  • Do not have associated code for methods

Are defined with the reserved word interface in a similar way as is done with the classes

In the example we have defined the interface anInterface with the methods method1 and method2

Similar to abstract classes, because they have no implementation it is possible to instantiate the interface

You can only use it to create new data types (other classes or interfaces)

In this example it has implemented the interface anInterface heredandola in the class aClass

When the class aClass inherited methods anInterface it has become a subtype of that interface

For that reason we must give them an implementation in the class, since sinó we would be obliged to declare it abstract

But precisely because he has used an interface, the interpreter will show us an error message telling us which specific methods have not been implemented

Differences between class and interface

Class:

  • Type that extending it by inheritance results in its behavior and implementation (both attributes and its methods)

  • Advantage: Less coding when creating new subtypes as its behavior comes to its implementation

  • Drawback: It can only be derived from one of them, multiple inheritance is not allowed

Interfaces:

  • Type that extending it by inheritance gets only its behavior (description of methods)

  • Advantage: You can inherit multiple interfaces without conflicts

  • Drawback: There is hard-coding the implementation of each method for each subtype inherited

Control statements in Java

Control statements

Control statements are nothing more than a set of words that tell the interpreter things like what the next statement to execute is, how many times to evaluate a particular expression, and so on

Sentences of selection

They serve to group statements and statements into a compound statement or block, which from that moment can be considered syntactically equivalent to a simple

if-else

The expression if-else lets you choose whether to run the next or following sentences on the basis of a boolean value

It has the following syntax:

First evaluates the boolean expression and in the case that your result is equal to TRUE to run the block of sentences then if

In the case that your result is equal to FALSE to run the block of sentences then the else

else is optional and we may not use it, although if we want to have all the options covered, it is advisable to use it

Within a block of statements can include additional if-else, this practice is known as nesting and it is very useful to continue adding conditions to check the code

The example compared the integer values contained in variables a, b, and c, using nested if-else, showing the user the highest value per screen

else-if

The else-if expression is an improvement to the if-else expression, its operation is similar, however it allows to have a multiple selection without resorting to nesting, although within the block of sentences it will be possible to perform nesting

It has the following syntax:

else is optional and we may not use it, although if we want to have all the options covered, it is advisable to use it

The code in this example is very similar to the previous one used with if-else, they are syntactically equivalent, but it has managed to reduce the number of lines of code a bit

switch

Since multiple selection is a very common construction, it is more advisable to use the switch

But keep in mind that it only works with whole expressions, we can't use any Boolean expression as with if-else or else-if

It has the following syntax:

First evaluates the entire expression and checks whether it equals the value contained in the first case, in case its result is equal to TRUE to run the block of sentences then in that case

The execution will not end until find a break, therefore ending the execution of the switch expression

break it can be omitted and then it would check the next case

In the event that no case has value TRUE, then it would work in a similiar way to the else, executing the block of sentences then the default

The example has checked which day of the week is the integer value by displaying the name of the day and if it is Saturday or Sunday, showing that it is a non-school day and weekend

This example would only work with values from 1 to 5, because if we enter any other value, it would show us by screen the default, that is, that it is weekend

Sentences jump

Sometimes we need to exit unconditionally of any expression and to do this we will use the sentences jump

break

This expression provides the option to unconditionally exit a while, do-while, for, for-each, or switch expression

In case the expression is nested, what it will do is exit the innerdest expression

It has the following syntax:

Although syntactically correct, its use makes the code difficult to read, since it is adding an exit point not controlled by a Boolean expression

continue

This expression is similar to the break expression, however, it is less aggressive

Breaks the execution of the block of sentences but it re-evaluates the boolean expression

It cannot be used on a switch, as it would have no effect

In case the expression is nested, what it will do is exit the innerdest expression

It has the following syntax:

Sentences of iteration

Sometimes we need to run a block of sentences un determinado o indeterminado número de veces, a estas sentencias se las denomina loops

while

This expression repeats a block of statements while is satisfied a boolean expression

It has the following syntax:

Within the block of sentences we must make sure that you modify in any way the value of the boolean expression, because otherwise we can fall into a loop that never ends and is called infinite loop

This situation is not desirable, as our program will be hung and it is likely that the user would not know what to do in that situation, since the programmer has not bothered to control it

The example walks through numbers 1 through 100 and shows the user per screen

The counter started at 0, because it is an agreement that was used to initialize variables in C and is still used in Java

Just like using variable names i, k, or j for counters

do-while

This expression is similar to while, however the statement block is always executed at least once and the condition check is performed after that execution

It has the following syntax:

Within the block of sentences we must make sure that you modify in any way the value of the boolean expression, because otherwise we can fall into a infinite loop

Also supports expressions break and continue

The example walks through numbers 1 through 100 and shows the user per screen

It should be noted that the first time the Boolean expression is not evaluated, but rather because of that situation, it would be totally equivalent to the expression while

for

This expression is similar to while, however it allows you to initialize the variable that will handle the loop

It has the following syntax:

Within the variation of the variable we must make sure that you modify in any way the value of the boolean expression, because otherwise we can fall into a infinite loop

Also supports expressions break and continue although its use is discouraged, as it is considered that for this expression they break the normal flow of the program

The example walks through numbers 1 through 100 and shows the user per screen

It is totally equivalent to the while expression, but saves some lines of code by including its own initialization and in this case, an increase in the variable outside the expression block

for-each

This expression is similar to the for but is specialized in travel objects that support the Iterator class

It was introduced in Java version 5

It has the following syntax:

It is not necessary to make sure that it is changed in any way the value of the boolean expression as in a for, because when based on the Iterator class, the loop will end when there are no more elements of the object, the preventing it from falling into a infinite loop

Also supports expressions break and continue although its use is discouraged, as it is considered that for this expression they break the normal flow of the program

The example walks through an array containing numbers 1 through 5 and shows the user per screen

In this case, a simple array has been traversed, but more specialized objects could be traversed (as long as they support the Iterator class) such as an ArrayList, a Vector, a Map, etc

Exceptions in Java

Exceptions in Java

If an operation cannot be completed due to an error, the program must:

  • return to a stable state and allow other operations

  • try to save your work and finish

This task is difficult because usually the code that detects the error is not the one that can perform such tasks this is why you should inform that you can handle it

The most common solution are the error codes

Java offers another way to deal with errors under exceptional conditions: the exceptions

An exceptional condition is one that prevents the continuation of an operation

It's not known how to handle it, but you can't continue

In Java an exception is thrown to someone who knows how to handle the question in a higher context

In the example it is checked by the conditional if the file readme.txt there was in the system and in case it does not exist it throws the exception IOException, which at the moment is without trying

The reserved word throw terminates the current method and throws an object that provide information about the error that occurred

Normally you would use a class for each type of error

Java requires that a method report the explicit exceptions that it can throw

A method doesn't just have to say it returns if everything goes well; should also indicate what may fail

In the example, we have declared exceptions EOFException and FileNotFoundException affecting the method file

The specification of exceptions is performed using the word throws in the method declaration, and there can be as many as needed separated by a space

Handling of the exceptions

Once detected the error makes it necessary to indicate who is in charge of treating it

An exception handler has the following format:

The block try delimits the group of operations that may produce exceptions

The block catch it is the place to which control is passed if any of the operations throws an exception

In the example it has been used a try block to your catch block to handle the errors of the previous example

If any of the operations in the block throw an exception, the block is interrupted try and runs the catch

At the end of this, it is normally continued

If no exception is thrown, the catch block is ignored

There is also the possibility of using the generic exception Exception, but it is best to use the specific exception type for the error

In the example it has been used a try block to your catch block to handle multiple exceptions as in the previous example

A try block can have multiple catch statements associated

When an exception does not correspond to any catch is propagated backward in the sequence of invocations until a catch right

In the example is managed the exceptions of the methods f1 and f2 and if you don't find any, it continues the execution of the code in the normal way outside of the block try

This example has tried to show the 3 alternatives we can use to handle the exception IOException from the method f2

When a method that throws exceptions is invoked, it is mandatory:

  • to handle the error with a block catch

  • that is indicated by throws its spread

Finally block

There may be occasions in which you want to perform some operation if exceptions occur as if not

Such operations can be located within a finally block

A finally block has the following format:

If there is any exception it will execute the try block and the finally

In the example it has controlled the closing of the file f in the block finaly, always running

If any exceptions occur:

  • If it is caught by a catch the same try it runs east and then the finally

    The execution continues after the finally normally

  • If this is not trapped it is running the finally and the exception is propagated to the previous context

Hierarchy of exceptions

Any exception must be an instance of the class Throwable

It inherits the following methods from it:

  • getMessage()

    returns a string with a message that details of details the exception

  • toString()

    returns a brief description which is the result is concatenate:

    • the name of the class of this object
    • el token :
    • the result of the method getLocalizedMessage() this object
  • fillInStackTrace()

    records information about the current state of the stack frames for the current thread

    If the stack status cannot be written, there will be no return value

  • printStackTrace()

    returns the trace that has followed the exception

    The first line of output contains the result of the method toString() this object

    The remaining lines represent data previously recorded by the method fillInStackTrace()

The basis of the Java exception hierarchy is:

  • Throwable

    • Error

    • Exception

      • RuntimeException

Derived classes Error describe internal JVM errors:

  • should not be thrown by the classes of user

  • these exceptions rarely occur and when it is the only thing you can do is try to close the program without losing the data

  • Examples: OutOfMemoryError; StackOverflow; etc

Java programs will work with the exceptions of the branch Exception

This group is in turn divided into:

  • The classes that are derived directly from Exception (explicit)

  • Arising from a course of RuntimeException (implicit)

Use the RunTimeException to indicate a programming error

If there is an exception of this type is that fixing the code

Examples:

  • A cast wrong

  • Access to an array out of range

  • Use of a pointer null

The rest of Exception indicate that has happened some error due to any cause beyond the program

Examples:

  • An I/O error

  • Connection Error

Declaration of exceptions

The methods should be declared only with the explicit exceptions

Implicit ones should not be declared (although they can occur equally)

Therefore, when a method declares an exception, warning you that it may occur that error in addition to any error implicit

Creation of exceptions

If you need to handle any errors not covered by the standards that Java has, we can create our own kind of exception

The only condition is that the class derives from Throwable or in any arising out of it

In practice, the following shall generally be derived:

  • of RunTimeException if you want to report a programming error

  • of Exception in any other case

Summary

Explicit exceptions Exceptions implied
Derived from Exception (no de RunTimeException) Derived from RunTimeException
Indicate an error external to the application Indicate a programming error
If launched it is obligatory to declare them Don't declare: they are corrected
If you invoke a method that throws it is compulsory to catch them or declare them to be

You can catch

Otherwise, the application ends

Exceptions and inheritance

When you redefine a method it is giving another implementation for the same behavior

The new method may only throw exceptions declared in the original method

In the example, has redefined the method f of the class A in the class B with an additional exception

A method can declare the exceptions that do not throw really

A base method may allow the redefinitions may cause exceptions

Constructors, not inherited, can throw new exceptions

Rules of use

  1. Standard

    • If an exception can be handle should not be spread

    • It is more convenient to use methods that do not produce errors

  2. Standard

    • Do not use exceptions to avoid a query

      • Not to abuse them

  3. Standard

    • To separate the error handling logic

      All together
      Separate
  4. Standard

    • Do not ignore an exception already that we leave the code with errors without control

I/O streams in Java

I/O streams

The I/O streams in Java is performed through sorted sequences of bytes (streams)

These can be input (InputStream) or output (OutputStream) independent objects from data

The classes of E/S are in the package java.io

The methods of OutputStream and InputStream throw the exception IOException for any failure related to the attempt to read/write

The class OutputStream

Abstract class from which derive the other output streams

It essentially offers the following methods:

  • public abstract void write(int b) throws IOException
  • public void write(byte b[]) throws IOException
  • public void write(byte b[], int off, int len) throws IOException
  • public void flush() throws IOException

    Force the write

  • public void close() throws IOException

There are several classes that are derived from OutputStream and redefine the method write to give you a different implementation:

  • FileOutputStream

    it redefines the method write to send bytes to a file

  • ByteArrayOutputStream
  • PipedOutputStream
  • Sun.net.TelnetOutputStream

FilterOutputStream

A output filter it is a OutputStream to which will be associated to it in its constructor another OutputStream (a decorator pattern)

The filter forwarded all of the information you receive to your OutputStream associated, after carrying out some kind of transformation in it

In this way each filter adds an additional functionality to the OutputStream that encapsulates

You can chain multiple filters to obtain multiple functionalities, combined

In the example the file has loaded data.dat for writing and using the method write have saved several integer values that are stored in the variable i

He adds & 0xFF at the end of the write stream to indicate within the file that a data has finished writing

Filter DataOutputStream

The methods of the class OutputStream only allow you to send bytes

Any other type must be broken down into a sequence of bytes before it can be written

Among the most prominent methods:

  • void writeBytes(String s) throws IOException
  • void writeBoolean(boolean v) throws IOException
  • void writeShort(int v) throws IOException
  • void writeChar(int v) throws IOException
  • void writeInt(int v) throws IOException
  • void writeLong(long v) throws IOException
  • void writeFloat(float v) throws IOException
  • void writeDouble(double v) throws IOException
  • void writeChars(Strings s) throws IOException

    Almost uns used, the filter is more used PrintStream

In the example, two filters have been used, the FileOutputStream seen above and the DataOutputStream seen now

The class DataOutputStream adds the functionality of being able to send all primitive types directly

So you can write in the file any primitive type and even attributes of an object, as long as they are primitive types, since you do not write the entire object

Filter PrintStream

The class PrintStream adds the functionality of being able to send all of the primitive types in text format

In the example, two filters have been used, the FileOutputStream seen above and the PrintStream seen now

Methods print and println are overloaded for all primitive types

System.out is of type PrintStream and that's why it is not necessary to reference it by using this filter

The most common way of use OutputStream will be combining several filters

The class InputStream

Abstract class from which derive the other input streams

It essentially offers the following methods:

  • public abstract int read() throws IOException
  • public int read(byte b[]) throws IOException
  • public int read(byte b[], int off, int len) throws IOException
  • public int available() throws IOException
  • public void close() throws IOException

There are several classes that are derived from InputStream and redifinen the method read to give you a different implementation:

  • FileInputStream

    it redefines the method read to read bytes from a file

  • ByteArrayInputStream
  • StringInputStream
  • SequenceInputStream
  • PipedInputStream
  • Sun.net.TelnetInputStream

FilterInputStream

An input filter is a InputStream to which will be associated to it in its constructor another InputStream

The filters return the information which they have read of his InputStream associated, after carrying out some kind of transformation in it

In this way each filter adds an additional functionality to the InputStream basic

You can chain multiple filters to obtain multiple functionalities, combined

In the example the file has loaded data.dat for reading and using the method read have read several integer values that are stored in the variable ch in the positions i + 1 and we've shown by screen

So we have been able to read the file that we write with the example of FileOutputStream

Filter DataInputStream

The methods of the class InputStream only allow to read bytes

Any other type should be read as a sequence of bytes, and to pick up the pieces before it can be used

It essentially offers the following methods:

  • readBoolean()
  • readChar()
  • readByte()
  • readShort()
  • readInt()
  • readLong()
  • readFloat()
  • readLong()
  • readFloat()
  • readDouble()
  • readLine()
  • readFully(byte[] b)

In the example, two filters have been used, the FileInputStream seen previously, and the DataInputStream seen now

The class DataInputStream adds the functionality of being able to receive all of the primitive types directly

That has allowed us to display primitive data contents of the file directly on the screen

So read from the file any primitive type and even attributes of an object, as long as they are primitive types, since it does not read the entire object

The most common way of use InputStream will be combining several filters

Utilities in Java

Utilities

There is a set of utilities within the Java language

Found in the package java.util

These are useful and everyday classes, among which we highlight:

  • Collections
    • Collection
      • List
      • Set
      • Map
  • Dates
    • Date
    • Calendar
  • Properties
  • Scanner

Collection

The API of collections of Java includes classes that are able to hold sets of objects

Represent containers of objects

They are dynamic structures, grow as elements are added and work with Objects

  • You can add any thing

  • To retrieve the item must be done casting

There are basically two sets:

  • Classes that implement Collection

    • Represent containers of objects

    • There are basically lists (List) and sets (Set)

  • Classes that implement Map

Some of its most important methods are:

  • boolean add(Object o)

    adds an item to the collection

  • boolean addAll(Collection c)

    adds a group of objects (another collection) to the collection

  • void clear()

    empty the collection

  • boolean contains(Object o)

    checks if an element is within the collection

  • boolean isEmpty()

    checks if the collection is empty

  • Iterator iterator()

    returns a java.util.Iterator to iterate through the elements of the collection

  • boolean remove(Object o)

    removes an item from the collection

  • int size()

    number of objects stored

  • Object[] toArray(Object[] a)

    returns an array with the elements of the collection

List

Serves as the interface for classes that represent data lists or dynamic arrays

Its elements are accessible by means of an index

Inherits the methods of Collection and also adds:

  • void add(int index, Object element)

    adds an element at a given position

  • Object get(int index)

    returns the item that occupies a certain position

  • int indexOf(Object o)

    returns the index of the first occurrence of the item in the list (or -1 if it cannot be found)

  • Object remove(int index)

    it removes the element that occupies a certain position

  • Object set(int index, Object element)

    changes the element that occupies a particular position with another element

When you add an object with add(Object), the element is added at the end

When you delete an object with remove(Object), everyone else moves so as not to leave gaps

The objects List most common are Vector (is threadsafe) and ArrayList (not threadsafe)

Set

Serves as an interface for classes that represent datasets

Can not have duplicate elements

Its elements are not accessible by an index

Adds No new methods

The objects Set most common are HashSet and TreeSet

Map

Represent tables of data

The whole map consists of a set of entries composed of:

  • A key, it serves to retrieve the item
  • A value

The most important methods are:

  • void clear()

    empty the structure

  • boolean containsKey(Object key)

    returns true if there is any object stored with that key

  • boolean containsKey(Object value)

    returns true if the Map contains that object

  • Object get(Object key)

    allows you to retrieve a specific item from its key

  • boolean isEmpty()

    indicates if the Map is empty

  • Set keySet()

    returns a set of keys in the Map

  • Object put(Object key, Object value)

    stores an object on the map with a particular class. If the key is already stored it is replaced by an associated object with the new

  • void putAll(Map t)

    includes a submap on the map

  • Object remove(Object key)

    deletes an object from given key

  • int size()

    returns the number of objects stored

  • Collection values()

    returns the set of values stored in the map

Are implemented as Hash tables

The most common are HashMap (not threadsafe) and Hashtable (is threadsafe)

Iterator

There are collections that are accessed through an index, others not

Iterator lets you iterate over collections of objects regardless of how they are organized

Otra ventaja, permite eliminar objetos sin tener que gestionar los indices

The most important methods are:

  • boolean hasNext()

    returns True if the iterator has any more element

  • Object next()

    returns the next element of the iteration

  • void remove()

    removes from the collection the last element returned by the iterator

Comparison of route of a Collection
for with index
Iterator

Dates

There are two classes that allow you to work with dates:

  • Date

    almost all of its methods are deprecated so it is not recommended to use

  • Calendar

    it is an interface which is very easy to give you the behavior you want

Both of the internally represented time by a value of type long that represents the number of milliseconds from the January 1, 1970 at 00:00:00 GMT

That value can be obtained using System.currentTimeMillis()

Calendar allows for many more operations with dates Date, although it is more difficult build (being an interface we will have to do its implementation ourselves)

Date

It is easy to build:

  • new Date()

    constructs an object Date with the current system date

Methods that are not deprecated:

  • boolean after(Date when)

    checks to see if the date is later than the one supplied as a parameter

  • boolean before(Date when)

    checks to see if the date is previous to the one supplied as a parameter

  • long getTime()

    returns the number of milliseconds since the 1 de Enero de 1970 a las 00:00:00 GTM

  • void setTime(long time)

    changes the date to another date in milliseconds

Deprecated methods:

  • int getDay()

    returns the day of the week for that date or returns the day that represents that instant in the local area

    Day of the week
    Day Sunday Monday Tuesday Wednesday Thursday Friday Saturday
    Value 0 1 2 3 4 5 6
  • getMonth()

    returns the month for that date starting with 0

    Months
    Month January February March April May June July August September October November December
    Value 0 1 2 3 4 5 6 7 8 9 10 11
  • getYear()

    returns the year for that date that has been subtracted from 1900

  • getHours()

    returns the time for that date, which will be between 0 and 23

  • getMinutes()

    returns the minutes for that date, which will be between 0 and 59

  • getSeconds()

    returns seconds for that date, which will be between 0 and 61, values 60 and 61 will only appear when the MVJ skips for a few seconds in an account

Calendar

Abstract class for representing dates in different types of calendars

It includes a lot of constants for all days of the week, months, fields of a date...

In the west, to get the date of the system we will use the GregorianCalendar:

  • new GregorianCalendar()
  • new GregorianCalendar(2007, 1, 5)

    Attention should be paid to the date:

    • es año, mes, día

    • Corresponds to the February 5, 2007 and not the January 5, 2007 as it might seem at first glance

      January corresponds to the value 0

We can also get the system date by using the static method Calendar.getInstance()

The most noteworthy methods are:

  • void add(int field, int amount)

    adds (or subtracts, depending on the sign of the operand) time to a date

  • boolean after(Object when)

    checks to see if the date is later than the one supplied as a parameter

  • boolean before(Object when)

    checks to see if the date is previous to the one supplied as a parameter

  • int get(int field)

    returns the value of some field of the date, which we specify with the parameter field

  • Date getTime()

    converts the type Calendar to Date

  • void set(int field, int value)

    change of value of a date field

  • void set(int year, int month, int date)

    changes the year, month and day of the date

  • void setTime(Date date)

    from a Date, creates a Calendar

Properties

Usually the behavior of applications can change in function of parameters

It is very comfortable to place those settings in the files for the application to the lea as needed

Java has the class Properties that automates this management

Each line in the property file saves a variable and is formatted as:

We will use the file called connection.properties which will have the following content:

To show the use of Properties with the following example:

Scanner

You can use the class Scanner to read primitive types and Strings using regular expressions

The class Scanner collect the characters typed from the keyboard until you find a delimiter which by default is space

The collected data are converted to different types using the method next<type>(), to collect texts like String we will use only next()

In this way we will be able to collect from the keyboard or other means, the types of data that we need

In the example we have read a int from the keyboard

In the example we have read several long from a file called numbers.txt

In the example we read several words from a String

Showing us on screen:

That is, the words contained in the String, each on one line at a time because we used println to display them on the screen

As we can see, if instead, we would have used print the would have shown all on the same line without any delimiter between them

In the example we read several words from a String changing the delimiter space by the delimiter 1

To set the new delimiter we use the method useDelimiter and we pass it parameter a string containing a regular expression, in this case \\s*1\\s*

Showing on the screen the same as in the previous example, despite using a different delimiter

JDBC

JDBC

JDBC is a set of Java classes and interfaces for executing statements SQL

It is the CLI part of Java (Call-Level Interface)

It was jointly developed by JavaSoft, Sybase, Informix and IBM among others

JDBC allows the manipulation of any SQL database

You don't need to do a specific program to manipulate Oracle, Sybase, etc...

Our program can handle any database

Bringing together Java with JDBC, we get programs that can run on any platform, and they can manipulate any database

The classes and interfaces JDBC is located within the package java.sql

Process of working with JDBC

The JDBC worker process consists of the following steps:

  1. Connect to the database (using DriverManager)

  2. Issue SQL statements (using Statement, PreparedStatement, CallableStatement)

  3. Processing the results (ResultSet)

JDBC Driver

Each particular database implements the JDBC interface in a particular way, as do the helper and utility classes that are required for that database

That is why they are necessary drivers of databases

The same application will be able to connect to different databases simply by changing that driver (we should not confuse the database driver with the class Driver, because they are different things)

The interface Driver specifies the methods that any JDBC driver must implement, so drivers can be loaded in two ways:

  1. When you start the class Driver, the DriverManager consultation the property jdbc.drivers

    This property contains a list of drivers (classes) that must be loaded

    To do this, you must run a command like this (to use ODBC) on the command line:

  2. If you want to enter a new driver after the DriverManager is initialized we should use the method forname of the class Class

    To do this we must include in our code the following statement (to use ODBC):

    It is advisable to use of static in our application (because the driver will only load once, when loading the class)

Examples of drivers
Database Driver
ODBC sun.jdbc.odbc.JdbcOdbcDriver
Oracle oracle.jdbc.driver.OracleDriver
SQLServer com.microsoft.jdbc.sqlserver.SQLServerDriver
MySQL com.mysql.jdbcDriver

Tipos de driver:

  • Bridge JDBC-ODBC

    Translates JDBC to ODBC and then relays it to the ODBC driver of the machine

    Is the ODBC driver actually communicates with the database

    Is included in the JDK but does not include JDBC2

    Inconvenience:

    • It's useful for testing, but it's slow in production

    • ODBC driver required on client (lower portability)

  • Driver JDBC on a native driver of the database

    Relays JDBC the native driver installed on the machine

    The native driver is the one that actually communicates with the database

    Drawback:

    • need for native driver (lower portability)
  • Driver Java on network

    Translates JDBC calls into a network protocol independent of the platform that contact with the server

    The server translates these requests to the specific protocol of each database

    It uses a middleware on the network server that is capable of connecting customers with pure Java to many different databases

    Advantage:

    • is fast, platform-independent and requires no installation on the client

  • Driver pure Java and native protocol

    Translates the JDBC calls to the specific protocol of the database by directly contacting it

Get connections

Using the specific driver we will make the connections, but connection requests must be made using the DriverManager

Once the class Driver has been uploaded and registered, the DriverManager you can establish connections to the database by using these two steps:

  1. The method is called DriverManager.getConnection(url, user, pass); and you get an object of type Connection

  2. The DriverManager tests the registered drivers to see if you can establish the connection and if it wasn't possible, launch a SQLException

A single application can have multiple connections to the same database or multiple connections to other databases (up to the maximum allowed by the database)

The parameters supported by getConnection are the url (which is a subprotocol that uses the database to make the connection), the user (the username to be connected) and the pass (the password that the user uses to connect)

The parameter url has the following format:

The subprotocol is particular to each database, and uses the DriverManager to find the proper driver to handle it

The subname depends on the subprotocol specific

The driver will be responsible to interpret and will help you to locate the database

Our app won't work with the specific driver, but will work on the DriverManager

In this way applications can work with the object Connection without worrying about the type of database we're working with (no code modifications need to be made, just change the parameter url)

The connection should always be closed at the end, because otherwise resources are consumed unnecessarily, although connections can be reused, it is not advisable, it is better to always use a new connection

In the example we have used a skeleton of connection to Oracle

To use the connection we need to create an object of type Connection, which represents an open session with the database

The object provides a context with which to issue SQL statements and get results

The object Connection must be initialized to an initial null, so we can check if there was a connection because we'll include a block try to handle bugs, which will launch SQLException

To close the connection must be made using the method close(), within a finaly (which will also have its block try that spear SQLException)

The interface Statement

The connection allows us to create objects Statement by using the method createStatemen()

The objects Statement allow sql statements to be executed and results obtained (using the objects ResultSet)

The methods to execute SQL accept String (JDBC is CLI), which can be composed dynamically based on values contained in variables

To compose the String SQL, concatenate the different SQL fragments (static and variable)

There are three ways to execute SQL statements:

  1. By using the method executeQuery(<sql>) for queries using the statement SELECT that produces tuples as a result (returns an object of type ResultSet)

    • It is like a table that stores the result of the query

    • You have a number of query methods

    • It's like a cursor (in PL/SQL terminology)

  2. By using the method executeUpdate(<sql>) for updates by using the sentences INSERT, DELETE, UPDATE, as well as DDL commands (CREATE, DROP, ALTER TABLE, ADD) and PL/SQL blocks (between begin and end blocks)

    • Returns an integer that indicates the number of rows modified by the command

    • With DDL commands it returns 0

  3. By using the method execute(<sql>) that executes any SQL statement

    • If we used a QUERYReturn True

      • The ResultSet can be obtained by the method getResultSet()

    • If we used a UPDATEReturn False

      • The total number of modified rows can be obtained by using the method getUpdateCount()

After processing the result, the Statement by using the method close()

This method will also close the ResultSet associate, however, Sun recommended closing the ResultSet explicitly to avoid errors unwanted

The same Statement can be reused in the same connection to execute different statements

The interface ResultSet

The object ResultSet acts as a cursor within the results

The first time you read it points to the first result, but does not read it, so you have to read the first row moving forward using the method next()

The method next() returns True if you were able to move forward or False if you could not

To obtain the values of the ResultSet methods are used get that have the following format get<type>(<column>)

To name the columns we can either do it by name or by an index, which starts at 1, their numbering is given by the order in which it was entered in the SELECT

You have to pay attention to the dates, because they are kept as java.sql.Date, not as java.util.Date as you might expect

It should be close ResultSet although it is implicitly closes when you close or reuse the Statement that created it

When you have read a null SQL using one of the methods get<tipo>, it returns:

  • A value null Java for those methods that return Java objects (getString(), getBigDecimal(), getDate(), getTime(), getTimestamp(), getObject(), etc)

  • A value of 0 for those methods that return numeric types (getByte(), getShort(), getInt(), getLong(), getFloat(), getDouble() )

  • A value False for the method getBoolean()

To determine if a given value was null, you must first try to read the column and use the ResulSet wasNull() to know if it was null

Return True yes it was, False otherwise

The interface PreparedStatement

Every time you launch a Statement the database must interpret it and calculate a query plan

But when using PreparedStatement, can be executed multiple times, getting an increase in performance by having the query already analyzed and optimized

Not all databases support PreparedStatement, you have to read the documentation of it to know if they can be used

The objects PreparedStatement derived from the Statement obtained from the connection, using the prepareStatement(<sql>);

A PreparedStatement to launch precompiled SQL statements, you can parameterize one or more entries using the ?, whose values may be changed in different executions of the statement

Parameterize entries is useful when we do not know the values of certain SQL data types in the target database,

The parameterized value gets the correct value from the database driver, so we won't have to worry about the types

Before the SQL statement can be executed we will need to assign a value to the input parameters

To assign values use the methods set<type>(column, value); being the type compatible with the parameter

To run methods are used execute of Statement

In the example we have used a PreparedStatement for Oracle

Python

Python

Python is a widely used programming language currently in Data Science and Big Data related environments

Its use in libraries created by Google and other tech giants has made it one of the most widely used languages

Within programming languages, its features are:

  • Interpreted

    The compilation process is the translation process of the programming language that we are using (e.g. C++) to machine code that the computer can run

    In addition, this process creates an executable file that can be used on other computers

    There are programming languages that do not use a compiling process but an interpreter, which adds meaning to scheduled statements

    Python is an interpreted language

  • Dynamic typing

    Typing a programming language is the language's way of managing variables and their types

    Usually, in a programming language you can create variables of different types (whole number, actual number, character, lists...)

    There are languages in which before we can use a variable we have to define it and assign it a specific type of variable

    In a non-formal language it would be something like: I want an entire variable called Brothers and Assigns the home variable the value 3

    However, in Python you don't need to make this mapping, because it's a dynamic typed language, and you generally don't need to define a variable before you can use it

    In Python we would write directly The variable brothers has a value of 2 and it would be the interpreter who would see that we want to use a variable that does not exist, with the name Brothers and assign the value 2

  • Multi paradigm

    There are several ways to program; with object oriented programming as functional programming

    Python admits both types

  • Multi platform

    There are Python interpreters for multiple platforms, such as MS Windows, Mac OS or Linux

Both the Python interpreter and its extensive standard library are freely available in the form of source code and executable file for major platforms from the Python

Behind Python there is a large community that provides extensive support while constantly developing and updating a centralized library array in a repository called Pypi

There is also a code of good programming practices in Python as well as a style guide, so that the code is easy to read and understand

Installing and using Python modes

Python can be installed on our computer from the Python page (recommended to install the latest version of Python)

However, it is more convenient to install using a distribution such as Anaconda, which downloads the interpreter, different editors and the most used packages and libraries

To install this distribution we would have to:

  1. Go to the downloads page Anaconda and download the package that fits your desired operating system and Python version

    It is recommended to install the one corresponding to the most current version of Python

  2. Run the package and let it install completely on the system
  3. After installation it would be advisable to update the packages

    To do this open a terminal and run:

    It will display a list of libraries to be updated

    If you agree, accept and start downloading and installing the libraries

  4. In the case of wanting to install a specific library, in the terminal we will run:

    You will install the latest version of the library present in the Anaconda repository that corresponds to our operating system and our version of Python

In case it is not present in the repositories, we can optionally install the libraries with pip

To do this open a terminal and run:

For more information, see the Anaconda documentation

The fastest way to use Python is by using command line

Once we have an interpreter installed on our computer, we would open a terminal and write

This opens a console on which we can write and run Python code

Each line we executed would perform the requested operation

It's a very quick way to test code but it's very impractical, as we lose the reuse of executed code

That is, if we wanted to run it again, we would have to write the code line by line again

The most common thing is to use an editor as a Spyder (installs next to Anaconda) the Jupyter notebooks, which is the one I'm going to use for the examples

Jupyter Notebook

Jupyter Notebook (formerly IPython Notebook) is an open source web application that lets you create and share documents that contain live code, equations, visualizations, and narrative text

In addition, it is a widely used application in the field of Data Science to create and share documents that include: data cleansing and transformation, numerical simulation, statistical modeling, data visualization, machine learning and much more

It allows you to edit and run notebook documents through any web browser of your choice; and can run on a local desktop that does not require Internet access or can be installed on a remote server and accessed over the Internet

We can also execute Jupyter Notebook without any installation from the project's website

Or install it using pip, open a terminal and run:

Use Jupyter Notebook

Once we have it installed, we will open a terminal and run:

This will print some information about the notebook server in our terminal, including the web application URL (by default, http://localhost:8888)

In case you need to know the path where we have Jupyter installed, we can run in the terminal:

In case you need to know the version of Python that we have installed, we can run in the terminal:

Before running this one-line command, it is recommended that we verify that our Anaconda PATH directory has been successfully added to the Environment Variables, and if not, we should locate our Anaconda directory/file path and add it to the Environment Variables, or if you could not get an error:

jupyter is not recognized as an internal or external command

If the launch has worked properly, our default browser will open with the Notebook open on port 8888

Once inside the Notebook, we will see a button called New which, when clicked, allows us to select a Python kernel (the options depend on what is installed on our local server) from the drop-down menu

It is recommended to select the latest version of Python that appears in the drop-down, unless you need to use another version for compatibility reasons

Once selected and accepted, we will open our first notebook to write our programs in Python

Our first Python script

Let's write a small sample script to show how simple it is to run a Python script from Jupyter

Python has a defined storage system and variable management

In variables we can save information that we want to use later in the code with a name that is easy for us to remember

In our example, we want to calculate the area and volume of a sphere

The equations we need are:

  • A = 4\pi \cdot r^2 for the area
  • V = \frac{4}{3}\pi \cdot r^3 for the volume

Specifically, we want to calculate these values for a 7 radio sphere

Let's define three variables:

  • r

    It contains the radius value, in this case 7

  • A

    Contains the value of the calculated area

  • V

    Contains the value of the calculated volume

What advantages do we get by defining variables?

If we change our minds and instead of a radio 7 we want it to be 6, we would have to change the number of two sites (which in the case of a program in production could be hundreds)

Or we want the user to indicate the value, so we can't know a priori

To write it in Python we will use a cell of the notebook to which we will assign it in the drop-down menu (we will see it to the left of the icon that looks like a keyboard) the Code value

Once inside the cell, we will use it as a text editor by typing:

To run it we can use the run button or by leaving the uppercase key and then pressing enter

The result of the variables will remain in memory, but we won't be able to see it

Now let's use the print function (similar to the C++ function) to be able to see the result of our Python script

In order to use the constant Pi, the math module has been imported with the statement import math and then we've used it with math.pi

As you can see, to define a variable we write the name with which we want to baptize it, the sign and the expression that we want to be assigned to that variable

Comments on Python

Python supports Unix Shell commentary

Operators in Python

Operators in Python

Python has arithmetic, relational, logical, bit by bit, assignment, membership, and identity operators

Arithmetic operators

Python supplies basic operations with the only additions of the remaining operators, whole quotient and exponentiation

Arithmetic operators
Operator Operation Description
+ Addition Add two operands
Subtraction

Subtract the value of the right operand from the left operand

Used on a single operand, it changes the sign

* Multiplication Multiplication of two operands
/ Division Divide the operand from the left to the right (the result is always a float)
% Rest Gets the rest of dividing the operand on the left by the one on the right
// Integer quotient Gets the integer quotient of dividing the operand from the left to the right operand
** Exponentiation The result is the left operand raised to the power of the right operand

Note In Python, using the + operator applied to strings concatenates both strings into a single

Relational operators

Are used typically in the conditional expression

The relational operators return boolean values

The operands can be numerical or strings

Relational operators
Operator Operation Description
> Greater than

True if the operand on the left is strictly greater than that on the right

False otherwise

< Less than

True if the operand on the left is strictly less than the one on the right

False otherwise

> = Greater than or equal to

True whether the operand on the left is greater than or equal to that of the right

False otherwise

< = Less than or equal to

True if the operand on the left is less than or equal to that of the right

False otherwise

! = Other than that

True if the operands are different

False otherwise

= = Like

True if the operand on the left is the same as the one on the right

False otherwise

Objects of different types, except numeric types, are never compared the same

The operator == it is always defined, but for some types of objects (for example, class objects) it is equivalent to is

Non identical instances of a class are typically compared as non equal unless the class defines the method __eq__()

Instances of a class cannot be sorted with respect to other instances of the same class or other object types, unless the class defines the methods __lt__() and __gt__()


Logical operators

The logical operands is related to the relational as they are normally the operands used are the result of expressions in relational

The resulting values are boolean

Logical operators
Operator Description
AND True if both are True
OR True if one of them is True
NOT It was True moves on to False and vice versa

Bitwise operators

The way of working of these operators is to convert to the binary operands and then operate with them bitwise

Bitwise operators
Operator Operation Description
& AND Change the bit to 1 if both were 1
| OR Change the bit to 1 if one of them was 1
^ XOR Change the bit to 1 if one of them was 1, but not both
~ NOT

Change the bit to 1 if it was 0

Change the bit to 0 if it was 1

<< Propagation to the left Shift the value to the left by entering zeros, if it goes out of range, values are lost
>> Spread to the right Moves the value to the right entering by the left, the sign bit and eliminating the values that are out by the right

Note Propagation operators take two operands: the first is the variable to propagate and the second is the number of positions to propagate

Assignment operators

The assignment is also an operator that returns the variable modified

The mapping operator in Python is =

The assignment operators shown below are but abbreviations that make expressions more comfortable and simple, even if they are sometimes more unreadable

Assignment operators
Operator Expression Equivalence
=

A = B = C

D = ‘Text’

A = C

B = C

D = ‘Text’

+ = A + = 4 A = A + 4
– = A – = 3 * B A = A – (3 * B)
* = A * = 2 A = A * 2
** = A ** = 2 A = A ** 2
/ = A / = 35 + B A = A / (35 + B)
% = A % = B A = A % B
// = A // = B A = A // B
>> = A >> = 1 A = A >> 1
<< = A << = B A = A << B
& = A & = (C + = 3) C = C +3
A = A & C
^ = A ^ = 2 A = A ^ 2
| = A | = C A = A | C

Membership operators

Membership operators are used to check whether a value or variable is in a sequence (list, tuple, dict, set or str)

Membership operators
Operator Expression Equivalence
in Included

Returns True if the value is in a sequence

False otherwise

not in Not included

Returns True if the value is not in a sequence

False otherwise

Identity operators

These operators will be used to check whether or not two variables are the same object

Membership operators
Operator Expression Equivalence
is Equal objects

Returns True if both operands refer to the same object

False otherwise

is not Different objects

Returns True if both operands do not refer to the same object

False otherwise

Preference

The operator precedence will determine the order in which they are running in a given expression

Using parentheses will check that the operations are carried out according to us we want to

In Python, the preference for operators from highest to lowest is as follows:

Preference
Parenthesis ( )
Exponentiation **
Unaries ~ +
Mul / Div / Rest / Div integer * / % //
Addition / Subtract +
Spread << >>
Bit by bit &
Bit by bit ^ |
Relational < < = > > =
Equality = = !=
Assignment = + = – = * = * * = / = // = % = & = | = ^ = >> = << =
Identity is is not
Membership in not in

Data types in Python

Data types in Python

Types in Python are a representation of data because it does not require variables to declare their type, because all types are automatically converted

We can use the function type to know the type of a variable

Type boolean

The Boolean type simply distinguishes between two states, a success or enabled state, true value, True, and a failure or deactivated state, false value, False

Both states are not case sensitive

Typically, the result of operators that return a Boolean value are passed to the control structures

Numeric types

In Python there are 4 different types of numeric variables:

  • int

    integer with fixed precision

  • long

    integer if the size of an int is exceeded

  • float

    double precision floating point number

  • complex

    complex number (real part + j imaginary part)

It is the interpreter who decides the type of variable according to what we define

However, we may want to force it ourselves through a cast

Type string

A string is a string of characters delimited by quotation marks

A string literal can be specified in two different ways:

  • single quote

    are specified between the characters opening and closing

    To specify a literal single quotation mark, you must escape with a backslash (\). To specify a literal backslash, it is duplicated (\\)

    All other instances of backslashes will be treated as a literal backslash: this means that other escape sequences that could be used, such as \r o \n, will be displayed literally as specified, instead of having any other special meaning

  • double quotes

    are specified between the characters " opening and " closing

    Python will interpret the following escape sequences as special characters:

    Code Description
    \n line feed (LF or 0x0A (10) in ASCII)
    \r carriage return (CR or 0x0D (13) in ASCII)
    \t horizontal tab (HT or 0x09 (9) in ASCII)
    \\ backslash
    \" double quotes

Methods

Let's look at some of the most everyday methods for strings

Formatting methods

They affect the formatting of the text contained in the string

  • capitalize()

    Make a copy of the string with the first letter in uppercase

  • lower()

    Returns a copy of the string in lowercase

  • upper()

    Returns a copy of the string in uppercase

  • swapcase()

    Returns a copy of the string in which they are case-sensitive and vice versa

  • title()

    Returns a copy of the string in which the first letter of each word is uppercase and the other lowercase letters

  • center(length, 'fill character')

    Returns a copy of the input string centered on the specified length and between the specified fill character

  • ljust(length, 'fill character'): Returns a copy of the left aligned string

  • rjust(length, 'fill character')

    Returns a copy of the left/right aligned string

  • zfill(length)

    Returns a copy of the string filled with zeros to the left until it reaches the indicated length

Search methods

They allow us to search within a certain string to check whether a substring is contained in the string or how many times a substring appears

  • count (‘substring’)

    Returns an integer representing the number of occurrences of the substring within the string

  • find(‘substring’)

    Returns an integer representing the position at which the substring begins within the string

Validation methods

They always give us back a boolean, that is, True or False

They serve to check if a chain meets a certain condition

  • startswith(‘substring’)

    It tells us if a string starts with a certain string

  • endswith(‘substring’)

    It tells us if a string ends up by a certain string

  • isalnum()

    It tells us if a substring is alphanumeric

  • isalpha()

    It tells us if a string is alphabetical

  • isdigit()

    It tells us if a string is numeric

  • islower()

    It tells us if a string contains only lowercase

  • isupper()

    It tells us if a string contains only capital letters

  • isspace()

    It tells us if a string contains only blanks

  • istitle()

    It tells us if a string is formatted as a title

Substitution methods

They allow us to replace text to unify the format of different strings that have come to us in different ways

  • format(arguments)

    We may have a chain that is prepared to receive a certain amount of arguments

    Calling this function and entering the necessary arguments returns a copy of the already formatted string

  • replace('searched substring', 'substring to put')

    Searches within the string for a substring and replaces it with the indicated string

  • strip()

    Removes the character we specify from the right and left of the string

    By default it looks for the space character

  • lstrip()

    Removes characters to the left of a string

    If we enter a substring as an argument, look for that substring and the combinations of the substring characters from the left until it finds no more

  • rstrip()

    Removes characters to the right of a string

    If we enter a substring as an argument, look for that substring and the combinations of the substring characters from the right until it finds no more

Methods of union and division

They allow us to replace text to unify different strings that have come to us by different ways or to separate a string into several

  • join(iterable)

    It receives as an argument an iterable and returns as a result the elements of the iterable joined by the character of the string on which it is applied

  • partition('separator')

    Returns a 3 elements tuple

    The first element is to the left of the 'separator', the second element is the separator, and the third element is to the right of the separator

  • split('separator')

    Returns a list of all items found when splitting the string by the separator

  • splitlines()

    Returns a list where each item is a fraction of the string divided into lines

Lists

They are defined by putting the contents of the list in square brackets, separating each of the elements by a comma

Each item in the list can contain items of different types

The lists are mutable, that is, their elements can be modified

In Python, items in a list are numbered from 0 to length – 1

To access the item in a list, the name of the list is put and then the index that we want to access (if we put the index with a negative sign will start at the end of the list)

To access a range within a list we have different options:

  • Take items from the start: lista[:a]
  • Take items from position to (included) to end: lista[a:]
  • Take items from a to b (not including b): lista[a:b]

The start of the range always includes the element in that position, but not the end of the range

Methods

Let's look at some of the methods for most everyday lists

  • append()

    adds an item to the bottom of the list

  • insert()

    is used to insert an item into the assigned index

  • pop()

    deletes and returns the value at the position of the assigned index

  • reverse()

    reorders the list in reverse

  • sort()

    rearrange the list in ascending order

We can find all the methods in your documentation

Tuples

Tuples are similar to lists, defined with parentheses instead of brackets

They have the peculiarity of being immutable

As you can see, items are accessed in the same way as with lists

Dictionaries

Dictionaries define a one to one relationship between key value between {} and they're mutable

They are defined by placing a comma separated list of pairs key:value

Once defined, we can access the value associated with a key by searching by key

In addition, we can search whether or not a certain key exists in our dictionary

Dictionaries are a type of collection in Python that, unlike lists, are indexed by words and not by numbers

Values can be of any type

We can think of a dictionary as an unordered set of pairs key:value with the requirement that the keys have to be unique

Methods

Let's look at some of the methods for more everyday dictionaries

  • keys()

    returns us an iterable containing the dictionary keys

  • values()

    returns us an iterable containing the dictionary values

  • items()

    returns us an iterable with the pairs key:value of the dictionary

Objects

Objects consist of a set of values, properties, and a set of methods applied to those values

It is these methods that allow us to modify the state of that object, that is, the value of its properties

In Python, objects have the following characteristics:

  • Everything is an object, including types and classes
  • Allows multiple inheritance
  • There are no private methods or attributes
  • Attributes can be modified directly
  • Allows monkey patching

    Classes are created at run time but can be modified after they are created

  • Allows duck typing

    The dynamic typing style of data in which the current set of methods and properties determines the semantic validity, rather than inheritance of a class

  • Allows operator overload
  • Allows the creation of new data types

Let's create a academic sample object where you have the properties: Name, Surname, Age and Identity card

We'll create the object instance by mapping it to a variable as follows:

It is possible to query the class of an object with the function type, but you can also query through its special attribute __class__

[/tp”]

A su vez las clases tienen un atributo especial __name__ que nos devuelve su nombre en forma de cadena sin adornos:

You can initialize all variables to have the kind we want, we will use the class constructor passing the arguments we need

The constructor is a method that is called automatically when you create an object and is defined with the name __init__ and through the reserved word self we can reference to the current object

If a constructor exists, there must also be a destructor that is called when deleting the object to handle cleanup tasks such as emptying the memory

All objects are automatically deleted from memory at the end of the program, although to remove them automatically we have the special method __del__

It is not advisable to overwrite this method because it is handled automatically, but it is interesting to know that it is possible

The method __str__ is the one that returns the representation of an object in the form of a string

It is called automatically is when we print a variable per screen with the function print

By default the objects print their class and a memory address, but we can change it by overwriting their behavior

For example, for the university object we overwrite the method __str__ to show us the name, age, surname and dni

An interesting special method is the one that returns the length

It is usually linked to collections, but nothing prevents it from defining it in a class and not redefining it, because by default it does not exist in objects even if it is the one that is executed when passed to the function __len__

In our example of the university object it doesn't make much sense to count its length, but I include it to show its use

The properties of an object can be described by other objects or even collections of them

The definition of methods associated with an object can be specified in the object definition

For example, for the university object we overwrite the method __str__ to show the student's first name, age, surname, dni and mean student's notes

To access the properties or methods we will use the operator .

Inheritance

Inheritance is the ability of one class to inherit attributes and methods from another, something that allows us to reuse code

To see its usefulness, let's develop an example by modifying the university object

We will start from a base class that will be the father (superclass) of other daughters who inherited from it (subclasses)

We start from a class Person that will contain all the common attributes and two child classes Student and Teacher who inherit from it and have their own attributes or methods

To inherit the attributes and methods of one class in another, you just have to pass it in parentheses during its definition

It is possible to use the behavior of a superclass without defining anything in the subclass, although in our example we will give them behavior

Thanks to the flexibility of Python we can handle objects of different classes massively in a very simple way

Let's start by creating a list with our two People from different subclasses

One of the few flaws in Python is that if we modify the values within an object, these changes will be reflected outside the same

Just as in collections, objects are passed to functions by reference

It affects when making copies, creating instead an access to the object instead of a new one with its previous values

To make a copy from its values we can use the function copy of the module with the same name

The function copy can also be used to copy collections

Multiple inheritance allows a subclass to inherit from multiple superclasses

This involves a problem, which is that if multiple superclasses have the same attributes or methods, the subclass can only inherit from one of them

In addition to superclasses you can also inherit multiple subclasses

In these cases Python will prioritize the leftmost classes at the time of subclass declaration

We've used the reserved word pass to instruct the interpreter to ignore the body code and use the one in the class object or the superclasses (subclases) we tell you to

Null value

In Python variables can be assigned a value that indicates the empty value, this value is the value NULL

A variable is considered None if:

  • has been assigned the constant None
  • has not passed an attribute to a function

The constant None is insensitive to case sensitive

Control structures in Python

Control structures in Python

For control structures, Python possesses the control statements typical of high-level languages

Variable statement

Variables in Python are not assigned a predefined type

In Python the type of variables depends on the value they contain at all times

Therefore it performs an automatic conversion of types

Python recognizes the following types of values:

  • Numbers
  • Boolean values

    true and false

  • Strings
  • Lists

    data type that associates values with a numeric value by putting the contents of the list in square brackets, separating each of the elements by a comma

  • Tuples

    data type that associates values with a numeric value by putting the contents of the list in parentheses, separating each of the elements by a comma

    They have the peculiarity of being immutable

  • Dictionaries

    type of data that associates a value with a key and allows you to search for those keys

  • Objects

    Created by the programmer or pre-defined by the language

As it is a language with dynamic typing, it is not necessary to tell the interpreter its type of variable, but it is he who decides the type that will assign

The names with which we can name variables in Python follow several rules:

  • Names always start by letter
  • Within the name you can use any letter or number within the utf-8 encoding
  • Python reserved words, which are used in your code syntax, cannot be used

    For more information on these names, see the Python documentation

Note that Python is case sensitive, so two variables with the same name but containing an uppercase letter will be understood as two distinct variables

For example Variable is different of variable

There are also certain conventions to reduce errors and improve readability

To avoid errors it is recommended not to use certain characters:

  • Do not use neither l (l lowercase) neither I (i uppercase), because depending on the type of font used they may be confused with each other or the number 1
  • Do not use Or (o uppercase) because depending on the type of font used it may lead to confusion with the number 0

In order to promote readability, the following suggestions are made:

  • variablename is unreadable, because it's all together and can make it difficult to read
  • variableName is a little more readable, when applying uppercase letter when starting word
  • variable_name is the one that brings the best readability, when applying underscore at word start, which is the most recommended way

The if sentence

The if sentence has the form:

If the condition is true, instruction 1 will be executed; otherwise it is executed if there is instructution 2

The use of the sentence else is optional, so brackets have been used in the definition

If omitted, the instruction block will only be considered when the condition is true

An instruction block is a set of tab statements after the statement if, when jumping from line after the symbol :

They are mandatory as they tell the interpreter that the instruction block belongs to the sentence if

If omitted and the condition was true, the following instruction will be executed

Otherwise, the subsequent instruction will be executed, independent of the condition state

In this way, the omission of tabulations after the sentence if will allow us to write everything on a single line after the symbol :

The elif sentence

We can also use sentences if anities by sentencing elif

Sentences elif work just like a sentence if

But they will only be executed in case the condition of the sentence if was false

We can optionally add a statement else in the end but will only be executed if all the above conditions were false

The while sentence

The while sentence has the form

If the condition is met, the sentence or instruction block is executed and the process is repeated until the condition is no longer met

The for sentence

This loop has a syntax very similar to the for-each Java

Iterates a variable var over all the properties of an object obj that is passed to it

Thus, for each value of var is is executed, the judgments of the loop

Therefore, the loop will have as many iterations as the object's properties, and in each iteration the variable will have the value of the corresponding object's property with that iteration

Its syntax is:

Iterators

In Python there are different structures that are sets of elements, they are called collections

These types of structures are iterable, that is, they can be traversed element by element

Some variable types that are iterable are:

  • Character string (str)
  • List (list)
  • Tuple (tuple)
  • Dictionary (dict)

Its use is useful for traversing collection items such as lists, tuples, or objects

In addition, many times we want to repeat a loop a certain number of times

The function of this can be useful for this range(n)

This function generates an iterable ranging from 0 to n – 1

The break sentence

The break sentence can be placed within a loop or anities loops

When you execute the break sentence exits the loop more internal

To all effects, the break sentence acts as a jump to the sentence following the loop in which it runs

The continue sentence

The continue sentence does not leave the loop but causes the next iteration to run

In the loop while the execution of the continue causes the program flow to jump to the condition

In the for loop the continue execution causes the increment expression to run, and then continue normally with the condition

That is, running the continue prevents the rest of the loop body from running