View page as slide show

A Linguagem Java

Java sem classe

Por João Araujo (adaptado do curso de Oscar Farias).

Características de Java

  1. Linguagem totalmente Orientada a Objetos
  2. Portabilidade
  3. Alta Performance
  4. Facilidades para Processamento Distribuído
  5. Ambiente Seguro

Linguagens Compiladas

Cada SO necessita que o programa seja recompilado

Java Virtual Machine

JVM e Portabilidade

Plataforma Java

Arquitetura

Versões Java

    • Java 1.0 e 1.1 são as versões muito antigas de Java.
    • Com o Java 1.2 virou Java2, incorporando o 2 ao nome
      • Não existe Java 2.0, mas Java2 1.2.
    • Depois vieram o Java2 1.3 e 1.4
    • Até a versão 1.4, existia a terceira numeração (1.3.1, 1.4.1, 1.4.2, etc)
    • A partir do Java 5 existem apenas updates: Java 5 update 7, por exemplo.
  • Java 5 e 6

    • Java 1.5 passou a se chamar Java 5
      • O 2 desaparece do nome
    • Versão atual é Java 6, lançada em 2006.
  • Sopa de letras: JVM, JRE, JDK

    JAVA SE (Standard Edition)

    JAVA EE (Enterprise Edition)

    JAVA ME (Micro Edition)

    Produtividade

    Tudo em Java é objeto

    Exceção (parcial): os tipos de dados primitivos. Estes tipos são padronizados para todas as plataformas. São eles:

    TipoTamanhoFaixa
    byte 8-bit -128 a 127
    short 16-bit -32768 a 23767
    int 32-bit -2147483648 a 2147483647
    long 64-bit-9223372036854775808 to 9223372036854775807
    float 32-bit floating point10e38
    double 64-bit floating point10e308
    char 16-bit Unicode
    boolean false true

    E os unsigneds?

    <note warning>Java não tem tipos unsigned!</note>

    Literais (i)

    São usados para representar os tipos de dados primitivos.
    Iniciando com:

    Literais (ii)

    Literais (iii)

    Palavras-Chave

    Hello Java World

    // A program to display the message
    // "Hello World!" on standard output
    public class HelloWorld {
       public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) {
           1.5.0/docs/api/java/lang/System.html">System.out.println("Hello World!");
       }
    }    // end of class HelloWorld

    Forma Geral

    public class program-name   {
         optional-variable-declarations-and-subroutines
        public static void main(1.5.0/docs/api/java/lang/String.html">String[] args) {
            statements
        }
         optional-variable-declarations-and-subroutines
    }

    Executando um Programa em JAVA

    E os bytecodes?

    javap -c HelloWorld (i)

    Compiled from "HelloWorld.java"
    class HelloWorld extends java.lang.Object{
    HelloWorld();
      Code:
       0:	aload_0
       1:	invokespecial	#1; //Method java/lang/Object."<init>":()V
       4:	return
    
    public static void main(java.lang.String[]);
      Code:
       0:	getstatic	#2; //Field java/lang/System.out:Ljava/io/PrintStream;
       3:	ldc	#3; //String Hello World!
       5:	invokevirtual	#4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
       8:	return
    
    }
    

    Hello World

    Comentários

    /**
     * This class implements a simple program that
     * will compute the amount of interest that is
     * earned on $17,000 invested at an interest
     * rate of 0.07 for one year. The interest and
     * the value of the investment after one year are
     * printed to standard output.
     */
    // One line comment

    Outro programa

    public class Interest {
       public static void main(String[] args) {
     
    double principal; // The value of the investment.
    double rate;      // The annual interest rate.
    double interest;  // Interest earned in one year.
     
    principal = 17000;
    rate = 0.07;
    interest = principal * rate;   // Compute the interest.
    principal = principal + interest;
          // Compute value of investment after one year, with interest.
          // (Note: The new value replaces the old value of principal.)
    System.out.print("The interest earned is $");
    System.out.println(interest);
    System.out.print("The value of the investment after one year is $");
    System.out.println(principal);
       } // end of main()
    } // end of class Interest

    Variáveis

    Declarando e iniciando

    podemos também dar a carga inicial quando declaramos:

       int a = 20;
       double pi = 3.14;
       double x = 3 * 5;
       boolean verdade = true;
       char letra = ’a’;

    Coerção de tipos (i)

      double var_double = 3.1415;
      int var_int = var_double; // não compila
      int var_int1 = 3.14; // não compila
      double var_double1 = 5; // ok, o double pode conter um número inteiro
      int var_int2 = var_double1; // não compila

    Coerção de tipos (ii)

    Do menor para maior, funciona:

      int i = 5;
      double d2 = i;

    Coerção de tipos (ii)

      double d3 = 3.14;
      int i = (int) d3;

    Coerção de tipos (iii)

      float x = 0.0;//Não funciona
      float x = 0.0f;// Funciona
      double d = 5;
      float f = 3;
      float x = f + (float) d;

    Tabela de coerção

    Fluxo de Controle

    if

    	if  (boolean expression)  {
       		//... qualquer número de comandos
    	}
    	else  {
     		//... qualquer número de comandos
    	}

    while loop

    	while (boolean expression)  {
    		  //... qualquer número de comandos
    	}
     
    	do  {
    		  //... qualquer número de comandos 
    	}  while (boolean expression);

    for loop

    	for (expr1; expr2; expr3) {
    		//...qualquer número de comandos
    	}

    Equivalente a:

    	avalia expr1;  //inicialização do loop
    	while (expr2) {
    		//... Qualquer número de comandos
    	     avalia expr3 // expressão para controlar o loop
    	}
    

    switch statement

    	switch (expr)  {
    		case cexpr1:  
    			// comandos JAVA
    			break;
    		case cexpr2:  
    			// comandos JAVA
    			break;
    		... 
    		case cexprn:  
    			// comandos JAVA
    			break;
    		default:
    			// mais comandos JAVA
    	}

    Arrays (i)

    	int		numbers[];     //para arrays de inteiros
    	String	myStrings [];  // para arrays de objetos do tipo string	
    	String[]	myStrings;      //forma alternativa

    Arrays (ii)

        int numbers[] = new int[5];  //array de inteiros, de dimensão 5.
        String  myStrings[] = new Strings[20] ;  //array de Objetos String, de dimensão 20.

    Arrays (iii)

    	myStrings[0] = “My first String”;
    	myStrings[1] = “My second String”;
    	numbers[0] = 20;
    

    Arrays (iv)

    	Int	q = numbers.length;   // q = 5

    Arrays Multidimensionais (i)

    	int k[][] = new int[5][4];
    	k[1][3] = 100;	//atribui valor a um dos elementos do array

    Arrays Multidimensionais (ii)

    Outra forma de se criar um array:

    	int z[][];
    	int outerSize = 5;
    	int innerSize = 4;
    	z = new int[outerSize][innerSize];

    Exemplo

    class TestArray { 
    	public static void main (String args[]) {
     	int z[][];
    	int outerSize = 5;
    	int innerSize = 4;
        	z = new int[outerSize][innerSize];
    	int i, j , k;  // linha --> i;  coluna --> j
    	for (i = 0, k = 0; i < innerSize; i++)
    		for (j = 0; j < outerSize; j++) {
    			z[j][i] = k++;
    			System.out.println("i = " + i + " j = " + j + " " + z[j][i]);
    		}

    Exemplo (cont.)

       	int w[][] = new int[10][];
    	w[0] = new int[5];
    	w[3] = new int[3];
    	System.out.println (w.length + "  " + w[0].length + " "+ w[3].length);
    	w[10] = new int[3];	  // OutOfBoundException  
     
    	/* int y[][] = new int [10][];	   // missing array dimension  
    	y[0][] = new int [5];	   // missing array index 
    	y[][2] = new int [10]; */
    	}
    }

    Exceções (try...catch)

    try-catch

    Exemplo try-catch

    try {
       double x;
       x = Double.parseDouble(str);
       System.out.println( "The number is " + x );
    }
    catch ( NumberFormatException e ) {
       System.out.println( "Not a legal number." );
    }

    Outro Exemplo

    enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
    Day weekday; // User’s response as a value of type Day.
    while ( true ) {
       String response; // User’s response as a String.
       TextIO.put("Please enter a day of the week: ");
       response = TextIO.getln();
       response = response.toUpperCase();
       try {
          weekday = Day.valueOf(response);
          break;
       }
       catch ( IllegalArgumentException e ) {
          TextIO.putln( response + " is not the name of a day of the week." );
       }
    }

    Fim

    Fim deste módulo