Category Archives: Java

Java is a language that is purely object oriented, all code is defined in classes

It was defined by the company Sun Microsystems, which was acquired in 2009 by Oracle Corporation

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

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

Javascript

Javascript

JavaScript, just like Java or VRML, emerged to extend the capabilities of the language HTML and get dynamic web pages

JavaScript is not a programming language itself

It is a scriptor or document-oriented language, such as macro languages that have many word processors. You will never be able to make a program written in JavaScript, you can only improve your website by inserting javascript code in it

Utility of JavaScript

JavaScript serves primarily to improve client/server interface management. A JavaScript script embedded in an HTML document allows you to recognize and treat user-generated events locally, that is, on the client. These events can be the journey of the HTML document itself or the management of a form

For example: when the HTML page is a form that allows access to a phone book, you can insert a script that verifies the validity of the user-provided parameters. This test is done locally and does not need network access

On the other hand, you can also use JavaScript to make several options at once; for example, viewing a video within an HTML document or running a Java applet...

Differences with Java

The main difference between JavaScript and Java is that the latter is a complete programming language. Although they share the same syntax

JavaScript is a language that integrates directly into HTML pages. It has as its main features the following:

  • It is interpreted (not compiled) by the client, that is, the source program is executed directly, unlike in the compiled languages, neither object or executable code is generated for each computer on which you want to run that program
  • It's object-based. It is not, like Java, an object oriented programming language (OOP). JavaScript does not employ classes or inheritance or other typical OOP techniques
  • Your code is integrated into the HTML pages, included in the pages themselves
  • You don't need to declare the types of variables to be used, JavaScript performs an automatic type conversion
  • Object snaps are checked at run time. This is a consequence of JavaScript not being a compiled language
  • It is not possible to work directly with files, or automatically write to the hard drive. That's why JavaScript is said to be a safe language for internet users

Use of JavaScript in an HTML document

Inserting an HTML document is done using the SCRIPT mark using the syntax:

The attributes of this mark are:

  • type=“text/javascript”
    Specifies the language of the script. This attribute is required in the absence of the SRC attribute
  • src=url
    The SRC attribute specifies the URL of the script to insert into the document. This attribute is optional, because the script can be inserted directly into an HTML document

It can be specified to insert a script of a particular language into a document and whose source code is in a file specified in a particular url. It can be useful if we want several of our web pages to share the same scripts without having to insert them into each one, repeating the code

Here are some points to keep in mind regarding the introduction of JavaScript in an HTML document:

  • The script inserted via the brand SCRIPT it is evaluated by the client after the display of the page HTML. The defined functions do not execute immediately, depending on the events associated with the page
  • The insertion of the script by using the brand SCRIPT can be placed anywhere in the document HTML but it is recommended to place it in the header, that is, in the area defined by the HEAD. In this way, the script is defined from the beginning of the document, ensuring that the document is visible throughout the document
  • If defined, in addition to the script using the SRC, scripts in the document itself, the client will first evaluate the inserted using the SRC and then included in the document
  • The URL corresponding to a JavaScript have generally the extension .js
  • It is preferable to delimit the scripts inserted into a document-by-document comments HTML to ensure that the contents of the script will not appear on clients that do not recognize the brand SCRIPT. For example:
  • The JavaScript language is not case sensitive, except in literal character strings

Finally, comment on another way to introduce scripts in HTML documents, and is to include these scripts as event handlers for some brands, such as image marks, anchors, links, buttons, etc. Let's look at an example:

Go to the index

As you can see, within this mark, as an attribute of this, an event handler is put and after the equal sign and in quotation marks The JavaScript code is included. However, it is also possible to call a function from the HEAD document. This second option is recommended as it is a cleaner and clearer way to write pages. The same result would be achieved as in the previous example:

Versions of JavaScript

The language was invented by Brendan Eich in Netscape Communications. It first appeared in Netscape Navigator 2.0. Which included JavaScript under the name Mocha, when this version of Navigator appeared it was called LiveScript. It was finally renamed JavaScript in a joint ad between Sun Microsystems and Netscape on December 4, 1995

Traditionally, it had been used in HTML web pages, to perform tasks and operations within the framework of the client-only application, without access to server functions. JavaScript was running in the user's browser at the same time as the statements were being downloaded along with the HTML code. What Netscape wanted is for JavaScript to be a scripting language, easy to use and for anyone to use. After 2 years JavaScript became one of the most used tools by web developers, using almost 90% of web developments, even more than Java and Activex

Netscape introduced a server side script implementation with Netscape Enterprise Server, released in December 1994 (shortly after the release of JavaScript for web browsers)

In 1996 Microsoft began to show great interest in competing with JavaScript so it launched the language called Jscript, which was the implementation of ECMAScript, very similar to Netscape's JavaScript, but with some differences in the object model of the browser that would make both versions incompatible. But version 4.0 of Internet Explorer without any problem supported JavaScript version 1.1. However, Jscript was unable to compete directly with Javascript

In mid 1997, Netscape promoted JavaScript and released version 1.2. This new version included new components that gave great potential to the language, but unfortunately this version only worked on the latest version of the Navigator. The authors proposed that it be adopted as the standard of “the European Computer Manufacturer’s Association” (ECMA, with the ECMAScript implementation), which despite its name was not European but international, based in Geneva. Shortly after it was also proposed as an ISO standard

Version 1.3 was a small revision of 1.2, which was included in version 4.07 of the Netscape Navigator

To avoid these incompatibilities, the World Wide Web Consortium designed the Document Object Model (DOM) standard, which incorporates Konqueror, versions 6 of Internet Explorer and Netscape Navigator, Opera version 7, and Mozilla from its first version

Since mid 2000s, there has been a proliferation of JavaScript implementations for the server side. Node.js is one of the notable examples of JavaScript on the server side, being used in important projects

The arrival of Ajax returned JavaScript to fame and attracted the attention of many programmers. As a result, there was a proliferation of a set of frameworks and libraries of general scope, improving programming practices with JavaScript, and increasing the use of JavaScript outside web browsers, with the proliferation of server-side JavaScript environments. In January 2009, the CommonJS project was inaugurated with the objective of specifying a library to use common tasks mainly for development outside the web browser

In June 2015, the ECMAScript 6 standard (latest version to date) was closed and published with irregular support between browsers and that provides JavaScript with advanced features that were missed and that are commonly used in other languages such as, for example, modules for code organization, true classes for object-oriented programming, date expressions, iterators, generators or promises for asynchronous programming

Comments in JavaScript

The comments in the code allow the author's comments to be inserted to describe the different parts of the program. The JavaScript interpreter ignores them and therefore has a particular syntax

Comments on a single line are distinguished, preceded by the double slash // and comments on several lines delimited by the symbols / * and * /. For example:

Identifiers and reserved words

To know what is the syntax of the identifiers which are reserved words is something that is necessary before you start to write a program in a particular programming language

The identifiers of a language are the string of characters that we assign to the names of variables, constants, functions, objects, etc ..., which we define in that language, these are necessary to be able to invoke said elements in places after their definition

Identifiers must follow the following rules:

  • The identifier must start with a letter or the character '_'
  • The following characters, in addition to letters or the '_' character, can be figures

Note that case is not important, because JavaScript does not differentiate from case names in identifiers. Let's look at some examples of variable names:

First, say that reserved words are special words that are used to increase readability and separate syntactic entities. These words cannot be used as identifiers

Next we will see a table in which all the existing reserved words in JavaScript are shown, these words have or will have a special meaning within the language:


Reserved words
Abstract
Boolean
Break
Byte
Case
Cath
Char
Class
Const
Continue
Default
Do
Double
Else
Extends
False
Final
Finally
Float
For
Function
Goto
If
Implements
Import
In
Instaceof
Int
Interface
Long
Native
New
Null
Package
Private
Protected
Public
Return
Short
Static
Super
Switch
Synchronized
This
Throw
Throws
Transient
True
Try
Var
Void
While
With