Índice
- Disciplinas Atuais
- Disciplinas Antigas
Por João Araujo (adaptado do curso de Oscar Farias).
Cada SO necessita que o programa seja recompilado
Exceção (parcial): os tipos de dados primitivos. Estes tipos são padronizados para todas as plataformas. São eles:
Tipo | Tamanho | Faixa |
---|---|---|
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 point | 10e38 |
double | 64-bit floating point | 10e308 |
char | 16-bit Unicode | |
boolean | false true |
<note warning>Java não tem tipos unsigned!</note>
São usados para representar os tipos de dados primitivos.
Iniciando com:
// 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
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 }
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 }
/** * 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
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
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’;
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
Do menor para maior, funciona:
int i = 5; double d2 = i;
double d3 = 3.14; int i = (int) d3;
float x = 0.0;//Não funciona float x = 0.0f;// Funciona double d = 5; float f = 3; float x = f + (float) d;
if (boolean expression) { //... qualquer número de comandos } else { //... qualquer número de comandos }
while (boolean expression) { //... qualquer número de comandos } do { //... qualquer número de comandos } while (boolean expression);
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 (expr) { case cexpr1: // comandos JAVA break; case cexpr2: // comandos JAVA break; ... case cexprn: // comandos JAVA break; default: // mais comandos JAVA }
int numbers[]; //para arrays de inteiros String myStrings []; // para arrays de objetos do tipo string String[] myStrings; //forma alternativa
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.
myStrings[0] = “My first String”; myStrings[1] = “My second String”; numbers[0] = 20;
Int q = numbers.length; // q = 5
int k[][] = new int[5][4]; k[1][3] = 100; //atribui valor a um dos elementos do array
Outra forma de se criar um array:
int z[][]; int outerSize = 5; int innerSize = 4; z = new int[outerSize][innerSize];
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]); }
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]; */ } }
try { double x; x = Double.parseDouble(str); System.out.println( "The number is " + x ); } catch ( NumberFormatException e ) { System.out.println( "Not a legal number." ); }
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 deste módulo