2016

12/18/2016

Algoritmos y Programas


La naturaleza  de la programación es dificil de entender sin una visión de los conceptos basicos que en ella se emplean. 

En este post te explicaré conceptos básicos que todo entuciasta de la programación debe conocer.

Algoritmo

Los algoritmos son una secuencia de comandos que de forma ordenada son empleados para resolver problemas concretos. Deben de tener finitud, definibilidad, entradas, salidas y efectividad.

Caracteristicas del Algoritmo

  1. Finitud: Los algoritmos deben ser finitos, es decir, deben acabar tras un número finito de pasos. Es más, es casi fundamental que sea un número razonable de pasos.
  2. Definibilidad: Cada paso del algoritmo debe ser definido de forma precisa, es decir, se debe evitar toda ambigüedad al definir cada paso. 
  3. Entrada: Cada algoritmo tendrá cero o más entradas, estas son las cantidades dadas antes de comenzar el algoritmo. Estas cantidad pertenecen además a conjuntos especificados de objetos.
  4. Salida: El algoritmo puede tener una o más salidas.
  5. Efectividad: Debe permitir a cualquier persona realizar el algoritmo de modo exacto y sin ayuda de una máquina en un lapso de tiempo finito.

Programa

Los programas son la implementación de algoritmos en un lenguaje de programación.


Los programas son un conjunto ordenados de instrucciones pasadas al ordenador indicándole las operaciones o tareas que el ordenador deba ejecutar para dar solución a un determinado problema.

Lenguajes de Programación

Una instrucción es un conjunto determinado de símbolos los cuales representan una orden para el ordenador: la ejecución de operaciones con datos.

Estas instrucciones son escritas en un lenguaje de programación:
  • Se forman con símbolos tomados de un determinado repertorio (componentes léxicos que dependen del lenguaje de programación)
  • Se construyen siguiendo reglas precisas (sintaxis).
Los lenguajes de programación se pueden clasificar en:
  • Lenguaje Máquina: Este lenguaje es el único que entiende la CPU del ordenador
    • Depende del modelo de ordenador.
    • Repertorio de instrucciones reducido (operaciones muy elementales)
    • Muy difícil programar en él (en binario, con cadenas de ceros y unos)
  • Lenguaje Ensamblador: Equivalente al lenguaje máquina, cada linea de código se traduce en una instrucción para la máquina.
    • Le asocia mnemónicos a las operaciones que entiende la CPU.
    • Repertorio de instrucciones reducido (operaciones muy elementales)
    • Programas difíciles de entender.
  • Lenguaje de Alto Nivel: Permiten que el programador exprese el procesamiento de datos de forma simbólica, sin tener en cuenta detalles específicos de la máquina.
    • Independientes del modelo de ordenador.
    • Proporcionan un mayor nivel de abstracción.

Clasificación de los lenguajes de programación de alto nivel

  • Lenguajes Imperactivos: Estos programas indican al ordenador de forma enequívoca los pasos a seguir para la resolución de un problema.
    • Programación Estructurada: La estructura del programa debe auxiliarnos para entender la función que realiza: estrategia "divide y venceras" (La resolución de un problema se divide en tareas y, éstas, en subtareas). Ejemplos: C, Pascal, Fortran...
    • Programación Orientada a Objetos: Estilo de programación que basa la estructura de un programa en módulos deducidos a los tipos de objetos que manipula (en lugar de basarse en las tareas que el sistema debe realizar). Ejemplos: Smalltalk, C++, Java, C#...
  • Lenguajes Declarativos (funcionales y lógicos):  Los programas se implementan como conjunto de funciones (o reglas lógicas) cuya evaluación nos dará el resultado deseado. Ejemplos: List, Prolog..

Traductores

Los traductores transforman programas escritos en un lenguaje de alto nivel en programas escritos en código entendibles para la máquina.

Tipos de traductores

Compiladores

Generan programas ejecutables a partir de código fuente.

Intérpretes

Analizan, traducen y ejecutan las instrucciones del programa una por una. No se traduce una instrucción hasta que la ejecución de la anterior haya finalizado.

Herramientas de programación

Entre las herramientas de programación que no deben faltar tenemos:

  • Editores: Es la herramienta usada para tipear el código fuente. En estos podemos encontrar los siguientes:
    • IDEs (Entornos de desarrollo integrados, ejemplos. Eclipse, Netbeans)
    • Editores de texto planos (NotePad++, WordPad etc)
  • Depuradores: Es la herramienta usada para depurar el código fuente con la finalidad de dectectar posibles problemas que este presente.

Desarrollo de aplicaciones informáticas:

Ciclo de vida del software

El ciclo de vida de una aplicación comprende las sigiuentes etapas:
  • Planificación: Delimitación del ámbito del proyecto, estudio de viabilidad, análisis de riesgos, estimación de costos, planificación temporal y asignación de recursos.
  • Análisis (¿Qué?: Ellicitación de requisitos. Descripción clara y completa de qué es lo que se pretende, incluyendo la presentación de los resultados que se desean obtener (formato de las salidas) y la forma en que se va a utilizar la aplicación (interfaz del usuario)
  • Diseño (¿Cómo?): Estudio de alternativas. 
    • Diseño Arquitectónico: Organización de los distintos módulos que compondrán la apliacación (diseño arquitectónico).
    • Diseño Detallado: Definición de los algoritmos necesarios para implementar la aplicación en lenguaje natural, mediante diagramas de flujo o en pseudocódigo [Lenguaje Algorítmico]
  • Implementación: Adquisición de componentes, creación de los módulos de la aplicación en un lenguaje de programación e integración de los recursos necesarios para que el sistema funcione.
  • Depuración y pruebas: Comprobación del funcionamiento de la aplicación Pruebas de Unidad y de Integración, pruebas alfa, pruebas beta, test de aceptación.
    • Verificación (Si se está realizando lo que se pretendía)
    • Validación (Si se realiza lo correcto)
  • Explotación: Uso y Mantenimiento
    • Mantenimiento Correctivo: Corrección de defectos o errores.
    • Mantenimiento Adaptativo: Adaptación de la aplicación a nuevas circunstancias e inclusión de nuevas prestaciones.

Estos son conceptos básicos que todo programador debe dominar. Suerte en tu aprendizaje....

11/20/2016

La Clase Object. La SuperClase en JAVA


Es la clase base de las clases en JAVA. Cada una de las clases JAVA extienden de esta super clase, con la finalidad de proporcionar una serie de métodos de utilidad general que pueden ser utilizados por todos los objetos, en la documentación de JAVA podrás encontrar información de estos métodos.



Ubicación de la clase Object

La ubicación de esta clase se en cuentra en el paquete java.lang 

Extendiendo la de la clase Object

Para extender de esta clase no es necesario utilizar la palabra reservada extends, de esto se encarga la JVM. 


Algunos Metodos de la clase Object.

Entre los métodos de la clase Object podemos tener los siguientes:
  • El método equals().
  • El método getClass().
  • El método toString().

Definición del método equals().

Este método es heredado por todas las clases definidas en Java, este puede ser utilizado para comparar dos objetos, esta comparación no es la misma proporcionada por el operador ==, debido a que solamente compara si dos referencias a objetos apuntan al mismo objeto.

Por lo general el método equals() es utilizado para saber si 2 objetos son del mismo tipo y contienen los mismos datos. Este método devuelve dos posibles valores (true, false) devuelve true sólo si los objetos son iguales y falso en el caso contrario.

Este método puede ser sobreescrito por cualquier clase creada en Java

Este método es utilizado para comparar  si un objeto es igual al objeto que llama a este metodo

Definición del método getClass().

Las instancias de la clase Class representan todas las clases e interfaces que están siendo ejecutadas por la aplicación Java. Esta clase no presenta constructores debido a que los métodos son construidos de forma automática por la Máquina Virtual Java (JVM) cuando sus clases son cargadas, o mediante llamadas al método defineClass() del cargador de clases. 

Class es una clase de gran importancia, con ella se pueden realizar peticiones de información sobre objetos, como lo es su nombre o cómo se llama su superclase. 

El método getClass() de la clase Object se puede utilizar para determinar la clase de un objeto. Este devuelve un objeto de tipo Class, el cual contiene información importante sobre el objeto que crea la clase.


Definición del método toString().

Éste método puede usarse para convertir todos los objetos conocidos por el compilador a algún tipo de representación de cadena, la cual dependerpá del objeto.


Download Source Code

Ejemplos.

/**
 * Example to show the overwriting of the toString() and equals() method and the implementation of the getClass()
 */
package com.onlyjava.test;

/**
 * @author OnlyJava
 *
 */
public class TestObject {
/** Object Value */
private Object m_Val = null;
/** String ClassName */
private String className = null;
/** String SupClassName */
private String supClassName = null;
/**
* Construct
*/
public TestObject(Object p_Obj) {
super();
this.className = p_Obj.getClass().getName();
this.supClassName = p_Obj.getClass().getSuperclass().getName();
if(p_Obj instanceof Integer) {
m_Val = (Integer) p_Obj;
} else if(p_Obj instanceof Byte) {
m_Val = (Byte) p_Obj;
} else if(p_Obj instanceof String) {
m_Val = (String) p_Obj;
} else if(p_Obj instanceof Float) {
m_Val = (Float) p_Obj;
} else if(p_Obj instanceof Double) {
m_Val = (Double) p_Obj;
} else if(p_Obj instanceof Boolean) {
m_Val = (Boolean) p_Obj;
}
}
/**
* Main
* @param args
*/
public static void main(String[] args) {
// Instance object to compare
TestObject m_ObjInt = new TestObject(1);
TestObject m_ObjString = new TestObject("1");

System.out.println(m_ObjInt.toString());
System.out.println(m_ObjInt.equals(m_ObjInt));
System.out.println(m_ObjString.toString());
System.out.println(m_ObjString.equals(m_ObjString));
System.out.println(m_ObjString.equals(m_ObjInt));
}
@Override
public boolean equals(Object p_Obj) {
if ((p_Obj != null) 
&& (p_Obj instanceof TestObject)) {
TestObject m_Obj = (TestObject) p_Obj;
return this.m_Val == m_Obj.m_Val;
} else {
return false;
}
}
@Override
public String toString() {
return "[ClassName= " + this.className + ", " 
+ "SuperClassName= " + this.supClassName + "]";
}
}




11/16/2016

Java vs Node.js: An epic battle


Ever, 1995 was an insane time. To begin with, Java showed up, then close on its heels came JavaScript. The names made them appear like conjoined twins recently disengaged, yet they couldn't be more unique. One of them aggregated and statically wrote; the other translated and progressively wrote. That is just the start of the specialized contrasts between these two uncontrollably particular dialects that have since moved onto an impact course of sorts, on account of Node.js.

In case you're mature enough to have been around in those days, you may recall Java's initial, epic pinnacle. It cleared out the labs, and its buildup meter stuck. Everybody considered it to be an unrest that would remain absolutely determined not exactly an aggregate takeover of processing. That forecast wound up being just mostly right. Today, Java overwhelms Android telephones, undertaking processing, and some installed universes like Blu-beam plates.

For all its prosperity, however, Java never settled much footing on the desktop or in the program. Individuals touted the force of applets and Java-based instruments, yet gunk dependably glitched up these mixes. Servers turned into Java's sweet spot. In the interim, what developers at first mixed up as the idiotic twin has made its mark. Without a doubt, JavaScript followed along for a couple of years as HTML and the Web pulled a Borg on the world. In any case, that changed with AJAX.

All of a sudden, the stupid twin had control. At that point, Node.js was produced, stopping people in their tracks with its speed. Not just was JavaScript speedier on the server than anybody had expected, however it was regularly quicker than Java and different alternatives. Its enduring eating routine of little, snappy, unlimited solicitations for information have since made Node.js more basic, as Web pages have developed more dynamic. While it might have been unimaginable 20 years back, the semi-twins have presently secured a fight for control of the programming scene. On one side are the profound establishments of the strong building and engineering. On the opposite side are straightforwardness and pervasiveness. Will the old-school compiler-driven universe of Java hold its ground, or will the speed and adaptability of Node.js help JavaScript keep on gobbling up everything in its way?

Where Java wins: Rock-strong establishment 


I can hear the engineers chuckling. Some may even be passing on of heart disappointment. Yes, Java has glitches and bugs, yet moderately, it's the Rock of Gibraltar. A similar confidence in Node.js is numerous years off. Actually, it might be decades before the JavaScript team composes almost the same number of relapse tests as Sun/Oracle created to test the Java Virtual Machine. When you boot up a JVM, you get 20 years of experience from a strong custodian resolved to overwhelm the undertaking server. When you start up JavaScript, you get the work of a regularly irritable coalition that occasionally needs to team up and once in a while needs to utilize the JavaScript standard to dispatch uninvolved forceful assaults.


Where Node wins: Ubiquity 

On account of Node.js, JavaScript finds a home on the server and in the program. Code you compose for one will more than likely run a similar path on both. Nothing is ensured in life, however, this is more or less close the PC business. It's much simpler to stay with JavaScript for both sides of the customer/server separate than it is to compose something once in Java and again in JavaScript, which you would likely need to do on the off chance that you chose to move business rationale you wrote in Java for the server to the program. Alternately perhaps the supervisor will demand that the rationale you worked for the program be moved to the server. In either heading, Node.js and JavaScript make it much less demanding to relocate code.

Where Java wins: Better IDEs 

Java designers have Eclipse, NetBeans, or IntelliJ, three first-rate instruments that are all around coordinated with debuggers, decompilers, and servers. Each has years of advancement, committed clients, and strong biological communities loaded with modules. In the interim, most Node.js designers sort words into the charge line and code into their most loved content tool. Some utilization Eclipse or Visual Studio, both of which bolster Node.js.

Obviously, the surge of enthusiasm for Node.js implies new apparatuses are arriving, some of which, similar to IBM's Node-RED offer fascinating methodologies, however, they're still far from being as total as Eclipse. WebStorm, for example, is a strong business apparatus from JetBrains, connecting in numerous charge line construct instruments. Obviously, in case you're searching for an IDE that alters and juggles apparatuses, the new instruments that bolster Node.js are adequate. Be that as it may, in the event that you request that your IDE lets you alter while you work on the running source code like a heart specialist cuts open a mid-section, well, Java devices are significantly more intense. It's all there, and it's all neighborhood.

Where Node wins: Build prepare streamlined by utilizing the same dialect

Entangled form instruments like Ant and Maven have upset Java programming. Be that as it may, there's just a single issue. You compose the particular in XML, an information configuration that wasn't intended to bolster programming rationale. Indeed, it's moderately simple to express spreading with settled labels, yet there's as yet something irritating about changing apparatuses from Java to XML only to fabricate something.

Where Java wins: Remote investigating

Java gloats extraordinary apparatuses for checking bunches of machines. There are profound guides into the JVM and expound profiling apparatuses to recognize bottlenecks and disappointments. The Java undertaking stack runs probably the most advanced servers on the planet, and the organizations that utilization those servers have requested the absolute best in telemetry. These checking and investigating apparatuses are very developed and prepared for you to send.

Where Node wins: Database questions

Questions for a portion of the more up to date databases, as CouchDB, are composed in JavaScript. Blending Node.js and CouchDB requires no apparatus moving, not to mention any need to recall language structure contrasts. In the interim, numerous Java designers utilize SQL. Notwithstanding when they utilize the Java DB (in the past Derby), a database written in Java for Java designers, they compose their inquiries in SQL. You would think they would basically call Java techniques, however, you'd not be right. You need to compose your database code in SQL, then let Derby parse the SQL. It's a pleasant dialect, however, it's totally unique and numerous advancement groups require diverse individuals to compose SQL and Java.

Where Java wins: Libraries 

There is a gigantic accumulation of libraries accessible in Java, and they offer probably the most genuine work around. Content ordering apparatuses like Lucene and PC vision toolboxes like OpenCV are two cases of awesome open source extends that are prepared to be the establishment of a genuine venture. There are a lot of libraries written in JavaScript and some of them are astonishing, however, the profundity and nature of the Java code base prevalent.

Where Node wins: JSON

At the point when databases release answers, Java goes to expound lengths to transform the outcomes into Java objects. Designers will contend for a considerable length of time about POJO mappings, Hibernate, and different instruments. Arranging them can take hours or even days. Inevitably, the Java code gets Java questions after the majority of the transformation. Numerous Web administrations and databases return information in JSON, a characteristic piece of JavaScript. The organization is presently so normal and helpful that numerous Java designers utilize the JSON groups, so various great JSON parsers are accessible as Java libraries too. Be that as it may, JSON is a piece of the establishment of JavaScript. You needn't bother with libraries. It's all there and prepared to go.

Where Java wins: Solid building 

It's somewhat difficult to evaluate, yet huge numbers of the mind-boggling bundles for genuine logical work are composed in Java since Java has solid scientific establishments. Sun invested a long energy sweating the points of interest of the utility classes and it appears. There are BigIntegers, expound IO schedules and complex Date code with usage of both Gregorian and Julian timetables. JavaScript is fine for basic undertakings, however, there's a lot of perplexity in the guts. One simple approach to see this is in JavaScript's three unique results for capacities that don't have answers: unclear, NaN, and invalid. Which is correct? All things considered, each has its part - one of which is to drive software engineers nuts attempting to keep them straight. Issues about the more bizarre corners of the dialect seldom cause issues for basic frame work, however, they don't feel like a decent establishment for complex scientific and sort work.

Where Node wins: Speed 

Individuals love to adulate the speed of Node.js. The information comes in and the answers turn out like lightning. Node.js doesn't botch around with setting up isolated strings with the greater part of the locking cerebral pains. There's no overhead to back off anything. You compose basic code and Node.js makes the right stride as fast as could be allowed. This acclaim accompanies an admonition. Your Node.js code better be straightforward and it better work accurately. On the off chance that it stops, the whole server could bolt up. Working framework designers have hauled their hair out making wellbeing nets that can withstand programming botches, however, Node.js discards these nets.

Where Java wins: Threads 

Quick code is awesome, however, it's generally more imperative that it be right. Here is the place Java's additional elements bode well. Java's Web servers are multithreaded. Making different strings may require some serious energy and memory, however, it pays off. On the off chance that one string stops, the others proceed. In the event that one string requires longer calculation, alternate strings aren't famished for consideration (ordinarily). On the off chance that one Node.js ask for runs too gradually, everything backs off. There's just a single string in Node.js, and it will get to your occasion when it's great and prepared. It might look super fast, yet underneath it utilizes an indistinguishable engineering from a one-window post office in the prior week Christmas. There have been many years of work dedicated to building brilliant working frameworks that can juggle a wide range of procedures in the meantime. Why backtrack so as to the '60s when PCs could deal with just a single string?

Where Node wins: Momentum 

Yes, the greater part of our grandparents' lessons about thrift are valid. Squander not; need not. It can be excruciating to watch Silicon Valley's stupid dedication to the "new" and "troublesome," yet now and then clearing out the cruft bodes well. Yes, Java can keep up, yet there's old code all around. Of course, Java has new IO schedules, however, it additionally has old IO schedules. A lot of applet and util classes can act as a burden. Where both win: Cross-assembling from one to the next The civil argument whether to utilize Java or Node.js on your servers can and will continue for a considerable length of time. Rather than most civil arguments, be that as it may, we can have it both ways. Java can be cross-arranged into JavaScript. Google does this every now and again with Google Web Toolkit, and some of its most well-known sites have Java code running in them - Java that was converted into JavaScript.

Java vs. Python: key differences


Java and Python, two programming languages are very different, but both can be useful tools for modern developers. If you are considering to learn how to program for the first time, you can then find Python easy to master. Python syntax is designed to be intuitive and its relative simplicity allows beginners to quickly start an write code for different applications. While Java has a more pronounced learning curve, it is extremely useful for developing applications that will run on any platform.


Dynamic typing versus static typing 

One of the largest differences between Python and Java is that each language's handling of the factors. Java requires an indicate the type of a variable when you declare it for the first time and will not allow you to change the type later in the program. This is known as static typing. On the other hand, Python uses dynamic typing, which allows you to change the type of a variable, replacing an integer with a string, for example. The novice programmer become better familiar with dynamic typing, since you can use the factors as you want to without having to worry too much about their types. Without a ban, many developers argue that static typing to decrease the risk of spreading undetected errors in your program. When the factors need not be explicitly declared bets to use them, it is easy to misspell a variable name and accidentally create a new variable.

Keys versus indentation 

Python is a little weird in that it uses indentation to separate code into blocks. Java, like most other languages, use the keys to define the first and last of each function or class definition. The advantage of using indentation is that it forces him to build your program in a way that is easy to sneer, and there will not be any resulting blunder that is missing a key.

Speed versus portability 

The main advantage of Java is that it can be used to create platform-independent applications. Because any computer or mobile device that can run a Java virtual machine can run a Java application, on the other hand to run Python programs need a compiler that can convert the code in Python code that your operating system in particular can understand. Thanks to the popularity of Java for simple desktop applications and web applications, most of the devices already have a Java virtual machine installed, thus a Java developer can be sure that your application can be used by most users. Having the drawback of that to be run within a virtual machine, the Java program runs more slowly than in Python programs.

Python vs. Java: what is the easiest to use? 

The majority of developers are agree that Python is a language easier so beginner programmers can learn. You will progress faster if you learn Python as preliminary language than Java. However, the popularity of Java implies that this powerful language is crucial if you want to develop applications for Android for example.

Questions

What is your opinion in this discussion Python versus Java?
Which language is easier to use?

Share your thoughts in the comments below.

What is and how the Java Virtual machine?


The Virtual Java machine (JVM) is a genuine snob when you are modifying Java. In contrast to what shows the name, the Java Virtual machine can be experienced in relation to other dialects of programming also.

However, it is not important to understand what is the Java Virtual machine, or even what it does, to have the ability to program in Java. On the other hand, to acclimatize with the inner workings of a machine help to build general knowledge and understanding.

This article of the brushes on the possibility of the Java Virtual machine, which does for you, the absolute most essential advantages and disadvantages. Although I tried to keep it simple and there is no doubt more propelled by writing on the subject, a simple understanding of Java and write computer programs it is normal.

High-level Languages


The semantics of a programming dialect aims to be close to our common dialect, while still being succinct and easy to decipher by a machine. As you probably know, the dialect of programming is totally not the same as machine code, the arrangement of a PC addresses is used to generate and execute a program. This call dialects been abnormal; one or several levels of reflection from the machine code.

Before that run, the first abnormal status code must be translated. A considerable measure of programming interfaces arrange ahead of time (AOT Assembly) for a particular stage. This makes the most competent program at runtime, however far less well with several stages. Java, curiously, works with an average of the dialect of road called Java bytecode and Virtual machine Java.

JVM and Java Bytecode


At the point when your Java extends manufactures, decodes the source code (contained in source documents *. java) to Java bytecode (regularly contained in *.class files). This takes your abnormal status code a stage to machine code, however not exactly there yet. This bytecode is a gathering of small instructions; less demanding to machine translate, however less coherent.

When you run a Java application on your PC, mobile phone, or any other Java stage enabled, basically spend this Java bytecode to the Java Virtual machine. Mediator in machine Java Virtual more often that does not start adding all the bytecode at runtime, taking after the standards of supposedly without a moment to spare set. This makes Java normal, though frequently slight delay when you open an application, but for the most part updates the implementation of the programme in contrast to accumulation.




The critical favorite view of this framework is the extended similarity. Since applications keep running in a virtual machine instead of on your computer, the designer can set and build your application once, that can then be executed on each gadget with a use of the Java Virtual machine. This standard has brought forth the Java brand: "Write once, run all".

Expert: Greater security and compatibility


Apart from the similarity of the code, the Java Virtual machine accompanies several advantages. A standout among the most essential of the relative security of Java projects as a side effect of the Java Virtual machine is. Security, which means that a program that runs on a virtual machine is much more reluctant to frame the client work, or degenerate records, if errors occur.

With: Implementations of different JVM and debugging


One of the fundamental reactions expressed against the similarity of the code and the Java Virtual machine is due to a wide range of application of the last mentioned. The Java Virtual machine is not a bit of programming. Prophet, the owners of Java, is the use of the Java Virtual machine, however others can make theirs in the possibility that complies with various cases viable and legally binding.

These different executions imply that your code can easily run on a Java Virtual machine, however, biting the dust in other. While, practically speaking, you can write the code once and run it all, more baffling code now and then still must be secured in several use the Java Virtual machine to ensure the repair operation.

Do you have any experience of working with the Java Virtual machine? Is this the case, something that I spent here a great opportunity that should be specified?