Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

Convirtiendo Tipo Datos Primitivos A Integer (Java)


Ayúdanos a seguir creciendo


public class ConvirtiendoTipoDatosPrimitivosAWrapper {
    public static void main(String[] args) {
        // Crear instancia de objeto Integer
        Integer contador = new Integer(7801);
     
        // Convertir tipo Integer a tipo primitivo int usando el método intValue()
        int newCount = contador.intValue();
        System.out.println("int nuevoContador = " + newCount);
     
        //Usando método estático de la clase wrapper Integer
        //para convertir un tipo de dato String String a un tipo de dato
        //entero primitivo int
        String pennsylvania = "65000";
        int penn = Integer.parseInt(pennsylvania);
        System.out.println("int penn = " + penn);
     
        // Converyir tipo de dato entero primitivo int a tipo Integer
        Integer miInteger = new Integer(penn);
        System.out.println("Integer miInteger = " + miInteger);
    }
}

Variables Por Referencia (Java)


Ayúdanos a seguir creciendo


public class VariablesPorReferencia {
        public static void main(String[] args) {
        System.out.println("main: iniciar");
     
       
        int [] edades = {10, 11, 12};
     
        // Salida:
        // 10, 11, 12
        for (int i=0; i<edades.length; i++ ){
            System.out.println(edades[i]);
        }
     
        System.out.println("main: antes de llamar método procesar");
             
        procesar(edades);
     
        System.out.println("main: después de llamar método procesar");
     
        //debe imprimir nuevos valores
        for (int i=0; i<edades.length; i++ ){
            System.out.println(edades[i]);
        }
     
        System.out.println("main: iniciado");
       
    }
   
    public static void procesar(int[] arreglo){
     
        System.out.println("procesar: inicia");
             
        for (int i=0; i<arreglo.length; i++ ){
            arreglo[i] = i + 50;
        }
     
        System.out.println("procesar: final");
    }
}

Comparacion String (Java)

public class ComparacionString {
 
    public static void main(String[] args) {
   
     /**
      * Comparacion de expresiones usando String
      */
   
     String nombre = null;
     String apellido = null;
     String nombre1 = null;
   
     //Comparar usando el metodo equal
     if(nombre.equals("Richard")){
         //do something
     }
   
     //igual que usar el metodo equal pero no distingue entre minuscula y mayuscula
     if(nombre.equalsIgnoreCase("Richard")){
       
     }
   
     //Validar que la variable no tenga un valor asignado
     if(nombre.equals("")){
       
     }
     //Usar la expresion negacion
     if(!apellido.equals("Reinoso")){
       
     }
     //comparacion usando otra variable y la negacion del resultado de la comparacion
     if(!nombre.equalsIgnoreCase(nombre1)){
       
     }
     //comparacion con un valor null
     if(nombre == null){
       
     }
   
     //que la variable nombre sea diferente de null
     if(nombre != null){
       
     }
   
     //comparacion de dos variables
     if(nombre == nombre1){
       
     }
   
       
    }
 
}

Ayúdanos a seguir creciendo


Variables Por Valor (Java)


Ayúdanos a seguir creciendo


public class VariablesPorValor {
       public static void procesar(int j){
     
        System.out.println("iniciado procesar : j = " + j);  // 10
     
       
        j = 33;
     
        System.out.println("final de procesar : j = " + j);  // 33
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
       
         int i = 10;
     
       
        System.out.println("main : i = " + i);  //10
           
        procesar(i );
     
       
        System.out.println("final método main: i = " + i);  // 10
       
       
    }
}

Bigdecimal (Java)

import java.math.BigDecimal;

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

        /**
         * Por que usar BigDecimal (y no Double) para calculos aritmeticos financieros ?
         */

        double unCentavo = 0.01;
        double suma = unCentavo + unCentavo + unCentavo + unCentavo + unCentavo + unCentavo;
        System.out.println(suma); //Que se imprime? Si contestaste: 0.06, estas equivocado.

        /**
         * Ahora escribe:
         */

        BigDecimal unCentavo1 = new BigDecimal("0.01");
        BigDecimal suma1 = unCentavo1.add(unCentavo1).add(unCentavo1).add(unCentavo1).add(unCentavo1).add(unCentavo1);
        System.out.println(suma1); // Que imprime? 0.06

      }
}

Ayúdanos a seguir creciendo


Math (Java)

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

        /**
         * Ejemplo1: Metodo round
         * Redondear
         */
        long result = Math.round(1.667); //result = 2
        int result1 = Math.round(1.49F); //result1 = 1

        /**
         * Ejemplo2 : Metodo pow
         * Elevar a la n
         */

        double result2 = Math.pow(2, 2); //result2 = 4 (2*2)
        double result3 = Math.pow(2, 3); //result3 = 8 (2*2*2)
        double result4 = Math.pow(5, 2); //result4 = 25.0 (5^2)
        int result5 = (int)Math.pow(5, 2); //result5 = 25 (5^2)

        /**
         * Ejemplo 3: Metodo sqrt
         * Raiz cuadrada
         */

        double result6 = Math.sqrt(20.25); //result6 = 4.5

        /**
         * Ejemplo 4: Metodo max y metodo min
         * conseguir el valor maximo y minimo en cada caso
         */

        int x = 67;
        int y = 23;

        int max = Math.max(x, y); //max = 67
        int min = Math.max(x, y); //min = 23


        /**
         * Ejemplo 5: Metodo random
         * Generar valores aleatorio
         *
         */

        double x1 = Math.random() * 100; //Genera un valor entre 0.0 y 100.0
        long result7 = (long)x1; //convertir de double a long

    }
}

Ayúdanos a seguir creciendo


Operadores Lógicos (Java)

public class OperadoresLogicos {
    public static void main(String[] args) {
        /**
         * Uso de Operadores logicos
         */
       
        int subtotal  = 0;
        int timeInService = 0;
        boolean isValid = false;
        int counter = 0;
        int years = 0;
       
        //Evaluacion del operador && (AND)
        if(subtotal >= 250 && subtotal < 500){
           
        }
       
        //Evaluacion del operador || (OR)
        if(timeInService <=4 || timeInService >=12){
           
        }
       
        //Otra forma del operador  AND &
        if(isValid == true & counter++ < years){
           
        }
       
        //Otra forma del operador  OR |
        if(isValid == true | counter++ < years){
           
        }
       
        //combinando operador AND y OR
        if((subtotal >= 250 && subtotal < 500) || isValid ==true){
           
        }
       
        //negacion del resultado de la expresion
        if(!(counter++ >= years)){
           
        }

    }
}

Ayúdanos a seguir creciendo


Expresión While, Do While (Java)

public class ExpresionWhileDoWhile {
    public static void main(String[] args) {
        /**
        * Evaluacion de la expresion While y Do While
        */


        /**
         * While:
         * La sintaxis del bucle while
         * while (booleanExpression)
         * {
         * declaraciones
         * }
         */

        int i = 1;
        int months = 36;

        while (i < months) {
            //do something here
            i++;
        }

        /**
         * Do While
         * do{
         *  //declaraciones
         *  }while(booleanExpression)
         */


        do {
            //do something here
            i++;
        } while (i < months);
         
    }
}


Ayúdanos a seguir creciendo


Expresion Switch (Java)

public class ExpresionSwitch {
    public static void main(String[] args) {
        /**
         * Declaracion de la expresion switch
         * switch(integerExpresion){
         *  case label1:
         *   //do something
         *   break;
         *   case label2:
         *   //do something
         *   break;
         *   default: (optional)
         *    //do something
         *    break;
         * }
         */


        int productId =  0;
        String productDescription = "";

        switch (productId) {
        case 1:
            productDescription = "Hammer";
            break;
        case 2:
            productDescription = "Box of nails";
            break;
        default:
            productDescription = "Product not found";
            break;
        }
        }
       
       

Ayúdanos a seguir creciendo


Expresión If Else (Java)

public class ExpresionIfElse {

    public static void main(String[] args) {
       
      /**
      * if (booleanExpression) {statements}
      * [else if (booleanExpression) {statements}]
      * [else {statements}]
      */

        double discountPercent = 0.2;
        int subtotal = 0;
        String shippingMethod;
        String customerType = "";

        /**
      * Ejemplo I
      */
        if (subtotal >= 100 && subtotal < 200) {
            discountPercent = 0.1;
        } else if (subtotal >= 200 && subtotal < 300) {
            discountPercent = 0.2;
        } else if (subtotal >= 300) {
            discountPercent = 0.3;

        } else {
            discountPercent = 0.05;
        }

        /**
         * Ejemplo II
         */

        if (customerType.equals("R")) {
            discountPercent = 0.1;
            shippingMethod = "UPS";

        } else if (customerType.equals("C")) {
            discountPercent = 0.2;
            shippingMethod = "Bulk";

        } else {
            shippingMethod = "USPS";
        }

        /**
      * Ejemplo III
      */

        if (customerType.equals("C")) {

            if (subtotal >= 100) {
                discountPercent = 0.2;
            } else {
                discountPercent = 0.1;
            }
        } else {
                discountPercent = 0.4;
        }

    }
}

Ayúdanos a seguir creciendo


Expresión Boolean (Java)

public class ExpresionBoolean {
 
    public static void main(String[] args) {
       
        /**
         * Como usar expresiones del tipo boolean
         */
       
      double  discountPercent = 0.0;
     
      //Usando IF
      if(discountPercent == 2.3){
          //Realizar operaciones dentro del este segmento
      }
     
      //Operador ternario
      boolean estado =   (discountPercent == 2.3)? true : false;
     
       
      if(estado){  //usando una variable tipo boolean
        //Realizar operaciones dentro del este segmento
      }
     
      //Evaluando expresion negacion
      if(discountPercent !=0){
         
      }
     
      //Expresion  mayor que
      if(discountPercent > 0){
         
      }
     
     
      //Expresion menor que     
      if(discountPercent < 5){
         
      }
     
      //Mayor o igual
      if(discountPercent >= 5){
         
      }
     
      //menor o igual
      if(discountPercent <= 5){
         
      }
     
      //Negacion del valor boolean
      if(!estado){
         
      }
     
        //TODO: Hacer alguna operacion que permita evaluar alguno de los casos anteriores
       
     
    }

 
}

Ayúdanos a seguir creciendo


Estructura Control Switch (Java)

public class EstructuraControlSwitch {

    enum Marca {

        DELL, TOSHIBA, SAMSUNG;
    }

    public void ejecutar(Marca m) {   

        switch (m) {
            case DELL:
                System.out.println("Es dell");
                break;
            case TOSHIBA:
                System.out.println("Es Toshiba");
                break;
            default:
                System.out.println("Ninguna");
             
        }
    }
   
    public static void main(String[] args) {
        EstructuraControlSwitch esw = new EstructuraControlSwitch();
        esw.ejecutar(Marca.SAMSUNG);
         esw.ejecutar(Marca.TOSHIBA);
    }

}

Ayúdanos a seguir creciendo


Conversion Tipo Datos Primitivos (Java)

public class ConversionTipoDatosPrimitivos {
 
    public static void main(String[] args) {
        // Ejemplo conversión implícita 1
        int numInt = 10;
        double  numDouble = numInt;
        System.out.println("int " + numInt + " fue convertido de forma implícita a double " +                          numDouble);
     
        // Ejemplo conversión implícita  2
        int numInt1 = 1;
        int numInt2 = 2;
        double  numDouble2 = numInt1/numInt2;
        System.out.println("numInt1/numInt2 " + numInt1/numInt2 + " fue convertido de forma                      implícita a double " + numDouble2);
     
        // Ejemplo conversión explícita 1
        double  valDouble = 10.12;
        int valInt = Double.valueOf(valDouble).intValue();
     
             
        System.out.println("double " + valDouble + " fue convertido de forma explícita a  int " + valInt);
     
        // Ejemplo conversión explícita 2
        double x = 10.2;
        int y = 2;
        int resultado = (int)(x/y);
        System.out.println("x/y " + x/y + " fue convertido de forma explícita a int " + resultado);

    }
}

String (Java)

public class ClaseString {
    public static void main(String[] args) {
        String strInstance1 = new String("I am object instance of a String class");
        String strInstance2 = "Live your passion!";
       
        
        char x = strInstance1.charAt(2);
        char y = strInstance2.charAt(1);
        char z = strInstance2.charAt(0);
       
        System.out.println("The 3rd char of strInstance1 = " + x);
        System.out.println("The 2nd char of strInstance2 = " + y);
        System.out.println("The 1st char of strInstance2 = " + z);
        
        
        // Invoke an instance method equalsIgnoreCase(..) method
        boolean b = strInstance1.equalsIgnoreCase(strInstance2);
        String strInstance3 = b? "Yes":"No";
        System.out.println("Do strInstance1 and strInstance2 have same string ignoring case?  " +                    strInstance3);
       
        // Invoke a static-method, valueOf (int i), of the String class
        int i = 23;
        String strInstance4 = String.valueOf(i);
        System.out.println("value of strInstance4 = " + strInstance4);
       
        // You already have used parseInt() static method of the Integer class in
        // previous exercises.
        String strInstance5 = new String("34"); // Create an object instance of String class
        int ii = Integer.parseInt(strInstance5);
        System.out.println("value of ii = " + ii);
        
        
        // The following code will generate a compile error since you are trying to
        // invoke a instance method through a class.   Fix this compile error.
        //char f = strInstance5.charAt(2);
       // System.out.println("f");
        
        
        // endsWith() method
        String str = "Hello";   
        System.out.println( str.endsWith( "slo" ) );

        // forDIgit() method
        System.out.println( Character.forDigit(13, 16) );

        // floor() method
        System.out.println( Math.floor(3.14));

        // isDigit() method
        System.out.println( "0=" + Character.isDigit('0'));
        System.out.println( "A=" +Character.isDigit('A'));

    
    }
}