Expresiones y Tipos

Embed Size (px)

Citation preview

  • 8/3/2019 Expresiones y Tipos

    1/74

    Fundamentos de programacinFundamentos de programacin

    Una vista a los principios deprogramacin

    TopicosTopicos Panorama Proceso de desarrollo de un programa

    Palabras reservadas, tipos, salida

  • 8/3/2019 Expresiones y Tipos

    2/74

    RevistasRevistas

    ByteByte www.mkmwww.mkm--pi.compi.com

    PC ActualPC Actualhttp://www.pcactual.com/http://www.pcactual.com/

    PC Magazine www.pcmag.comPC Magazine www.pcmag.com

    Linux Magazine www.linuxLinux Magazine www.linux--mag.commag.com

    2 Fundamentos

    PCPC WorldWorldwww.pcworld.comwww.pcworld.com JavaJava ProProwww.javawww.java--pro.compro.com

  • 8/3/2019 Expresiones y Tipos

    3/74

    3 Fundamentos

  • 8/3/2019 Expresiones y Tipos

    4/74

    Reglas bsicasReglas bsicas

    Elementos del lenguajeElementos del lenguaje

  • 8/3/2019 Expresiones y Tipos

    5/74

    5 FundamentosEl lenguaje de programacin

    Java

    5

  • 8/3/2019 Expresiones y Tipos

    6/74

    Palabras Reservadas (Keywords)Palabras Reservadas (Keywords)

    6 Fundamentos

    true, false, null ?

    Palabras claves tienen significado

    especial y no pueden usarse como

    identificadores de variables ni

    clases ni mtodos

  • 8/3/2019 Expresiones y Tipos

    7/74

    Como trabaja JavaComo trabaja Java

    7 Fundamentos

  • 8/3/2019 Expresiones y Tipos

    8/74

    Qu hars con JavaQu hars con Java

    8 Fundamentos

    Esto no es un tutorial esEsto no es un tutorial esEsto no es un tutorial esEsto no es un tutorial es

    solo una ilustracinsolo una ilustracinsolo una ilustracinsolo una ilustracin

  • 8/3/2019 Expresiones y Tipos

    9/74

    Anatoma de una clase en JavaAnatoma de una clase en Java

    9 FundamentosEl lenguaje de programacin

    Java

    9

  • 8/3/2019 Expresiones y Tipos

    10/74

    Anatoma de una clase en JavaAnatoma de una clase en Java

    /*

    * File: HelloWorld.java

    * Author: Java Java Java

    * Description: Prints Hello World greeting.

    */

    public class HelloWorld extends Object // Class header

    { // Start class body

    private String greeting = "Hello World!";

    Comments

    10 Fundamentos

    { // Start method bodySystem.out.println(greeting); // Output statement

    } // greet() // End method body

    public static void main(String args[]) // Method header

    {

    HelloWorld helloworld; // declare

    helloworld = new HelloWorld(); // create

    helloworld.greet(); // Method call

    } // main()

    } // HelloWorld class // End class body

  • 8/3/2019 Expresiones y Tipos

    11/74

    CommentsComments

    comment: A note written in source code by thecomment: A note written in source code by theprogrammer to describe or clarify the code.programmer to describe or clarify the code.

    Comments are not executed when your program runs.

    Syntax:Syntax:

    11 Fundamentos

    or,or,/*/* comment text; may span multiple linescomment text; may span multiple lines */*/

    Examples:Examples:// This is a one-line comment.

    /* This is a very long

    multi-line comment. */

  • 8/3/2019 Expresiones y Tipos

    12/74

    Using commentsUsing comments

    Where to place comments:Where to place comments:

    at the top of each file (a "comment header")

    at the start of every method (seen later) to explain complex pieces of code

    12 Fundamentos

    Comments are useful for:Comments are useful for:

    Understanding larger, more complex programs.

    Multiple programmers working together, who mustunderstand each other's code.

  • 8/3/2019 Expresiones y Tipos

    13/74

    Using commentsUsing comments

    /* This first comment begins and ends on the same line.

    */

    /* A second comment starts on this line ...and goes on ...

    and this is the last line of the second comment.

    */

    *

    13 Fundamentos

    /* This is NOT a fourth comment. It is justpart of the third comment.

    And this is the last line of the third comment.

    */

    */ This is an error because it is an unmatched end

    marker.

  • 8/3/2019 Expresiones y Tipos

    14/74

    El punto de partida: mainEl punto de partida: main

    14 Fundamentos

  • 8/3/2019 Expresiones y Tipos

    15/74

    Que puedo poner dentro del

    main

    Que puedo poner dentro del

    main Dentro del mtodo main como cualquier otro mtodoDentro del mtodo main como cualquier otro mtodopueden agregarsepueden agregarse Declaraciones

    Asignaciones

    Condiciones

    Re eticiones o ciclos

    15 Fundamentos

    Selecciones

    Rompimientos

    Invocaciones a otros metodos

    Retornos

    Etc

  • 8/3/2019 Expresiones y Tipos

    16/74

    Salida mediante printlnSalida mediante println

    Cualquier tipo primitivo oCualquier tipo primitivo o StringString

    Pueden lograrse resultados semejantes al usarPueden lograrse resultados semejantes al usar printprint

    Se usan caracteres de escape para caracteres noSe usan caracteres de escape para caracteres noimprimibles o ambiguosimprimibles o ambiguos

    16 Fundamentos

    Ya estamos usando paquetes, objeto, mtodos,Ya estamos usando paquetes, objeto, mtodos,parmetrosparmetros

  • 8/3/2019 Expresiones y Tipos

    17/74

    System.out.printlnSystem.out.println

    A statement that prints a line of output on theA statement that prints a line of output on theconsole.console.

    pronounced "print-linn" sometimes called a "println statement" for short

    17 Fundamentos

    Two ways to useTwo ways to use System.out.printlnSystem.out.println ::

    System.out.println("text");

    Prints the given message as output.

    System.out.println();

    Prints a blank line of output.

  • 8/3/2019 Expresiones y Tipos

    18/74

    Names and identifiersNames and identifiers

    You must give your program a name.You must give your program a name.public class SerHumano {

    Naming convention: capitalize each word (e.g.MyClassName)

    Your program's file must match exactly (SerHumano.java)

    "

    18 Fundamentos

    -sensitive")

    identifieridentifier: A name given to an item in your program.: A name given to an item in your program. must start with a letter or_ or $

    subsequent characters can be any of those or a number

    legal: _myName TheCure ANSWER_IS_42 $bling$

    illegal: me+u 49ers side-swipe Ph.D's

  • 8/3/2019 Expresiones y Tipos

    19/74

    SyntaxSyntax

    syntax: The set of legal structures and commandssyntax: The set of legal structures and commandsthat can be used in a particular language.that can be used in a particular language. Every basic Java statement ends with a semicolon ;

    The contents of a class or method occur between { and }

    19 Fundamentos

    structure of a program that causes the compiler tostructure of a program that causes the compiler tofail.fail. Missing semicolon Too many or too few { } braces

    Illegal identifier for class name

    Class and file names do not match

    ...

  • 8/3/2019 Expresiones y Tipos

    20/74

    Syntax error exampleSyntax error example11 public class Hello {public class Hello {

    22 ppooooblic static void main(String[] args) {blic static void main(String[] args) {

    33 System.System.owtowt.println("Hello, world!")_.println("Hello, world!")_

    44 }}

    55 }}

    Compiler output:Compiler output:

    20 Fundamentos

    ..

    pooblic static void main(String[] args) {pooblic static void main(String[] args) {^Hello.java:Hello.java:33: ';' expected: ';' expected}}^2 errors2 errors

    The compiler shows the line number where it found theerror.

    The error messages can be tough to understand!

  • 8/3/2019 Expresiones y Tipos

    21/74

    StringsStrings

    string: A sequence of characters to be printed.string: A sequence of characters to be printed. Starts and ends with a " quote " character.

    The quotes do not appear in the output. Examples:

    "hello"

    21 Fundamentos

    "This is a string. It's very long!"

    Restrictions:Restrictions: May not span multiple lines.

    "This is nota legal String."

    May not contain a " character.

    "This is not a "legal" String either."

  • 8/3/2019 Expresiones y Tipos

    22/74

    Escape sequencesEscape sequences

    escape sequence: A special sequence of charactersescape sequence: A special sequence of charactersused to represent certain special characters in a string.used to represent certain special characters in a string.

    \t tab character\n new line character

    \" quotation mark character

    Otros Caracteres de

    Escape

    \b \r \

    \007 \u0007

    22 Fundamentos

    Example:System.out.println("\\hello\nhow\tare \"you\"?\\\\");

    Output:\hellohow are "you"?\\

  • 8/3/2019 Expresiones y Tipos

    23/74

    QuestionsQuestions

    What is the output of the followingWhat is the output of the followingprintlnprintlnstatements?statements?

    System.out.println("\ta\tb\tc");

    System.out.println("\\\\");

    System.out.println("'");

    23 Fundamentos

    ys em.ou .pr n n ;

    System.out.println("C:\nin\the downward spiral");

    Write aWrite aprintlnprintln statement to produce this output:statement to produce this output:

    / \ // \\ /// \\\

  • 8/3/2019 Expresiones y Tipos

    24/74

    AnswersAnswers

    Output of eachOutput of eachprintlnprintln statement:statement:

    a b c

    \\'

    """

    C:

    24 Fundamentos

    in he downward spiral

    printlnprintln statement to produce the line of output:statement to produce the line of output:

    System.out.println("/ \\ // \\\\ /// \\\\\\");

  • 8/3/2019 Expresiones y Tipos

    25/74

    QuestionsQuestions

    WhatWhatprintlnprintln statements will generate this output?statements will generate this output?

    This program prints a

    quote from the Gettysburg Address.

    "Four score and seven years ago,our 'fore fathers' brought forth on

    "

    25 Fundamentos

    .

    WhatWhatprintlnprintln statements will generate this output?statements will generate this output?

    A "quoted" String is'much' better if you learn

    the rules of "escape sequences."

    Also, "" represents an empty String.Don't forget: use \" instead of " !'' is not the same as "

  • 8/3/2019 Expresiones y Tipos

    26/74

    AnswersAnswersprintlnprintln statements to generate the output:statements to generate the output:

    System.out.println("This program prints a");System.out.println("quote from the GettysburgAddress.");System.out.println();System.out.println("\"Four score and seven yearsago,");

    System.out.println("our 'fore fathers' brought forthon");

    " ""

    26 Fundamentos

    . . .

    printlnprintln statements to generate the output:statements to generate the output:

    System.out.println("A \"quoted\" String is");System.out.println("'much' better if you learn");

    System.out.println("the rules of \"escape sequences.\"");System.out.println();System.out.println("Also, \"\" represents an emptyString.");

    System.out.println("Don't forget: use \\\" instead of \"!");

    System.out.println("'' is not the same as \"");

  • 8/3/2019 Expresiones y Tipos

    27/74

    27 FundamentosEl lenguaje de programacinJava

    27

  • 8/3/2019 Expresiones y Tipos

    28/74

    28 Fundamentos

  • 8/3/2019 Expresiones y Tipos

    29/74

    Reglas para identificadoresReglas para identificadores

    Nombran variables, funciones, clases y objetosNombran variables, funciones, clases y objetos

    Comienza con una letra, un subrayado (_) o unComienza con una letra, un subrayado (_) o unsmbolo de dlar ($). Los siguientes caracteressmbolo de dlar ($). Los siguientes caracterespueden ser letras o dgitos.pueden ser letras o dgitos.

    29 Fundamentos

    Se distinguen las maysculas de las minsculasSe distinguen las maysculas de las minsculas No hay una longitud mxima establecida para elNo hay una longitud mxima establecida para el

    identificador.identificador.

  • 8/3/2019 Expresiones y Tipos

    30/74

    Data typesData typestype: A category or set of data values.type: A category or set of data values.

    Constrains the operations that can be performed on data

    Many languages ask the programmer to specify types

    Examples: integer, real number, string

    30 Fundamentos

    Internally, computers store everything as 1s and 0sInternally, computers store everything as 1s and 0s104 01101000

    "hi" 01101000110101

  • 8/3/2019 Expresiones y Tipos

    31/74

    VariablesVariables

    Sirven para referirse tanto a objetos como a tiposSirven para referirse tanto a objetos como a tiposprimitivos.primitivos.

    Tienen que declararse antes de usarse:Tienen que declararse antes de usarse:tipotipo identificadoridentificador;;

    intint osicionosicion

    31 Fundamentos

    SeSe puedepuede inicializarinicializar mediantemediante unauna asignacinasignacin::tipotipo identificadoridentificador == valorvalor;;

    intintposicionposicion == 00;;

    DefinicinDefinicin dede constantesconstantes::

    staticstatic finalfinal floatfloat PIPI == 33..1415914159ff;;

    L i bl ti tiL i bl ti ti

  • 8/3/2019 Expresiones y Tipos

    32/74

    Las variables tienen un tipo y

    nombre

    Las variables tienen un tipo y

    nombre

    El compilador se

    quejara, en general

    32 Fundamentos

    cuando exista

    incompatibilidad de

    tipos

  • 8/3/2019 Expresiones y Tipos

    33/74

    Tipos de datos primitivosTipos de datos primitivos

    Java maneja 8 tipos primitivos:Java maneja 8 tipos primitivos:byte (entero de 8 bits)

    short (entero de 16 bits) int (entero de 32 bits)

    lon entero de 64 bits

    33 Fundamentos

    float (decimal de 32 bits)

    double (decimal de 64 bits)

    char (Unicode de 16 bits)

    boolean (true, false)

    Versiones no primitivas

    Byte Short

    Integer Long

    Float Double

    Character

    Boolean

    Boxing y Unboxing

  • 8/3/2019 Expresiones y Tipos

    34/74

    Tipos de datos primitivosTipos de datos primitivos

    34 Fundamentos

    Versiones no primitivasByte Short

    Integer Long

    Float Double

    Character

    Boolean

    Boxing y Unboxing

    Tipos primiti os EnterosTipos primiti os Enteros

  • 8/3/2019 Expresiones y Tipos

    35/74

    Tipos primitivos Enteros y

    Flotantes

    Tipos primitivos Enteros y

    Flotantes

    Difieren al entero en

    35 Fundamentos

    almacenamiento

  • 8/3/2019 Expresiones y Tipos

    36/74

    Tipos primitivosTipos primitivos

    36 Fundamentos36

  • 8/3/2019 Expresiones y Tipos

    37/74

    Evite derramamientosEvite derramamientos

    int x=24;

    byte b= x;

    El vaso chico no

    tiene suficiente

    capacidad

    37 Fundamentos37

  • 8/3/2019 Expresiones y Tipos

    38/74

    OperadoresOperadores

    Operadores Asociatividad Tipo

    () izquierda a derecha parntesis

    ++ -- + - ! derecha a izquierda unarios

    * / % izquierda a derecha multiplicativos

    En orden de precedencia:

    38 Fundamentos

    -

    < >= izquierda a derecha relacionales== != izquierda a derecha de igualdad

    & izquierda a derecha AND lgico booleano

    ^ izquierda a derecha OR exclusivo lgico booleano

    | izquierda a derecha OR inclusivo lgico booleano

    && izquierda a derecha AND lgico

    | | izquierda a derecha OR lgico

    ?: derecha a izquierda condicional

    expresion ? sentencia1 : sentencia2

    = += -= *= /= %= derecha a izquierda asignacin ej. x += y x = x + y;

  • 8/3/2019 Expresiones y Tipos

    39/74

    Precedencia de OperadoresPrecedencia de Operadores

    39 Fundamentos

    Precedencia de OperadoresPrecedencia de Operadores

  • 8/3/2019 Expresiones y Tipos

    40/74

    Precedencia de Operadores

    (Cont)

    Precedencia de Operadores

    (Cont)

    40 Fundamentos

    Precedencia de OperadoresPrecedencia de Operadores

  • 8/3/2019 Expresiones y Tipos

    41/74

    Precedencia de Operadores

    (Cont)

    Precedencia de Operadores

    (Cont)

    41 Fundamentos

    NOTA:

    Precedencias de mayor a menor

    LR significa asociatividad de izquierda a derecha

    RL de derecha a izquierda

  • 8/3/2019 Expresiones y Tipos

    42/74

    42 Fundamentos

    EXPRESIONESEXPRESIONESOperaciones y precedencia de operadoresOperaciones y precedencia de operadores

  • 8/3/2019 Expresiones y Tipos

    43/74

    ExpressionsExpressionsexpression: A value or operation that computes aexpression: A value or operation that computes a

    value.value.

    Examples: 1 + 4 * 5(7 + 2) * 6 / 3

    42

    43 Fundamentos

    The simplest expression is a literal value. A complex expression can use operators and parentheses.

  • 8/3/2019 Expresiones y Tipos

    44/74

    Arithmetic operatorsArithmetic operatorsoperator: Combines multiple values or expressions.operator: Combines multiple values or expressions.

    + addition

    - subtraction (or negation) * multiplication / division

    44 Fundamentos

    . . .

    As a program runs, its expressions areAs a program runs, its expressions are evaluatedevaluated..

    1 + 1 evaluates to 2 System.out.println(3 * 4); prints 12

    How would we print the text 3 * 4 ?

  • 8/3/2019 Expresiones y Tipos

    45/74

    Integer division with /Integer division with /When we divide integers, the quotient is also anWhen we divide integers, the quotient is also an

    integer.integer. 14 / 4 is 3, not 3.5

    45 /10 is 4

    52/14 is 4

    135 / 27 is 5

    45 Fundamentos

    MoreMore examples:examples: 32 / 5 is 6

    84 / 10 is 8 156 / 100 is 1

    Dividing by 0 causes an error when your program runs.

  • 8/3/2019 Expresiones y Tipos

    46/74

    Integer remainder with %Integer remainder with %TheThe %% operator computes the remainder from integeroperator computes the remainder from integer

    division.division. 14 % 4 is 2

    218 % 5 is 3

    3 43

    4 ) 14 5 ) 218

    12 20

    2 18

    15

    3

    46 Fundamentos

    ApplicationsApplications ofof %% operator:operator:

    Obtain last digit of a number: 230857 % 10 is 7 Obtain last 4 digits: 658236489 % 10000 is6489

    See whether a number is odd: 7 % 2 is 1, 42 % 2 is 0

    a s e resu

    45 % 6 = ___ 2 % 2=___ 8 % 20=___ 11 % 0=____

  • 8/3/2019 Expresiones y Tipos

    47/74

    PrecedencePrecedenceprecedence: Order in which operators are evaluated.precedence: Order in which operators are evaluated.

    Generally operators evaluate left-to-right.1 - 2 - 3 is (1 - 2) - 3 which is -4

    But * / % have a higher level of precedence than + -

    1 + 3 * 4 is 13

    47 Fundamentos

    6 + 8 / 2 * 36 + 4 * 3

    6 + 12 is 18

    Parentheses can force a certain order of evaluation:(1 + 3) * 4 is 16

    Spacing does not affect order of evaluation1+3 * 4-2 is 11

  • 8/3/2019 Expresiones y Tipos

    48/74

    Precedence examplesPrecedence examples

    1 * 2 + 3 * 5 % 41 * 2 + 3 * 5 % 4

    \\_/_/||22 + 3 * 5 % 4+ 3 * 5 % 4

    1 + 8 % 3 * 2 - 9

    \_/|

    1 + 2 * 2 - 9

    \___/

    48 Fundamentos

    __

    ||2 +2 + 1515 % 4% 4

    \\___/___/||

    2 +2 + 33

    \\________/________/||

    55

    |

    1 + 4 - 9 \______/

    |5 - 9

    \_________/|-4

  • 8/3/2019 Expresiones y Tipos

    49/74

    Precedence questionsPrecedence questionsWhat values result from the following expressions?What values result from the following expressions?

    9 / 5

    695 % 20 7 + 6 * 5

    7 * 6 + 5

    49 Fundamentos

    248 % 100 / 5 6 * 3 - 9 / 4

    (5 - 7) * 4

    6 + (18 % (17 - 12))

  • 8/3/2019 Expresiones y Tipos

    50/74

    Real numbers (type double)Real numbers (type double)Examples:Examples: 6.0226.022 ,, --42.042.0 ,, 2.143e172.143e17

    Placing .0 or . after an integer makes it a double.

    The operatorsThe operators ++ -- ** // %% ()() all still work withall still work with doubledouble..

    50 Fundamentos

    : . . .

    Precedence is the same: () before * / % before + -

  • 8/3/2019 Expresiones y Tipos

    51/74

    Real number exampleReal number example2.0 * 2.4 + 2.25 * 4.0 / 2.02.0 * 2.4 + 2.25 * 4.0 / 2.0

    \\___/___/||4.84.8 + 2.25 * 4.0 / 2.0+ 2.25 * 4.0 / 2.0

    \\___/___/

    51 Fundamentos

    4.8 +4.8 + 9.09.0 / 2.0/ 2.0

    \\_____/_____/||

    4.8 +4.8 + 4.54.5 \\____________/____________/

    ||

    9.39.3

    Mixing typesMixing types

  • 8/3/2019 Expresiones y Tipos

    52/74

    Mixing typesMixing types

    WhenWhen intint andand doubledouble are mixed, the result is aare mixed, the result is adoubledouble.. 4.2 * 3 is 12.6

    The conversion is perThe conversion is per--operator, affecting only itsoperator, affecting only itsoperands.operands. 2.0 + 10 / 3 * 2.5 - 6 / 4

    52 Fundamentos

    7 / 3 * 1.2 + 3 / 2 \_/

    |2 * 1.2 + 3 / 2

    \___/|2.4 + 3 / 2

    \_/|

    2.4 + 1

    \________/|3.4

    ___|

    2.0 + 3 * 2.5 - 6 / 4 \_____/

    |2.0 + 7.5 - 6 / 4

    \_/|

    2.0 + 7.5 - 1 \_________/

    |9.5 - 1

    \______________/|8.5

    S i iS i i

  • 8/3/2019 Expresiones y Tipos

    53/74

    String concatenationString concatenation string concatenation: Usingstring concatenation: Using ++ between a string andbetween a string and

    another value to make a longer string.another value to make a longer string.

    "hello" + 42 is "hello42"1 + "abc" + 2 is "1abc2""abc" + 1 + 2 is "abc12"1 + 2 + "abc" is "3abc"

    53 Fundamentos

    "abc" + 9 * 3 is "abc27""1" + 1 is "11"4 - 1 + "abc" is "3abc"

    UseUse ++ to print a string and an expression's valueto print a string and an expression's value

    together.together. System.out.println("Grade: " + (95.1 + 71.9) / 2);

    Output: Grade: 83.5

  • 8/3/2019 Expresiones y Tipos

    54/74

    VariablesVariables

    54 Fundamentos

    Receipt exampleReceipt example

  • 8/3/2019 Expresiones y Tipos

    55/74

    Receipt exampleReceipt example

    What's bad about the following code?What's bad about the following code?public class Receipt {

    public static void main(String[] args) {

    // Calculate total owed, assuming 8% tax / 15%tipSystem.out.println("Subtotal:");System.out.println(38 + 40 + 30);

    " "

    55 Fundamentos

    . .System.out.println((38 + 40 + 30) * .08);System.out.println("Tip:");System.out.println((38 + 40 + 30) * .15);System.out.println("Total:");System.out.println(38 + 40 + 30 +

    (38 + 40 + 30) * .08 +

    (38 + 40 + 30) * .15);}

    }

    The subtotal expression (38 + 40 + 30) is repeated

    So manyprintln statements

    V i blV i bl

  • 8/3/2019 Expresiones y Tipos

    56/74

    VariablesVariablesvariable: A piece of the computer's memory that isvariable: A piece of the computer's memory that is

    given a name and type, and can store a value.given a name and type, and can store a value. Like preset stations on a car stereo, or cell phone speed dial:

    56 Fundamentos

    Steps for using a variable:

    Declareit - state its name and type

    Initializeit - store a value into itUseit - print it or use it as part of an

    expression

    DeclarationDeclaration

  • 8/3/2019 Expresiones y Tipos

    57/74

    DeclarationDeclarationvariable declaration:variable declaration: Sets aside memory for storing aSets aside memory for storing a

    value.value. Variables must be declared before they can be used.

    Syntax:Syntax:

    57 Fundamentos

    type name;

    The name is an identifier.

    int x;

    double myGPA;

    x

    myGPA

    AssignmentAssignment

  • 8/3/2019 Expresiones y Tipos

    58/74

    AssignmentAssignmentassignment: Stores a value into a variable.assignment: Stores a value into a variable.

    The value can be an expression; the variable stores its result.

    Syntax:Syntax:

    name = expression;

    58 Fundamentos

    int x;

    x = 3;

    double myGPA;myGPA = 1.0 + 2.25;

    x 3

    myGPA 3.25

    Using variablesUsing variables

  • 8/3/2019 Expresiones y Tipos

    59/74

    Using variablesUsing variablesOnce given a value, a variable can be used inOnce given a value, a variable can be used in

    expressions:expressions:

    int x;

    x = 3;

    System.out.println("x is " + x); // x is 3

    59 Fundamentos

    ys em.ou .pr n n x - ; -

    You can assign a value more than once:You can assign a value more than once:

    int x;

    x = 3;System.out.println(x + " here"); // 3 here

    x = 4 + 7;

    System.out.println("now x is " + x); // now x is 11

    x 3x 11

    Declaration/initializationDeclaration/initialization

  • 8/3/2019 Expresiones y Tipos

    60/74

    Declaration/initializationDeclaration/initializationA variable can be declared/initialized in oneA variable can be declared/initialized in one

    statement.statement.

    Syntax:Syntax:

    60 Fundamentos

    type name = value;

    double myGPA = 3.95;

    int x = (11 % 3) + 12;

    x 14

    myGPA 3.95

    Assignment and algebraAssignment and algebra

  • 8/3/2019 Expresiones y Tipos

    61/74

    Assignment and algebraAssignment and algebraAssignment usesAssignment uses == , but it is not an algebraic, but it is not an algebraic

    equation.equation.

    = means, "store the value at right in variable at left"

    The ri ht side ex ression is evaluated first

    61 Fundamentos

    and then its result is stored in the variable atleft.

    What happens here?What happens here?int x = 3;

    x = x + 2; // ???

    x 3x 5

    Assignment and typesAssignment and types

  • 8/3/2019 Expresiones y Tipos

    62/74

    Assignment and typesAssignment and types A variable can only store a value of its own type.A variable can only store a value of its own type.

    int x = 2.5; // ERROR: incompatible types

    AnAn intint value can be stored in avalue can be stored in a doubledouble variable.variable. The value is converted into the e uivalent real number.

    62 Fundamentos

    double myGPA = 4;

    double avg = 11 / 2;

    Why does avg store 5.0and not 5.5 ?

    myGPA 4.0

    avg 5.0

    Compiler errorsCompiler errors

  • 8/3/2019 Expresiones y Tipos

    63/74

    Compiler errorsCompiler errorsA variable can't be used until it is assigned a value.A variable can't be used until it is assigned a value.

    int x;

    System.out.println(x); // ERROR: x has no value

    YouYou may not declare the same variable twice.may not declare the same variable twice.

    63 Fundamentos

    int x;int x; // ERROR: x already exists

    int x = 3;

    int x = 5; // ERROR: x already exists

    How can this code be fixed?

    Printing a variable's valuePrinting a variable's value

  • 8/3/2019 Expresiones y Tipos

    64/74

    Printing a variable s valuePrinting a variable s valueUseUse ++ to print a string and a variable's value on oneto print a string and a variable's value on one

    line.line.

    double grade = (95.1 + 71.9 + 82.6) / 3.0;System.out.println("Your grade was " + grade);

    64 Fundamentos

    n s u en s = ;

    System.out.println("There are " + students +" students in the course.");

    Output:

    Your grade was 83.2

    There are 65 students in the course.

    Receipt questionReceipt question

  • 8/3/2019 Expresiones y Tipos

    65/74

    p qp q

    Improve the receipt program using variables.Improve the receipt program using variables.

    public class Receipt {public class Receipt {public static void main(String[] args) {public static void main(String[] args) {

    // Calculate total owed, assuming 8% tax / 15% tip// Calculate total owed, assuming 8% tax / 15% tipSystem.out.println("Subtotal:");System.out.println("Subtotal:");System.out.println(38 + 40 + 30);System.out.println(38 + 40 + 30);

    " "" "

    65 Fundamentos

    System.out.println((38 + 40 + 30) * .08);System.out.println((38 + 40 + 30) * .08);

    System.out.println("Tip:");System.out.println("Tip:");System.out.println((38 + 40 + 30) * .15);System.out.println((38 + 40 + 30) * .15);

    System.out.println("Total:");System.out.println("Total:");System.out.println(38 + 40 + 30 +System.out.println(38 + 40 + 30 +

    (38 + 40 + 30) * .15 +(38 + 40 + 30) * .15 +(38 + 40 + 30) * .08);(38 + 40 + 30) * .08);}}

    }}

    Receipt answerReceipt answer

  • 8/3/2019 Expresiones y Tipos

    66/74

    pppublic class Receipt {public class Receipt {

    public static void main(String[] args) {public static void main(String[] args) {// Calculate total owed, assuming 8% tax / 15% tip// Calculate total owed, assuming 8% tax / 15% tipint subtotal = 38 + 40 + 30;int subtotal = 38 + 40 + 30;double tax = subtotal * .08;double tax = subtotal * .08;double tip = subtotal * .15;double tip = subtotal * .15;double total = subtotal + tax + tip;double total = subtotal + tax + tip;

    S stem.out. rintln "Subtotal: " + subtotalS stem.out. rintln "Subtotal: " + subtotal

    66 Fundamentos

    System.out.println("Tax: " + tax);System.out.println("Tax: " + tax);

    System.out.println("Tip: " + tip);System.out.println("Tip: " + tip);System.out.println("Total: " + total);System.out.println("Total: " + total);

    }}}}

    Conversiones implcitas yexplcitasConversiones implcitas yexplcitas

  • 8/3/2019 Expresiones y Tipos

    67/74

    explcitasexplcitas Conversin ImplcitaConversin Implcita

    El compilador realiza una conversin automtica al operando de

    mayor precisin

    67 Fundamentos

    Conversin ExplcitaConversin Explcita Es necesario agregar el cdigo que permita la conversin

    Ej. byte b= (byte) variableLong;

    fDato= (float)dDato;

    Variables referenciaVariables referencia

  • 8/3/2019 Expresiones y Tipos

    68/74

    Podemos pensar en unavariable de referencia a

    un objeto, como uncontrol remoto a eseobjeto, usado para

    68 Fundamentos

    Creacin de ObjetosCreacin de Objetos

  • 8/3/2019 Expresiones y Tipos

    69/74

    69 FundamentosEl lenguaje de programacinJava 69

  • 8/3/2019 Expresiones y Tipos

    70/74

    USO Y CREACIN DEOBJETOSUSO Y CREACIN DEOBJETOS

    70 Fundamentos

    Uso y creacin de ObjetosUso y creacin de Objetos

  • 8/3/2019 Expresiones y Tipos

    71/74

    ResumenResumen Se mostrar la forma en que los programas toman su

    entrada de datos

    Algunas entradas por Parmetros, Teclado y Archivos Utilizaremos la clase String, Scanner, InputStream

    representando al data source.

    71 Fundamentos

    Utilizaremos mtodos, repeticiones, clases, parmetros.

    ASCIIASCII

  • 8/3/2019 Expresiones y Tipos

    72/74

    72 Fundamentos

    Cdigo ASCIICdigo ASCII

  • 8/3/2019 Expresiones y Tipos

    73/74

    73 Fundamentos

    Caracteres no imprimiblesCaracteres no imprimibles

  • 8/3/2019 Expresiones y Tipos

    74/74

    74 Fundamentos