Define in a Class the following data types

  • Demonstrate use of Primitives: int, double, boolean, string
  • Demonstrate use of Wrapper Class object: String

Describe in comments how each data type choice is appropriate to application

public class DefinePrimitives {
    public static void main(String[] args) {
      int anInt = 55; //can be used to calculate people's age or grades
      double aDouble = 12.2; //can be used in a grade calculator
      boolean aBoolean = false; //can be used in a survay

      // not primitives but essential
      String aString = "Hello, I am Linda Liu!";   // can be used to display text
      String aStringFormal = new String("Greetings, World!");
  
      System.out.println("anInt: " + anInt);
      System.out.println("aDouble: " + aDouble);
      System.out.println("aBoolean: " + aBoolean);
      System.out.println("aString: " + aString);
      System.out.println("aStringFormal: " + aStringFormal);
    }
  }
  DefinePrimitives.main(null)
anInt: 55
aDouble: 12.2
aBoolean: false
aString: Hello, I am Linda Liu!
aStringFormal: Greetings, World!

Perform arithmetic expressions and assignment in a program code

  • simple operations
  • use compound assignment operator to perform an operation on both operands and store the result into the variable on the left

Perform compound assignment operator (ie +=), add comments to describe the result of operator

int a = 10;
int b = 5;
int c = 100;
int d = 0;

d = ( a + b ) * c;
System.out.println("d = " + d);


d /= c; //use compound assignment operator (/=)
System.out.println("d = " + d);

d += (a * b); //use compound assignment operator (+=)
System.out.println("d = " + d);
d = 1500
d = 15
d = 65

Determine what is result is in a variable as a result of an data type and expression (ie integer vs double)

  • the result of the variable d as a result of the operations (of intergers) is also an interger

Perform an arithmetic expressions that uses casting, add comments that show how it produces desired result.

  • we use casting in java to change the data type of a variable frome one type to another
  • if one of the value in an expression is a double, java will assume that you want a double result
    • or we can use the casting operator double
  • we can also use the casting operators to round
System.out.println(10/5);
System.out.println(10.0/5);
System.out.println((double) 10/5); //use casting operator double in ()
2
2.0
2.0
double number = 10/3;

System.out.println((double)10/3);

System.out.println((int)10/3); //int will drop everything after decimal, not rounding it

int roundedNumber = (int) (number + 1.1); //add 1.1 to the number, cast that as an int, store result in roundedNumber

System.out.println(roundedNumber);
3.3333333333333335
3
4