Udemy Java Masterclass 04: "Variables, Datatypes, and Operators" Final Coding Test

Ace your homework & exams now with Quizwiz!

Demonstrate using the modulo operator: Practice using other common operators in expressions:

% is the modulo symbol. This returns the remainder of an unevenly divided equation: EXAMPLE: int myRemainder = 9 % 6; System.out.println(myRemainder); The value of my myRemainder is 3. OTHER COMMON OPERATORS: int myNumber = 2 + 7; Plug the operators them into a statement similar to this above and experiment if you need the practice! Print out the result: System.out.println(myNumber); = assignment operator + plus - minus / divide * multiply > greater than < less than >= greater than or equal to <= less than or equal to != not equal to % = modulo (finds the remainder of a division problem)

Tim's final operator challenge: 1. Create a double variable with the value of 20 2. Create a second variable of type double with the value of 80. 3. Add both numbers up and multiply by 25 4. Use the remainder operator to figure out the remainder from the sum of #3 divided by 40 5. Write an "if" statement that displays a message "Total was over the limit" if the remaining total (#4) is equal to 20 or less.

(BOILERPLATE CODE): double doubleOne = 20d; double doubleTwo = 80; double doubleTotal = (doubleOne + doubleTwo) * 25; double doubleRemainder = doubleTotal % 40; if (doubleRemainder <= 20 ) { System.out.println("Total was over the limit"); } CORRECT TOTAL: 2500 doubleRemainder = 20; NOTE: Be very aware of operator precedence when you are doing calculations. If you write this out as: double doubleTotal = doubleOne + doubleTwo * 25; Your INCORRECT total will be 2020, not 2500.

1. Demonstrate using the && and the || operators: 2. What are these operators? When/how are they used?

1. DEMONSTRATE: int topScore = 80; int secondTopScore = 60; if ((topScore > secondTopScore) && (topScore < 100)) System.out.println("Greater than second score and less than 100"); if (topScore > 90) ||(secondTopScore <= 90) System.out.println("One of these tests is true"); 2. && is the "and" operator || is the "or" operator These are "conditional operators" and are used when evaluating multiple conditions for a boolean result. With the &&- BOTH conditions have to be true to execute the code: With the || - one OR the other condition (either condition) has to be true to execute the code below. NOTE: You must use TWO of each of these symbols (&& and ||). If you use only one- you will be performing a different function, and your results will not be predictable!

1. Demonstrate setting up a variable with a boolean value: 2. What are boolean's used for? 3. Demonstrate a working if statement (using a boolean evaluation):

1. EXAMPLE: boolean isMale = true; 2. booleans can only be two values: 'true' or 'false'. A boolean is used to evaluate/test whether something IS true or false- typically a condition: if(isMale == true) { DO THIS: EXECUTE MY CODE! 3. WORKING BOOLEAN IF STATEMENT: int myAge = 30; if(myAge >= 15) { System.out.println("You've passed level 1 of the initiation into our man club! It gets harder from here...");

1. Demonstrate assigning a value to a variable in Java: 2. Demonstrate printing the value that has been assigned to the console (in IntelliJ):

1. EXAMPLES OF ASSIGNING A VALUE TO A VARIABLE int myFirstNumber = 5; OR: String hello = "Hello world!"; 1. You declare the data type (int, String) 2. You name the variable "box" (myFirstNumber, hello) 3. You assign a value to the variable THAT MATCHES the declared data type (5, "Hello world!"). 4. Always close every statement in Java with a ;. NOTE: The value MUST match the declared data type! 2. PRINTING VALUE OF A VARIABLE TO THE CONSOLE Examples: System.out.println(myFirstNumber); OR System.out.println(hello);

What are the 8 data types that we have looked at so far? What do we call these data types?

1. Integer 2. Byte 3. Short 4. Long 5. Float 6. Double 7. Char 8. Boolean These are the "primitive" data types.

Demonstrate the difference between printing a String (a string can be any group of characters - including numbers & symbols) and a variable in a Java project (use your dummy/practice file):

1. PRINTING A STRING System.out.println("Hello world!"); 2. PRINTING A VARIABLE String hello = "Hello World!"; System.out.println(hello); The same thing will print out for both examples. Anything within the "" of the first example will print out (a String). Whatever value is contained within the variable hello is what will print for the second example.

What is the ternary operator and what is its function? Demonstrate using the ternary operator:

1. The ternary operator is a ? : Ternary is shorthand for if-then-else statement (simplify/dry our code). It is a way to set a value using two conditions. 2. DEMONSTRATE EXAMPLE: The syntax... wasCar = isCar ? true : false; is an ternary statement shortcut for: if (isCar) { wasCar = true; } else { wasCar = false; }

Demonstrate creating a 'char' unicode symbol that is NOT typically on your keyboard:

1. Visit www.unicode-table.com/en/#control-character 2. Use the table to find the symbol/character that you would like to add. 3. Enter as a char (within single quotations 'like this'). - Enter a forward slash \u (to indicate Unicode). - Type the code at the left hand side of the row, changing the the final character in that string to match the character of the column your symbol is in: char myChar = '\u00A9'; this will produce the "copyright" symbol.

Demonstrate "order of operations" in mathematical equations: - Create a variable that will contain the following value: - Add 5 and 10 together - Multiply the total by 15 - Print the total out to the console

CORRECT EXAMPLE: int myCalc = (5 + 10) * 15; System.out.println(myCalc); Correct answer is: 225. You MUST have parentheses around (5+10): Otherwise (INCORRECT EXAMPLE): int myCalc = 5 + 10 * 15; The multiplier here would take precedence in the order of operations and would: - INCORRECTLY multiply 10*15 FIRST... - then add 5 to that amount... And you would get an INCORRECT answer of: 155

Demonstrate using floating point numbers: Create a variable with a value that will be the result of unevenly divided number (i.e. the result will have several decimal points).

EXAMPLE 1: FLOAT- float myFloatResult = 5/3f; System.out.println(myFloatResult); RESULT (PRINTOUT): 1.6666667 EXAMPLE 2: DOUBLE- double myDoubleResult = 5/3; System.out.println(myDoubleResult); RESULT (PRINTOUT): 1.6666666666666667 REMEMBER: - If you declared "int" here: the console will print out 1 as the value of the variable (int only evaluates whole numbers: it will only be able to "see" that 3 goes into 5 one WHOLE time). ALSO: "double" is the default floating point Java type.

Demonstrate the difference between a number and a String of number CHARACTERS: If you attempt to add a number and a STRING OF number characters together, what will happen?

Example: String numberString = "50"; int myInt = 10; numberString = numberString + myInt; STRING "NUMBERS": Anything defined within "" is a String- Java does NOT recognize these characters as numbers! Because you have a String and a number, Java changes/converts the number to a String value and, instead of adding them, CONCATENATES them together. Essentially- the two values get squished together (5010), NOT ADDED.

What is wrong with this code and how do we fix it? boolean isAlien = true; if (isAlien = false) System.out.println("It is not an alien!");

Once again, you've used the assignment operator ( = ) in the if statement when you should have used the conditional "equals" operator ( ==). The code will actually execute because the if statement DOES return the boolean value expected. Why? Inside of the if statement, you have simultaneously assigned "false" to isAlien and then evaluated isAlien to see if it is false!

What is wrong with this code and how do we fix it? int newValue = 50; if(newValue = 50) System.out.println ("This returns an error!");

PROBLEM: In the if statement: We've used the assignment operator ( = ) instead of the equals conditional operator ( ==). The information that is returned from the parentheses MUST be a boolean value (true or false) for the condition to execute as intended, so the == symbol is typically used here. FIX: Simply change the = to == to evaluate the value of the variable. if(newValue == 50) System.out.println ("This returns an error!"); You may want to change that printout now that you've got your code working too! ;-)

What is the difference between the operators in these two lines that reference isAlien: boolean isAlien = false; if (isAlien == false) System.out.println("It is not an alien!");

The = is the ASSIGNMENT operator. It is assigning the value of false to the variable isAlien. The == is not assigning anything: it is TESTING to see whether isAlien EVALUATES to false. It's asking "is it true that 'isAlien' equals false? If so, then print the line below." This operator is closer to the equivalent to the mathematical equals sign.

What is the difference between the mathematical = (equals sign) and the same symbol in Java?

The mathematical = simply means "Equals". The = symbol in Java is the "assignment operator". Typically when used, the value on the right hand side of the expression is being assigned to the variable on the left hand side of the equation: int myNumber = 3; This would be accurate: myNumber = myNumber + 3; Take the current value of myNumber, add 3 to it, then assign the total to the variable (box) called myNumber.

What can you do with long numbers (ints and longs) to make them more readable?

You can place UNDERSCORED in your number and the compiler/editor will ignore it: 2_147_483_648.

Demonstrate "casting" a number correctly:

byte myNewByteNumber = (byte) (myByteNumber/2); REMEMBER: When you attempt to divide myByteNumber/2, you are attempting to divide a byte value by an integer value- because Java automatically defaults to int, so the 2 in this case is an integer. Without casting (byte) - Java assumes that an int cannot fit into a byte's allocated storage space/numerical range (even though in this case, technically it would). When we enter (byte) into the expression, we tell Java to treat everything in that expression as a byte.

Demonstrate your understanding of floating point numbers: Convert a given number of pounds to kilograms: (One pound = 0.453592 kilograms) 1. Create a variable to store the number of pounds 2. Calculate the number of kilograms for the number above and store in a variable. 3. Print out the result.

double myWeight = 195d; double kilosToPounds = .45359237d; double myWeightKilos = myWeight * kilosToPounds; System.out.println("I weight " + myWeightKilos + " in kilograms!"); NOTE: you can do the same thing with a float. HOWEVER- remember that "double" is the default floating point data type in Java: if you did this: float kilosToPounds = .45359237; IntelliJ will say there is an error: "incompatible types. required: "float" found: "double" If you want to use "float", you must cast- either (float) on the right hand side of the expression, or simply add an 'f' to the end of the number: float kilosToPounds = .45359237f;

Demonstrate the shortcut to incrementally increase or decrease the value of a variable by 1:

int result = 5; result++; (will now equal 6) result--; (will not equal 5) You can do: results++ OR results-- instead of: result = result + 1; result = result -1;

What shortcuts can you use when doing ANY calculation (using any operator) on the current value of a variable? Print out the values to verify the answer(s): example longhand: result = 5; result = result *5; result = result -3; etc...

result += 2; (value now 7) result -= 2; (value now 5) result *= 5; (value now 25) result -= 5; (value now 5) result %= 3 (value now 2) System.out.println(result);


Related study sets

Bio 131 Regulation of Gene Expression Weeks 10/11 Lecture 2

View Set

Nursing Skill: Nasogastric Tube Insertion and Removal

View Set

Chapter 2: Psychological Methods

View Set

Special Right Triangles Assignment and Quiz

View Set

World Geography Unit 2 Chapter 5 Lesson 2 Homework Questions

View Set

Kinesiology chapter 19: Knee Joint

View Set

#3 Life Insurance Policies- Provisions, Options, and Riders

View Set

Marketing Chapter 11: Product, Branding and Packaging

View Set

Dugga 1 Distributed Computing Tittis slides + chapter 1 i boken

View Set

NURS129 LESSON 2 PRACTICE QUESTIONS

View Set