Cognitionis
The little I know

Java Basic Kit


Java is an interpreted OO programming language originally developed by Sun Microsystems and released in 1995 as a core component of Sun Microsystems’ Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities.

Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture (architecture independent).

Java 6 Duke Java Mascot

The java architecture, for example the J2SE (Java 2 Standard Edition) 1.5 (2004) is defined as follows:

JAVA

As we can see, it is multi-platform, and depending on what package you install: jre (runetime, to be able to execute software), jdk (development kit for be able to create software) you have access to more or less elements. Obviousely, both include the multiplatform JVM.

ANT, java page (XML based setup/install facility for java programs)

Basic Java concepts

Java source: .java files. A source file represents a class (Java is a strict OO language)

Java compiler expects UTF-8 encoded source files. If not use:

javac -encoding ISO-8859-1 source.java

Internally variables use UTF-16BE encoding, but when they are printed through System.out, etc as inherited from system encoding. To be sure which is it just do:  System.out.println(“ecoding= ” + System.getProperty(“file.encoding”));

Java compiled sources (bytecode): .class files

JAR (Java ARchive): Also known as packages, they are aggregates many files into one. Software developers generally use .jar files to distribute Java classes and associated metadata.

Mainfest: A JAR file has an optional manifest file located in the path META-INF/MANIFEST.MF. The entries in the manifest file determine how one can use the JAR file. JAR files intended to be executed as standalone programs will have one of their classes specified as the “main” class (Main-Class: packagepath.MyClass).

WAR (Web Application aRchive):  files, also Java archives, store XML files, Java classes, JavaServer Pages and other objects for Web Applications.

Compilation:

javac Classname.java —> Source.class

Execution:

java Classname_withoutextension —> it is only possilbe if it has a main function.

ExampleProgram.java:

import java.io;
class ExampleProgram {
public static void main(String[] args){
System.out.println(“I’m a Simple Program”);
}
}

Compilation: javac ExampleProgram.java
Execution:   java ExampleProgram

To Remember:
1. Java classes start always by a Capitalized letter.
2. When executing a program you do not have to put .class extension (only the name of the class)
3. If using packages use: java packagename.classname

CLASSPATH (place where classes are)
—-> You can define it by an environement variable CLASSPATH (separing paths by :)
Normally you modify .bashrc and .bash_profile to make it automatically

—-> You can define it online by:           java -cp path:otherpath:… executable
Normally you use this option only for quick tests

————————————

Creation of JAR files

jar cf jar-file input-file(s)/directorie(s)
jar cvf TicTacToe.jar TicTacToe.class audio images
jar cvf TicTacToe.jar *
jar cvmf file.jar mymanifest input-file(s)/directorie(s)

c: create
f: in a file
v: verbose (pring creation process)
m: include a manually created mainfest file. Warning: The manifest must end with a new line or carriage return.
The last line will not be parsed properly if it does not end with a new line or carriage return.

Now that you’ve learned how to create JAR files, how do you actually run the code that you’ve packaged? Consider these three scenarios:

  • Your JAR file contains an applet that is to be run inside a browser.
  • Your JAR file contains an application that is to be invoked from the command line.
  • Your JAR file contains code that you want to use as an extension.

Extensions (libraries): JAR files can work as extensions/libraries including them into the classpath or directly in the developed package. The second option is better if you want your program to work in machines where may be the library is not present. To do this, make a lib folder into your java project folder and link code with relative path (Easy using an IDE like Netbeans).

Applets:

The ARCHIVE parameter specifies the relative path to the JAR file that contains TicTacToe.class. This example assumes that the JAR file and the HTML file are in the same directory. If they’re not, you would need to include the JAR file’s relative path in the ARCHIVE parameter’s value. For example, if the JAR file was one directory below the HTML file in a directory called applets, the APPLET tag would look like this:

<applet code=TicTacToe.class
        archive="applets/TicTacToe.jar"
        width=120 height=120>
</applet>

Compilation and execution of packages:

java -jar foo.jar

IDE

USE NetBens IDE it makes all of it a lot easier.

JAVADOC

Study javadoc and post here.

ANT Apache ANT

Para instalar con un build.xml (Para instalar descaragr copiar en c:\ant\ y poner el bin en el path
establecer JAVA_HOME y ANT_HOME

Para ejecutar escribir ant en el directorio donde haya un build.xml

INTERESTING LIBRARIES

http://commons.apache.org/

json

lang (String treatment, to strings, XML, escape XML, escape XHTML…)

cli (for command line options)

Asignación y paso de variables (difer. con C/C++)

IMPORTANTE

Es muy importante saber que en Java todas las variables se pasan a las funciones por referencia-valor. Es un poco distinto que C. Si pasamos objeto o y dentro de la función llamamos a o.modificarvariable() la variable será globalmente modificada. En cambio si asignamos o=new Objeto(“hola”) la variable o original que apuntaba a otro objeto permanecera igual y el nuevo o sera un objeto totalmente diferente válido sólamente dentro de la función. ES DECIR una variable es un apuntador que cambia al hacer new.

EN CAMBIO, si hago new pero luego asigno otro objeto:

a= new Integer(3);

a=b;

b++;

a no se habrá incrementado porque es un Objeto considerado de tipo básico (Integer, int, boolean,…) pero si fuera un objeto normal en el que dentro hay una variable privada de tipo int.

a= new MyInteger(3);

a=b;

b.inc();

a también se habrá incrementado puesto que a ahora es exáctamente una copia por referencia de b.

Vamos complejito.

Herencia y Polimorfismo

Clases abstractas e Interfaces

En java tenemos dos tipos principales de herencia.

Si yo defino la clase abstracta figura de la cual heredan (INHERIT) las propiedades las clases cirulo y cuadrado, puedo querer hacerlo de dos formas. (OJO: comprobar q Las clases abstractas tambien pueden incluir métodos vacios que luego deben ser implementados en las classes q heredan de estas).

1. Interface

Definir la classe figura como un patron de lo que debe poder hacer cualquier figura (variables y funciones vacias).

Al heredar class X implements Y -> significará que X debe implementar TODOS los métodos de Y

2. Clase abstracta

Definir la clase abstract figura con las propiedades y metodos básicos que el resto de figuras tendrán. En este caso pueden estar implementados en la propia figura o estar parcialmente implementados en la figura y ser extendidos o redefinidos (OVERRIDE) en las classes circulo y cuadrado. Además en este tipo de herencia las clases circulo y cuadrado pueden implementar nuevos métodos que no tienen pq compartir mientras q en las interfaces si deberían hacerlo.

class X extends Y -> significará que X hereda todo lo que Y contiene, pudiendo modificarlo o incluir nuevos métodos.

También se pueden hacer pirulas como que una classe abstracta implemente parte de una interface y las classes q hereden de la abstracta implementen todas las del interface que la abstracta no había implementado…

Regular Expressions

Java works well with UTF-8 source code and UTF-8 files (cadena.match(“é”))

Regular expressions in java are implemented in Strings (basic match).

For replacements and complex matches and finds use java.utils.RegExp.Pattern…

Arrays

Arrays in Java are great for working with a fixed numbers of elements, but Java also has the Collections library of classes that are a better choice when working with a variable number of objects, eg, ArrayList.

Array -> String[] a=new String[100];  // fixed size

ArrayList -> ArrayList<String> a;       // dynamic size

Collections (Lists, Sets and Maps)

HACER NUEVOS APUNTES CON LAS IMAGNES

Java-collection

TB ESTUDIAR LOS CASOS LINKED PARA CUANDO INTERESEN (MANTINENE EL ORDEN DE INSERCION)

El rendimieento es obvio. Lo más rápido es un Array/Vector/List, luego un Hash y lo más leento un Tree

Collections.tab

The three most significant types of Collections framework are:
-List

list
-Set

Set
-Map

Map

Hashtable??

First,look into the hierarchy of collection interfaces:

java.util.Collection <———java.util.List
java.util.Collection <——— java.util.Set
java.util.Collection <——— java.util.SortedSet

Collection interface is the root interface of collection hierarchy.

List interface is most commonly used collection type. LinkedList and ArrayList are its well known implementing classes. Lists can store objects only and not primitive types like int but one can create Integer objects.All objects in List are indexed from 0 to (size of list-1).

Set

Just a bag of any kind of objects without duplicates.

is very much like list but with added constraint of not storing duplicate values. Sets do not impose a 0..size-1 indexing of the elements (that’s what Lists do), so List methods like get(int index) are not available for sets.

HashSet is mostly used set which only works with elements, like String and Integer, which have a hashCode() defined. The TreeSet is an alternative which has performance issues, but keeps the set in sorted order, so iteration will yield the values in sorted order.

java.util.Collection <———–java.util.Map

A Map

A set in which each element maps ONE key to ONE value (The rest is the same)

is altogether different from List and Set. It stores key-value pairs and any value can quickly be searched on the basis of a key. A map cannot contain duplicate keys; each key can map to at most one value. ‘Map’ is a basic interface being implemented by classes HashMap and TreeMap. HashMap is most commonly used which can store objects in unordered fashion while TreeMap can store in ordered fashion. Some implementations of Map prohibit null keys and values and some have restrictions on type of their keys.You may get NullPointerException or ClassCastException when trying to insert or retrieve invalid keys or values.

Hash (unsorted)

Tree (Sorted)

Exceptions

Pease read this -> http://onjava.com/onjava/2003/11/19/exceptions.html

NIO

New I/O or Non-blocking I/O, usually called NIO, is a collection of Java programming language APIs that offer features for intensive I/O operations. It was introduced with the J2SE 1.4 release of Java by Sun Microsystems to complement an existing standard I/O.

Features and organization

The APIs of NIO were designed to provide access to the low-level I/O operations of modern operating systems. Although the APIs are themselves relatively high-level, the intent is to facilitate an implementation that can directly use the most efficient operations of the underlying platform.

The Java NIO APIs are provided in the java.nio package and its subpackages. The documentation by Sun Microsystems identifies these features.

[edit] NIO buffers

NIO data transfer is based on buffers (java.nio.Buffer and related classes). These classes represent a contiguous extent of memory, together with a small number of data transfer operations. Although theoretically these are general-purpose data structures, the implementation may select memory for alignment or paging characteristics, which are not otherwise accessible in Java. Typically, this would be used to allow the buffer contents to occupy the same physical memory used by the underlying operating system for its native I/O operations, thus allowing the most direct transfer mechanism, and eliminating the need for any additional copying. In most operating systems, provided the particular area of memory has the right properties, transfer can take place without using the CPU at all. The NIO buffer is intentionally limited in features in order to support these goals.

There are buffer classes for all of Java’s primitive types except boolean, which can share memory with byte buffers and allow arbitrary interpretation of the underlying bytes.

[edit] Usage

NIO buffers maintain several pointers that dictate the function of its accessor methods. The NIO buffer implementation contains a rich set of methods for modifying these pointers:

  • The flip() method, rather than performing a “flip” or paging function in the canonical sense, moves the position pointer to the origin of the underlying array (if any) and the limit pointer to the former position of the position pointer.
  • Three get() methods are supplied for transferring data out of a NIO buffer. The bulk implementation, rather than performing a “get” in the traditional sense, “puts” the data into a specified array. The “offset” argument supplied to this method refers not to the offset from within the buffer from which to read, nor an offset from the position pointer, but rather the offset from 0 within the target array.
  • Unless using the absolute get() and put() methods, any get() or put() is conducted from the position pointer. Should one need to read from a different position within the underlying array, whilst not adjusting the writing position, the mark() and reset() methods have been supplied.
  • The mark() method effectively stores the position of the position pointer by setting the mark pointer to the position of the position pointer. The reset() method causes the position pointer to move to the mark pointer’s position.
  • It should be noted that the clear() method and the flip() method both return the mark pointer to 0.
  • It should be noted that the clear() method does not ensure zero-ing of the buffer, but does return the limit pointer to the upper boundary of the underlying array, and the position pointer to the index.
  • put() and get() operations for NIO buffers are not thread safe.
  • You can only map() a java.nio.MappedByteBuffer from a java.nio.channels.FileChannel up to Integer.MAX_VALUE in size (2GiB); regions beyond this limit can be accessed using an offset greater than zero.

[edit] Channels

Channels (classes implementing the interface java.nio.channels.Channel) are designed to provide for bulk data transfers to and from NIO buffers. This is a low-level data transfer mechanism that exists in parallel with the classes of the higher-level I/O library (packages java.io and java.net). A channel implementation can be obtained from a high-level data transfer class such as java.io.File, java.net.ServerSocket, or java.net.Socket, and vice versa. Channels are analogous to “file descriptors” found in Unix-like operating systems.

File channels (java.nio.channels.FileChannel) can use arbitrary buffers but can also establish a buffer directly mapped to file contents using memory-mapped I/O. They can also interact with file system locks. Similarly, socket channels (java.nio.channels.SocketChannel and java.nio.channels.ServerSocketChannel) allow for data transfer between sockets and NIO buffers.

FileChannel can be used to do a file copy, which is potentially far more efficient than using old read/write with a byte array. The typical code for this is:

 // Getting file channels
 FileChannel in = new FileInputStream(source).getChannel();
 FileChannel out = new FileOutputStream(target).getChannel();

 // JavaVM does its best to do this as native I/O operations.
 in.transferTo (0, in.size(), out);

 // Closing file channels will close corresponding stream objects as well.
 out.close();
 in.close();

[edit] Selectors

A selector (java.nio.channels.Selector and subclasses) provides a mechanism for waiting on channels and recognizing when one or more become available for data transfer. When a number of channels are registered with the selector, it enables blocking of the program flow until at least one channel is ready for use, or until an interruption condition occurs.

Although this multiplexing behavior could be implemented with Java threads, the selector can provide a significantly more efficient implementation[citation needed] using native platform threads or, more likely, even lower-level operating system constructs. A POSIX-compliant operating system, for example, would have direct representations of these concepts, select(). A notable application of this design would be the common paradigm in server software which involves simultaneously waiting for responses on a number of sessions.

[edit] Character sets

In Java, a character set is a mapping between Unicode characters (or a subset of them) and bytes. The java.nio.charset package of NIO provides facilities for identifying character sets and providing encoding and decoding algorithms for new mappings.

[edit] Regular expressions

The regular expression library in the java.util.regex package provides a powerful search facility for character data based on regular expression matching.

The following example was adopted from the NIO API guide examples, where there are more examples.

 import java.io.*;
 import java.nio.*;
 import java.nio.channels.*;
 import java.nio.charset.*;
 import java.util.regex.*;

 public class Grep {

     // Charset and decoder for ISO-8859-15
     private static Charset charset = Charset.forName("ISO-8859-15");
     private static CharsetDecoder decoder = charset.newDecoder();

     // Pattern used to parse lines
     private static Pattern linePattern = Pattern.compile(".*\r?\n");

     // The input pattern that we're looking for
     private static Pattern pattern;

     // Compile the pattern from the command line
     private static void compile(String pat) {
         try {
             pattern = Pattern.compile(pat);
         } catch (PatternSyntaxException x) {
             System.err.println(x.getMessage());
             System.exit(1);
         }
     }

     // Use the linePattern to break the given CharBuffer into lines, applying
     // the input pattern to each line to see if we have a match
     private static void grep(File f, CharBuffer cb) {
         Matcher lm = linePattern.matcher(cb);  // Line matcher
         Matcher pm = null;                     // Pattern matcher
         int lines = 0;
         while (lm.find()) {
             lines++;
             CharSequence cs = lm.group();      // The current line
             if (pm == null)
                 pm = pattern.matcher(cs);
             else
                 pm.reset(cs);
             if (pm.find())
                 System.out.print(f + ":" + lines + ":" + cs);
             if (lm.end() == cb.limit())
                 break;
         }
     }

     // Search for occurrences of the input pattern in the given file
     private static void grep(File f) throws IOException {

         // Open the file and then get a channel from the stream
         FileInputStream fis = new FileInputStream(f);
         FileChannel fc = fis.getChannel();

         // Get the file's size and then map it into memory
         int sz = (int)fc.size();
         MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);

         // Decode the file into a char buffer
         CharBuffer cb = decoder.decode(bb);

         // Perform the search
         grep(f, cb);

         // Close the channel and the stream
         fc.close();
     }

     public static void main(String[] args) {
         if (args.length < 2) {
             System.err.println("Usage: java Grep pattern file...");
             return;
         }
         compile(args[0]);
         for (int i = 1; i < args.length; i++) {
             File f = new File(args[i]);
             try {
                 grep(f);
             } catch (IOException x) {
                 System.err.println(f + ": " + x);
             }
         }
     }
 }