Vectors

Creating a vector
Creating a vector involves the following steps:

  • Vector declaration – To be able to use a Vector we have to declare it. We do this through expressions of form:

  • Type[] nameVector; or

    Type nameVector[];

    as in the examples below:

    int[] integers;
    String address[];

  • Instantiation – Declaring a Vector does not involve allocating the memory needed to retain the Vector elements. The memory allocation operation, also called the vector instantiation, is always done through the new operator. Example:

  • nameVector = new Type[nrElements];

    where nrElements represents the maximum number of characters the Vector can have. Following the instantiation, you will be allocated nrElements * dimension(Type) to memorize the elements in Vector, where Type has the number of bytes represented by that type.

    v = new int[10];
    //allocate spaces for 10 integers: 40 bytes
    c = new char[10];
    //allocate space for 10 characters: 20 bytes


    The declaration and instantiation of a Vector can be done as follows:

    Type[] nameVector = new Type[nrElements];

  • Initialization
  • This page is under construction !

    Data types and variables

    In Java, data types are divided into two categories: primitive types and
    reference types. Java starts from the premise that anything is an object, therefore the data types should actually be defined by classes and all variables should store instances of these classes. Basically, this is true, but for ease of programming more there are so-called primitive types of data that are common:
      

  • arithmetical
    1.   -Integer: byte (1 octet), short (2), int (4), long (8)
        -real: float (4 bytes), double (8)

      

  • character: char (2 bytes)
  •   

  • logic: boolean (true and false)
  •  
    Vectors, classes and interfaces are reference types. The value of a variable of this type is unlike primitive types, a reference (address of memory) to the value or set of values represented by the variable respective.

    Variables can be primitive type or object references (reference type). Regardless of their type, the variables must be declared and eventually initialized for use.
      

  • Variable declaration: Type nameVariable;
  •   

  • Initializing variables: Type nameVariable = value;   

  • Declaration of constants: final Type nameVariable;
  •  
    There is the possibility to declare and initialize multiple variables or constants of the same type in a single instruction as follows:
       Type variable1[=value1], variable2[=value2],…;

    The Java naming convention includes among others the following criteria:
          – the final variables (constants) are capitalized;
          – variables that are not constant are written as follows: the first letter is small and if the variable name is made up of several lexical atoms then the first letters of the other atoms are written in capital letters.
       Example

    final double PI = 3.14;
    final int MIN=0, MAX = 10;
    int value = 100;
    char c1=’j’, c2=’a’, c3=’v’, c4=’a’;
    long numberElements = 12345678L;
    String myFavoriteDrink = "water";

    Depending on the location where the variables are declared, they are shared in the following categories:
        a. Member variables declared within a class visible to all methods of that class as well as for other classes depending on their level of access
        b. Parameters of methods visible only in that method.
        c. Local variables declared in a method visible only in the method respective
        d. Local variables declared in a block of code visible only in that block
        e. Parameters from exception handling

    class Example {
     // Each variable corresponds to the situation given by
     // its name in the enumeration above
    int a;
    public void method(int b) {
       a = b;
       int c = 10;
    for(int d=0; d < 10; d++) {
       c --;
    }
    try {
       a = b/c;
    } catch(ArithmeticException e) {
       System.err.println(e.getMessage());
        }
      }
    }

  • The variables declared in a local loop are:

  • for(int i=0; i<100; i++) {
       // the field of visibility of i
    }
    i = 101;//incorrect

  • It is not allowed to hide a variable:

  • int x=1;
    {
       int x=2; //incorrect
    }

    Execution control
    Java Instructions can be divided into the following categories:

  • decision instructions: if-else, switch-case
  • jump instructions: for, while, do-while
  • instructions for handling exceptions: try-catch-finally, throw
  • other instructions: break, continue, return, label:
  •  
    Decision instruction
    if-else

    if (logical-expression) {
    ...
    }
    if (logical-expression) {
    ...
    } else {
    ...
    }

    switch-case

    switch (variable) {
    case value1:
    ...
    break;
    case value2:
    ...
    break;
    ...
    default:
    ...
    }

    Leap Instructions
    for

    for(initialization; logical-expression; step-iteration) {
    //The body of the loop
    }

    for(int i=0, j=100 ; i < 100 && j > 0; i++, j--) {
    ...
    }


    In both initialization and iteration, there may be several instructions separated by commas.
     
    while

    while (logical-expresion) {
    ...
    }


    do-while

    do {
    ...
    }
    while(logical-expresion);


    Instructions for handling exceptions
     
    The exception handling instructions are try-catch-finally, respectively throw and will be treated in the “Exceptions” chapter.

    Other instructions

  • break: leaves the body of a repetitive structure
  • continue: terminate the current iteration of a cycle and proceed to the next iteration
  • return [value]: finishes a method and eventually returns a value
  • Labelname: defines a label
  •  
    Although there is no goto in Java, labels used in phrases such as: break Labelname or continue Labelname, useful to control the exit point of a repetitive structure, as in the example below:

    i=0;
    label:
    while (i < 10) {
      System.out.println("i="+i);
      j=0;
      while (j < 10) {
        j++;
        if (j==5) continue label;
        if (j==7) break label;
        System.out.println("j="+j);
      }
      i++;
    }

    What is Java

    Java is an innovative technology launched by Sun Microsystems in
    1995, which had a remarkable impact on the entire community
    software developers, imposing themselves on special qualities such as
    simplicity, robustness and last but not least portability.

    Main features:

      Simplicity – eliminates overloading operators, multiple inheritance and all the facilities that can cause a confusing code.
      Easily – create complex applications using scheduling in network, threads, graphical interface, databases, etc.
      Robust – eliminates frequent sources of errors that occur in programming by giving up pointers, automatically managing memory and eliminating memory loss through a collection procedure for objects that are no longer referenced, garbage collector.
      Complete object-oriented – completely eliminates the procedural programming style.
      Security – is a very secure programming language, providing
      strict program security mechanisms implemented by dynamic code verification to detect dangerous sequences, imposing strict rules for running remote processes.
      Architectural Neutrality – The behavior of a Java application does not depends on the physical architecture of the running machine .
      Portable – Java is a language independent of the platform thing, the same application running without any change without the need recompiling it on different operating system such as Windows, Linux, Mac OS, Solaris, etc.
      It is compiled and interpreted – this being the effective solution for getting portability.
      Performance – although slower than the programming languages which generates executable native for a particular work platform, compiler Java provides high performance byte code, so slower operating speed will not be an impediment to development of any complex applications, including 3D graphics, animation, etc.

    Java Work Platform

    The Java programming language has been used to develop technologies dedicated to solving problems in the most diverse fields. These technologies have been grouped into so-called work platforms, which are sets of libraries written in Java, as well as various utility programs, used for developing applications or components for a particular one categories of users.

      J2SE (Standard Edition)
      It is the standard work platform that provides support for creating independent apps and applets.
      J2ME (Micro Edition)
      Using Java, programming of mobile devices is extremely simple, the J2ME work platform provides support for writing programs dedicated to this purpose.
      J2EE (Enterprise Edition)
      This platform aa provides the application development API complex, composed of components that must run in heterogeneous systems, with information stored in distributed databases, etc.
      Here, too, we find the necessary support for creating applications and services Web based on components such as servlets, JSP pages, etc.

    Java: a compiled and interpreted language
    Depending on how the applications are executed, the programming languages are split into two categories:

      Interpreted: The instructions are read line by line of a program called interpreter and translated into machine instructions. The advantage this solution is the simplicity and the fact that the source is directly interpreted we get portability. The obvious disadvantage is speed to run low.
      Compiled: The program source code is converted by compiler into a code that can be executed directly by the processor, called machine code. The advantage is the extremely fast execution, the disadvantage being lack of portability, compiled code in a low-level format not can be run only on the work platform on which it was compiled.

    The Java language combines the above-mentioned solutions, Java programs being both interpreted and compiled. So we will have one compiler responsible for turning the program sources into the so-called code bytes, and an interpreter to execute that byte code.

    The byte code is different from the machine code. The machine code is represented a sequence of instructions specific to a particular processor and a certain work platforms represented in binary format so that they can be executed without requiring any processing.
    Byte codes are instruction sets that resemble written code in assembly language and are generated by the compiler independent of the work environment. While the machine code is executed directly by the processor and can only be used on the platform on which it was created, the byte code is interpreted by the Java environment and therefore can be run on any platform on which is installed the Java executable environment.
    Through the Java Virtual Machine (JVM) we will understand the execution environment of Java applications. Because an octe code can be executed on a some computer, it needs to be installed a virtual Java machine.

    First program

    Creating any Java application involves performing the following steps:

      Writing source code


    class FirstApp {

      public static void main( String args[]) {

        System.out.println("Hello world!");
      }
    }

    All Java applications contain a primary class in which they must find the main method.

    Saving source files
    It will be made in files that have the java extension, no other extension is accepted. It is recommended that the file containing the source code of the primary class have the same name as the class, although this does not it’s obligatory.

    Compiling the application
    For compilation we will use the javac compiler from the J2SDK distribution.

    javac FirstApp.java

    If the compilation succeeded, the FirstApp.class file will be generated.

    Running the application
    It’s done with the java interpreter as follows:

    java FirstApp

    Running an application that does not use the graphical interface will be done in a system window.

    Keywords

    Words reserved in Java can not be used as class names, interfaces, variables, or methods.
    true, false, null are not keywords.

    Keywords are:

    abstract, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, extends, final, finally, float, for, goto, if, implements, import, instanceof, integer, interface, long, native, new, package, private, protected, public, return, short, static, strictpf, super, switch, sinchronized, this, throw, throws, transient, try, void, volatile, while

    Comments

    There are three kinds of comments in Java:

      Comments on multiple lines, closed between /* and */
      Comments on several lines that keep the documentation closed between /** and */.
      Comments on a single line, which begin with //

    Operators

      assigning: +
      mathematical operators: +, -, *, /, %, ++, —

    There are operators for auto increment and auto decrement: x++, ++x, n–, –n

      logical operators: &&(and), ||(or), !(not)
      relational operators: <, <=, >, <=, ==, !=
      operators on bits: &(and), |(or), ^ (xor), ~ (not)
      translational operators: <<, >>, >>>
      the if-else operator: expression-logic? val-true: val-false
      operator, (comma): used for evaluation sequencing of operations: int x=0, y=1, z=2;
      operator +: for string concatenation:

    String s1="John";
    String s2="apples";
    int x=10;
    System.out.println(s1 + " has " + x + " " + s2);

      Conversion operators (cast):

      int a = (int)’a’;
      char c = (char)96;
      int i = 200;
      long l = (long)i; //widening conversion
      long l2 = (long)200;
      int i2 = (int)l2; //narrowing conversion