Category Archives: Java

Kotlin vs Java. what should i pick for my new android project?

Unlike iOS, where Swift is overtaking Objective-C rapidly and the momentum is clear. In the Android world, presently, the language option is not that clear.

Yes, Kotlin is there, new, coming forward, garden-fresh, 21-century ready but it isn’t ultimately taking off, not as expected.

Kotlin was first introduced by JetBrains in 2011, which is the creator of IntelliJ IDEA, PyCharm, and many other top IDEs. It got its name from ‘Kotlin Island’ in St. Petersburg, Russia. Made to strike Java.

That said, the dominance of Java is still immense, the number of libraries, APIs, code generally speaking is humongous. Not to mention the readability of it, the many algorithms and things done or thought already in Java, yeah… Simple as it sounds, it’s hard to break a solid present for a “uncertain” bright future.

Continue reading Kotlin vs Java. what should i pick for my new android project?

Send an Email from App with Android Intent

Send an Email from App with Android Intent

Intent emailIntent = new Intent(Intent.ACTION_SEND); 

// The intent does not have a URI, so declare the "text/plain" MIME type
emailIntent.setType("text/html");emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] {"david@google.com"}); // recipientsemail

Intent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text...");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));    

// You can also attach multiple items by passing an ArrayList of Uris
startActivity(emailIntent);Log.v("*** MainActivity ***","Intent method called");

Create executable files from Java .jar in Windows

JSmooth is a tool for wrapping Java JAR files into Windows Portable Executable EXE files. It allows specifying various details on how the program should be invoked, such as:

  • Executable icon
  • Program arguments
  • Type of wrapper application (console or Windows GUI)
  • Whether to launch the Java VM in the same process as the EXE or a separate process
  • Maximum and initial memory allocation
  • System properties available to the application via the System.getProperty function

JSmooth is distributed under the GNU General Public License, and is written in Java using Swing. Generated executables are built on MinGW, and as such there is no dependency on proprietary software.
Unlike other exe wrappers, JSmooth is 100%-Java, and can be used to create the Windows executable from a Linux compilation-chain (an ANT task is provided).

Download page:

http://sourceforge.net/projects/jsmooth/files/

 

In software, JAR (Java ARchive) is a package file format typically used to aggregate many Java class files and associated metadata and resources (text, images, etc.) into one file to distribute application software or libraries on the Java platform.

JAR files are fundamental archive files, built on the ZIP file format and have the .jar file extension. Computer users can create or extract JAR files using the jar command that comes with a JDK. They can also use zip tools to do so; however, the order of entries in the zip file headers is important when compressing, as the manifest often needs to be first. Inside a JAR, file names are unicode text.

To create .jar files with netbeans follow these steps:

1 Click on Properties
2 Click on Packaging
3 Click on Compress JAR File
4 Accept changes, click ok
5 Click the button in the ribbon tab with the hammer/broom. (clean and build project)
6 Go to the directory where your project is stored
7 Look in the dist folder for your .jar file

Javadocs

Javadoc es una utilidad de Oracle para la generación de documentación de APIs en formato HTML a partir de código fuente Java. Javadoc es el estándar de la industria para documentar clases de Java. La mayoría de los IDEs los generan automáticamente.


Javadoc también proporciona una API para crear doclets y taglets, que le permite analizar la estructura de una aplicación Java. Así es como JDiff puede generar informes de lo que ha cambiado entre dos versiones de una API.


Para generar APIs con Javadoc han de usarse etiquetas (tags) de HTML o ciertas palabras reservadas precedidas por el carácter “@”. Estas etiquetas se escriben al principio de cada clase, miembro o método, dependiendo de qué objeto se desee describir, mediante un comentario iniciado con “/**” y acabado con “*/”.


Netbeans ayuda en la generación de Javadocs de modo automático.


Las etiquetas en Javadocs son:

Tag Descripción
@author Nombre del desarrollador.
@deprecated Indica que el método o clase es antigua y que no se recomienda su uso porque posiblemente desaparecerá en versiones posteriores.
@param Definición de un parámetro de un método, es requerido para todos los parámetros del método.
@return Informa de lo que devuelve el método, no se puede usar en constructores o métodos “void”.
@see Asocia con otro método o clase.
@throws Excepción lanzada por el método
@version Versión del método o clase.



Un ejemplo de un Javadoc de un método:

/**
  * Inserta un título en la clase descripción.
  * Al ser el título obligatorio, si es nulo o vacío se lanzará
  * una excepción.
  *
  * @param titulo El nuevo título de la descripción.
  * @throws IllegalArgumentException Si titulo es null, está vacío o contiene sólo espacios.
  */
 public void setTitulo (String titulo) throws IllegalArgumentException
 {
   if (titulo == null || titulo.trim().equals(""))
   {
       throw new IllegalArgumentException("El título no puede ser nulo o vacío");
   }
   else
   {
       this.titulo = titulo;
   }
 }

Recursion – The basics

Recursion – The basics

 

COMPUT: a programming technique where a routine performs its task by delegating part of it to another instance of itself.

Introduction
For new computer science students, the concept of recursive programming is often difficult. Recursive thinking is difficult because it almost seems like circular reasoning. It’s also not an intuitive process; when we give instructions to other people, we rarely direct them recursively.

For those of you who are new to computer programming, here’s a simple definition of recursion: Recursion occurs when a function calls itself directly or indirectly.

A classic example of recursion
The classic example of recursive programming involves computing factorials. In mathematics, the factorial of a nonnegative integer, n (denoted n!) is the product of all positive integers less than or equal to n. For example, 5! is the same as 5*4*3*2*1, and 3! is 3*2*1.

An interesting property of a factorial is that the factorial of a number is equal to the starting number multiplied by the factorial of the number immediately below it. For example, 5! is the same as 5 * 4! You could almost write the factorial function as:

int factorial(int n)
{
   return n * factorial(n - 1);
}

Listing 1. First cut factorial function

However, there is a small problem with this; it will run forever because there is no place where it stops calling itself. It therefore needs a condition to tell it to stop. Since a factorial is for positive numbers only it makes sense to stop the recursion when the input is 1 and return 1 as the result. The modified code will look like this:

int factorial(int n)
{
   if(n == 1)
   {
      return 1;
   }
   else
   {
      return n * factorial(n - 1);
   }
}

Listing 2. better factorial function

As you can see, as long as the initial value is above zero, this function will terminate. Note that more work will need to be done to guard again invalid initial values.

The point at with the recursion is stopped is called the base case. A base case is the bottom point of a recursive program where the operation is so trivial as to be able to return an answer directly. In the case of a factorial 1! = 1. All recursive programs must have at least one base case and must guarantee that they will hit one eventually; otherwise the program would run forever or until the program ran out of memory or stack space.

recursion

Basic steps of recursive programs
All recursive programs follows the same basic sequence of steps:
1: Initialize the algorithm. Recursive programs often need a seed value to start with.
2: Check to see whether the current value(s) being processed match the base case. If so, process and return the value.
3: Redefine the answer in terms of a smaller or simpler sub-problem or sub-problems.
4: Run the algorithm on the sub-problem.
5: Combine the results in the formulation of the answer.
6: Return the results.

 

Advantages and drawbacks of recursion

Main advantage of recursion is programming simplicity. When using recursion, programmer can forget for a while of the whole problem and concentrate on the solution of a current case. Then, returning back to the whole problem, base cases (it’s possible to have more than one base case) and entry point for recursion are developed.

On the other hand, recursion has a serious disadvantage of using large amount of memory. Moreover, for most programming languages, recursion use stack to store states of all currently active recursive calls. The size of a stack may be quite large, but limited. Therefore too deep recursion can result in Stack Overflow. To resolve this problem recursion can be simulated, using loop and stack data structure.

Method Vs Function

Method Vs Function

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

1. It is implicitly passed the object for which it was called

2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class – the class is the definition, the object is an instance of that data)
(this is a simplified explanation, ignoring issues of scope etc.)

Summarizing…

A method is on an object.A function is independent of an object.

For Java, there are only methods.For C, there are only functions.

For C++ it would depend on whether or not you’re in a class.

Easy reading from Keyboard in Java

We can use Scanner class

Import first:

import java.util.Scanner;

Then we go this way for integers.

Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();

If we rather a string line:

String text= scan.nextLine();

Easy piece!

Note: If you are using nextInt() with nextLine() it may probably could have some trouble cause nextInt() does not read the last newline character of input and so nextLine().