Friday, March 18, 2016

Which GUI API is best for Desktop Java Applications?


When programming in Java there are many different GUI APIs to choose from including AWT, SWT, Swing, and JavaFX. Which one should you use for your Java application? Is it even worth learning how to use these libraries considering how most Java development is now Android based?

Wednesday, March 16, 2016

Enumerations In Java

Creating Enum Types

An enumeration is a data type that allows you to create variables with a list of predefined definitions. The variables created with specific Enum types must be equal to one of the predefined values in the list. They are constants, so the names in the enum are put in upper case. The following example creates an Enum type called "Color" which includes a predefined list of some colors.

public enum Color {
 RED, BLUE, GREEN, YELLOW, BLACK, WHITE, PINK
}
Watch Enum Video

Eclipse Shortcut

If you are using Eclipse you can create a new Enum by right clicking on the package you want to add an Enum to, selecting New, and clicking Enum.

Using The Enum

You can use the Enum like you would use any other variable. Declare the variable with the name of the Enum as the variable type, give the variable an identifier, and assign a value to it. The example below creates two Color variables, checks to see what the color is, and demonstrates what it looks like when you print the variable out.

//Creating Color Variables
Color myFavoriteColor = Color.BLACK;
Color herFavoriteColor = Color.BLUE;
//Checking With Conditional If-Then
if(myFavoriteColor == Color.BLACK){
 System.out.println("Your favorite color is Black!");
}
//Standard toString
System.out.println(myFavoriteColor);
Your favorite color is Black!
BLACK

Looping Through Enumerations

You can loop through all the values of an Enum with a for each loop using the .values() method which returns an array containing all possible values of the specified Enum. The example below loops through all the values in an Enum named Color and prints them to the console.

for(Color aColor:Color.values()){
 System.out.println(aColor);
}
RED
BLUE
GREEN
YELLOW
BLACK
WHITE
PINK

Multiple Enums In A File

It is possible to add multiple enums to a file by placing the Enums within a Class file.

public class Colors{
  public enum DarkColors {RED,BROWN,BLACK}
  public enum LightColors {YELLOW,PINK,WHITE}
  ....
}

You can then access the Enums with their class name followed by the enum name:

Colors myColor = Colors.DarkColors.BLACK;

Get Current Date/Time As String in Java

Watch Video

The simplest way to get the date and time as a String in Java is to import and use the following classes: Date and SimpleDateFormat. The Date class contains the current Date data and the SimpleDateFormat class allows us to format the date data in a manner we specify.

The following example prints out the current date and time formatted in US date/time notation.

import java.text.SimpleDateFormat;
import java.util.Date;

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

  SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/y hh:mm:ss a");
  Date thisDate = new Date();
  System.out.println(dateFormat.format(thisDate));

 }

}
Sample Output10/26/2015 06:55:07 PM

Modifying The Date Format

You can modify the date format string when you create the SimpleDateFormat with any of the following:

  • MM - The numerical month of the year
  • dd - The numerical day of the month
  • D - The numerical day of the year
  • W - The numerical week of the month
  • w - The numerical week of the year
  • E - The text format day of the week abbreviation
  • EEEE - The full text format day of the week
  • MMMM - The text format month of the year
  • a - AM or PM
  • H - Numerical hour of the 24 hour day
  • h - Numerical hour as AM/PM from 1-12
  • m - Numerical minute in hour
  • s - Numerical second in minute

For example, you could modify the date format to print out the date in US text format:

SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE MMMM dd, Y. h:mm a");
Date thisDate = new Date();
System.out.println(dateFormat.format(thisDate));
Sample OutputMonday October 26, 2015. 7:09 PM

Tuesday, March 15, 2016

Intro To Java: Section 3.3 - Using Switch Statements

Topic 3.3 Overview

In this section we will cover how to use another control structure known as a Switch.

Lecture Video 3.3

Switch Statements

Switch statements in Java allow you to easily define certain paths in which code can be executed based on specific values. Switches are composed of two parts - the switch, which takes the value, and the case, which corresponds to a particular value. For example, you could create a switch that takes a number representing a particular day of the week, and then each case could print out what day it is based on that value. Although you could achieve the same thing using multiple if/else statements. it is much cleaner in this scenario to use a single switch. The end of each code section should end with a break; to end the execution. If you do not include a break, once the case is satisfied, Java will continue executing the following cases regardless of whether or not the value matches the particular case.

public class DayOfWeek{
 public static void main(String[] args) {
  //Day of the week
  int day = 5;
  //Switch
  switch (day) {
   case 1: System.out.println("It is Sunday"); break;
   case 2: System.out.println("It is Monday"); break;
   case 3: System.out.println("It is Tuesday"); break;
   case 4: System.out.println("It is Wednesday"); break;
   case 5: System.out.println("It is Thursday"); break;
   case 6: System.out.println("It is Friday"); break;
   case 7: System.out.println("It is Saturday"); break;
   //Handle all other cases
   default: break;
  }
 }
}
It is Thursday

The above code prints out "It is Thursday" because it begins executing code at the 5th case. If the break statements were not there the blocks would fall through - Cases 5, 6, and 7 would all be executed without a break statement. The default case handles all of the other possible cases - in this case they're all just set to break.

Combining Cases

In addition to having a single case with a single set of actions, it is possible to have multiple cases perform one set of actions. You do this simply by adding multiple cases to a set of actions. The example below demonstrates this.

public class Test {

 public static void main(String[] args) {
  
  //Initialize
  int someValue = 5;
  
  //Create Switch
  switch(someValue){
  //Operations for cases 1, 2, and 3
  case 1: case 2: case 3: 
   System.out.println("Case 1, 2, or 3 has been triggered.");
   break;
  //Operations for cases 4, 5, and 6
  case 4: case 5: case 6:
   System.out.println("Case 4, 5, or 6 has been triggered.");
   break;
  //Default case for all other cases not caught in 1,2,3,4,5,6
  default: break;
  
  }
        
 }

}
Case 4, 5, or 6 has been triggered.

The system prints out that case 4, 5, or 6 has been triggered because someValue is equal to 5. It would also trigger if someValue was equal to 4 or 6. The first block would trigger if the value was 1, 2 or 3, and nothing would be printed if any value less than 1 or greater than 6 is given.

Review Exercise 3.3 - Menu Calculator

Instructions: Create a calculator which prompts the user to enter two values. It should then display a menu with 4 options - 1 to find the sum, 2 to find the difference, 3 to find the product, and 4 to find the quotient. The program should determine which number the user entered using a scanner and then calculate the result within the context of a switch and print out the result to the screen.

Sample Output:

Welcome to Calculator.
Please enter a first value:
10.00
Please enter a second value:
5.00
Would you like to:
1) Find the sum
2) Find the difference
3) Find the product
4) Find the quotient
1
Calculated Sum: 15.00

Monday, March 14, 2016

Intro To Java: Section 3.2 - Decision Making

In this section we will learn how to use control structures to make decisions in Java.

Watch 3.2 Lecture Video

Equality and Relational Operators

Computers are much more than calculators which take input and return formatted output. They can also make decisions using that data. Java makes it extremely easy to make decisions using if then conditional statements. Essentially they work just as they sound - The JVM will check to see if a certain condition is met, and if it is, it will perform a certain set of actions. The three most basic ways you can compare values using if/else statements are checking if two values are equal to one another or if one value is greater or less than the other value. The operators we use to compare values are known as equality and relational operators.

If then statements follow the syntax shown below:

if(conditions){
     //Code to execute in brackets
}

Equality and Relational Operators

You should memorize all the operators below. They are easy to remember and you will use them often.

NameOperatorDescriptionExample
Equal to == Checks if two values are equal if(x==y){}
Not equal to != Checks if two values are not equal if(x!=y){}
Less than < Checks if the first value is less than the second value if(x<y){}
Greater than > Checks if the first value is greater than the second value if(x>y){}
Less than or equal to <= Checks if the first value is less or equal to than the second value if(x<=y){}
Greater than or equal to >= Checks if the first value is greater than or equal to the second value if(x>=y){}

If-Then Statements With Equality

Equality can be assessed using the equality operator "==". We always use two equal signs to determine if two values are equal instead of one because the one equal sign operator is reserved for assigning values. Additionally, the not equals operator "!=" is used to determine if two values are not equal to each other. The following lines of code check to determine what the value of x is and print out a corresponding message based on what the value of x is.

public class EqualityTest{

     public static void main(String []args){
        int x = 5;
        if(x==5){
            System.out.println("x is equal to 5");
        }
        if(x!=5){
            System.out.println("x is not equal to 5");
        }
     }
}

The output of the program is as follows because x is in fact equal to 5. Note that if you change the value of x the second message will be printed instead of the first one.

x is equal to 5

If-Then Statements With Greater/Less Than

In addition to checking for equality, it is also extremely useful to be able to tell if one value is greater than or less than another value. This can be done using the greater than operator ">" and the less than operator "<". Combinations of these can be made with an equals sign to create the greater than or equal to ">=" operator and the less than or equal to "<=" operator.

The example below checks if one value is greater than another and prints out which value is greater.

public class GreaterLessThan{

     public static void main(String []args){
        //Initialize Variables
        double x = 5.0;
        double y = 10.0;
        //Check Values
        if(x>y){
            System.out.println("x is greater than y");
        }
        if(x<y){
            System.out.println("x is less than y");
        }
        if(x==y)
        {
            System.out.println("x is equal to y");
        }
        
     }
}

In this case the output is as follows, because x is less than y. Note that if you change the values of x and y the output can be different.

x is less than y

If Then Else Statements

In addition to if then statements, you can add an else block to create if then else statements. The "else" part of the statement is executed when the if statement is not executed. In other words, if the first condition is not met, it will execute the "else" statement. This helps shorten your code and allows you to use less if then statements. The example below checks if x is greater than or equal to y, and if not it prints out a message saying that x must be less than y.

public class IfElseExample{

     public static void main(String []args){
        //Initialize Variables
        int x = 10;
        int y = 20;
        
        //If Then Else Statement
        if(x>=y){
            //If x is greater than or equal to y
            System.out.println("x is greater than or equal to y");
        }
        else
        {
            //This code is executed if the first block is not executed, so x must be less than y
            System.out.println("x must be less than y");
        }
        
     }
}

The output is as follows, because x is less than y, and not greater than or equal to y, the else block is executed.

x must be less than y

Else If Statements

In addition to the if then else statements shown above, it is possible to have "else if" statements. They function similarly to else statements, but they also have conditions. So if the first condition is not met, Java will check the second, third, fourth, fifth conditions and so on. The example below quite simply prints out whether the value is equal to one, two, or not one of those two values.

public class ElseIfExample{
 
 public static void main(String[] args) {
  int x = 2;
  if(x==1){
   System.out.println("x is equal to one");
  }
  else if(x==2){
   System.out.println("x is equal to two");
  }
  else
  {
   System.out.println("x is not equal to one or two");
  }
 }

}
x is equal to two

Naturally the output is "x is equal to two" because the second condition is satisfied. Note that it stops once the condition is satisfied - the first block (x==1) is skipped and final else block is not executed.

Nested If Statements

It is possible to add if statements within if statements - this is known as nesting. This allows you to check for multiple things. The example below the age of the user based on if they're at or under the age of 10. It then determines if they are male or female after determining if they are 10 years old or younger with a second if statement within the first.

public class NestedExample{

 public static void main(String[] args) {
  
  //Nested If Statement Example
  int age = 6;
  boolean isMale = true;
  
  //Check to see if user is under the age of 10 and is a male
  if(age<=10){
   if(isMale==true){
    System.out.println("The user is a male under the age of 10");
   }
   else{
    System.out.println("The user is a female under the age of 10");
   }
  }
  else{
   System.out.println("The user is over the age of 10");
  }

 }

}

 

The user is a male under the age of 10

Multiple Conditions With And/Or

It is possible to have multiple conditions in a single if statement. This can be used as an alternative to nested if statements. The example below produces the same types of output as the previous example, but this uses the logical AND operator "&&". This means both conditions must be true for the block to execute. You can add as many additional conditions to the statement as you want.

public class Test {

 public static void main(String[] args) {
  
  //Example Using AND
  int age = 6;
  boolean isMale = false;
  
  //Check if user is under the age of 10 and is a male
  if(age<=10 && isMale==true){
   System.out.println("The user is a male under the age of 10");
  }
  //Check if user is under age of 10 and is female
  else if (age<=10 && isMale==false){
   System.out.println("The user is a female under the age of 10");
  }
  //User is over the age of 10
  else
  {
   System.out.println("The user is over the age of 10");
  }
  
 }
}
The user is a female under the age of 10

The output is "The user is a female under the age of 10" because the first condition is not satisfied (the user is not a male) so it continues on to the second block (the user is a female age 10 or younger).

The logical OR operator is made using two vertical bars "||" (should be located above the enter/return key). When you use OR operators if EITHER of the conditions are true in the if statement, the block will be executed.

public class Test {

 public static void main(String[] args) {
  
  //Example Using OR
  int age = 66;
  boolean isMale = true;
  
  //Check to see if the user is under the age of 10 OR if they are male
  if(age<=10 || isMale==true){
   System.out.println("The user is a male and/or is under the age of ten");
  }
  //If they are not a male OR aged < = 10 they MUST be female AND over the age of 10
  else
  {
   System.out.println("The user must be a female over the age of 10");
  }

 }
}
The user is a male and/or is under the age of ten

The output states that the user is a male and/or is under the age of ten because the user is a male. Even though they are aged 66 the first block is still executed. If this used an AND operator instead of an OR operator like the previous example, the first block would not have been executed. The else block of code will only be executed if the user is over the age of 10 and is a female - because that is the only logical thing that follows if the user is not a male or aged 10 or younger.

Combining/Multiple Operators

In addition to using a single and/or operator, it is possible to use multiple. You can separate each comparison using parenthesis. The example below prints out information based on the user's age, sex, and hair color.

 

The user is a male over age 30 AND/OR they have blond hair

Note what this code is doing. First, it checks if they are a male over the age of thirty, and then it checks if they have blond hair. If either of these conditions are true, the first message is printed. The second condition (haircolor=='R') checks to see if the user's hair color is red - this block will only be executed if the user has red hair and is not a male over age thirty. Try changing the values of the variables to see how it affects the results.

Additionally, notice that you do not have to check if "isMale==true" in the first condition - you can simply type the name of the boolean to check boolean values. If the boolean is true Java will execute the code. In other words, "if(isMale){}" is equivalent to "if(isMale==true){}". It's slightly shorter to type it this way.

public class Test {

 public static void main(String[] args) {
 
  //Example - Combining AND and OR
  
  int age = 43;
  boolean isMale = true;
  char hairColor = 'R'; //Red hair (R), Brown hair (B), or Blond Hair (L) 
  
  //Check to see if they are a male over the age of 30 OR if they have blond hair
  if((isMale && age>=30) || hairColor=='L'){
   System.out.println("The user is a male over age 30 AND/OR they have blond hair");
  }
  else if(hairColor=='R'){
   System.out.println("The user is not a male over age 30 and their hair color is Red.");
  }

 }
}

Sunday, March 13, 2016

Intro To Java: Section 3.1 - BigDecimals

In this section you will learn how to create and use BigDecimals to store currency values and control rounding.

BigDecimals

Unfortunately none of the primitive data types are apropriate for storing currency. Integers and longs cannot hold decimals. Floats and doubles are not percise enough to represent currency. If we used floats and doubles to perform calculations in important financial systems the values could regularly be off by one penny or more. Balances would be off, customers would be angry, and accounting would be impossible. This is where the BigDecimal object comes into play - BigDecimals are specialized objects which are appropriate for storing currency values. BigDecimals are immutable objects meaning once you create it its value cannot be changed directly - in order to perform computations you must use the appropriate BigDecimal methods and create entirely new BigDecimals. In order to access this class in your program, it must be properly imported in the same manner as the Scanner object from the previous topic. In order to import and use Big Decimals, you must access it from the math package of the Java API.

import java.math.BigDecimal;
Once you've imported the BigDecimal class you will be able to use BigDecimals in your code. Keep in mind that BigDecimals are not the same as primitive data types. Like Scanner objects, BigDecimals are also treated as objects and must be initialized as follows. First you must tell Java what type of object you are creating (BigDecimal) and name it (myDecimal). You must then initialize it as a new BigDecimal object with a value of your choice. Pass the value you would like to set it to as the first argument. (I chose 250.05).

BigDecimal myDecimal = new BigDecimal("250.05");
Now that the BigDecimal is initialized we can use it elsewhere in our code. Just like primitive data types, we can add, subtract, divide, and multiply. Unfortunately we cannot simply use the traditional operators (+, -, /, *). We must use the methods provided to us by the BigDecimal class. View the following example.

//Create Big Decimals
 //Note - We are passing the argument as a string instead of a double (note the quotes)
 //       the quotation marks are optional here but this prevents rounding errors.
 BigDecimal decimalOne = new BigDecimal("10.00");
 BigDecimal decimalTwo = new BigDecimal("5.00");
 
 //Operation Examples using BigDecimal methods
 //Addition decimalAdditionResult = decimalOne + decimalTwo
 BigDecimal decimalAdditionResult = decimalOne.add(decimalTwo);
 
 //Subtraction decimalSubtractionResult = decimalOne - decimalTwo
 BigDecimal decimalSubtractionResult = decimalOne.subtract(decimalTwo);
 
 //Multiplication decimalProductResult = decimalOne * decimalTwo
 BigDecimal decimalProductResult = decimalOne.multiply(decimalTwo);
 
 //Division decimalDivisionResult = decimalOne / decimalTwo
 BigDecimal decimalDivisionResult = decimalOne.divide(decimalTwo);
The code above is fairly simple to understand. All we're doing is applying operations to decimalOne using whatever values are passed in the arguments - the value is then stored in the new respective result BigDecimal. Whenever you use these operations (add/subtract/multiple/divide) you are generating a new BigDecimal.
Although BigDecimals are immutable objects, it is possible to "change" their values indirectly by updating their reference variable. Technically, you are not changing the value of the BigDecimal, but instead are creating an entirely new BigDecimal object to which the old variable name references. For example, you could add a second BigDecimal to a first BigDecimal using the .add() method - this returns an entirely new BigDecimal to which you can reference using the old name. This works because we are not directly modifying the values of the original BigDecimal, but are replacing it with a new BigDecimal that has the same name.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create BigDecimals
  BigDecimal someDecimal = new BigDecimal("14.00");
  BigDecimal otherDecimal = new BigDecimal("6.00");
  
  //Add otherDecimal to someDecimal
  someDecimal = someDecimal.add(otherDecimal);
  
  //Print
  System.out.println("The value of someDecimal is " + someDecimal.toString()); 
  
 }
}
The value of someDecimal is 20.00
Note that if you are doing this, you must always do it in this format: "someDecimal = someDecimal.add(otherDecimal);" - you cannot just have "someDecimal.add(otherDecimal);"
The diagram below illustrates what happens in the previous example.
Given this knowledge, it is also possible to change the value of the BigDecimal by having it reference a new BigDecimal.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create BigDecimals
  BigDecimal aDecimal = new BigDecimal("14.00");
  
  System.out.println("The value of aDecimal is: " + aDecimal.toString());
  
  //Reference a new BigDecimal
  aDecimal = new BigDecimal("10.00");
  System.out.println("The value of aDecimal is: " + aDecimal.toString());
 }
}
Output
The value of aDecimal is: 14.00
The value of aDecimal is: 10.00

Printing Results

You may print out the results in the same manner that we printed out the values of variables in the previous sections. Note that Java is actually converting the value of the BigDecimal into a string automatically. This means we don't have to manually convert the BigDecimal into another primitive data type such as a double before we print out its result.

 //Printing out results - Java automatically converts BigDecimals to Strings for output
  System.out.println("Addition result is: " + decimalAdditionResult);
  System.out.println("Subtraction result is: " + decimalSubtractionResult);
  System.out.println("Product result is: " + decimalProductResult);
  System.out.println("Divison result is: " + decimalDivisionResult);
Addition result is: 15.00
Subtraction result is: 5.00
Product result is: 50.0000
Divison result is: 2
It is also possible to manually convert the BigDecimal to a string and then print out its value. Note that the two examples below are basically the same thing - we're just printing out two concatenated strings.

//Convert to String - option one
  String resultString = decimalAdditionResult.toString();
  System.out.println("Result is: " + resultString);
  
  //All in one step - option two
  System.out.println("Result is: " + decimalAdditionResult.toString());
Result is: 15
Result is: 15
Alternatively, you could manually convert the BigDecimals to doubles and then print the values out to whatever amount of spaces you want using the proper format specifiers. BigDecimals can be converted to doubles using the .doubleValue method.

//Convert Result to Double
  double additionResult = decimalAdditionResult.doubleValue();
  System.out.printf("The addition result to two decimal places is %.2f",additionResult);
The addition result to two decimal places is 15.00
Just like the string result of the BigDecimal can be printed using one line of code - we can also print out the double result for the BigDecimal using one line of code by throwing the BigDecimal.doubleValue directly into the print method's arguments.

System.out.printf("The addition result to two decimal places is %.2f",decimalAdditionResult.doubleValue());
You may use any of the above methods to print out the values of variables. Many other objects in Java aside from BigDecimal also make use of the .toString and .doubleValue methods.

Setting Scale To Control Rounding

In addition to being able to control the amount of decimal places in BigDecimals by converting them to doubles you can also use the BigDecimal setScale method. This is the preferred way to do it because it gives you control over exactly how your decimals will be rounded. After creating your BigDecimal, you can use the setScale method to define the amount of decimal places you would like the BigDecimal to go to. In most cases with currency you will be using a value of 2 to go to two decimal places. The format for creating a BigDecimal with a set scale is as follows:

BigDecimal someDecimal = new BigDecimal("value").setScale(scale, roundingMode);
The beginning of the BigDecimal is set in the same manner as we previously created BigDecimals. Now however, we have introduced the .setScale method. You should always pass this two arguments. First, you should pass it an integer which represents how many decimal places you want to use. Second, you need to select a rounding mode. There are five main rounding modes we will discuss. Additional modes exist and can be referenced in the Java API.
  • BigDecimal.ROUND_CEILING: Rounds to the next highest number (1.222 -> 1.23) (-1.222 -> -1.22)
  • BigDecimal.ROUND_DOWN: Rounds in the direction of zero (1.222 -> 1.22) (-1.222 -> -1.22)
  • BigDecimal.ROUND_FLOOR: Rounds to the next lowest number (1.222 -> 1.22) (-1.222 -> -1.23)
  • BigDecimal.ROUND_HALF_UP: Rounds up if the decimal is >= 5 (1.225 -> 1.23) (1.224 -> 1.22)
  • BigDecimal.ROUND_HALF_DOWN: Rounds down if the decimal is <= 5 (1.225 -> 1.22) (1.226 -> 1.23)
Typically in math class we're taught to round up at 0.5 and down at 0.4 - so this fits with the BigDecimal.ROUND_HALF_UP rounding mode. The example below demonstrates this type of rounding.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create a BigDecimal
  BigDecimal someDecimal = new BigDecimal("14.555").setScale(2, BigDecimal.ROUND_HALF_UP);
  
  //Print
  System.out.println("The value of someDecimal is " + someDecimal.toString()); 
  
 }
}
Output:
The value of someDecimal is 14.56
The output was 14.56 because 14.555 was rounded up to 14.56.

Unreferenced Objects With BigDecimals

In Java, it is possible to create unreferenced objects, which are not referenced by name. This is especially useful in situations where you want to create an object for a single purpose and then get rid of it. The example below illustrates how we would typically add 10 to a BigDecimal object - by creating a second BigDecimal which holds the values we want to add and then combining the two BigDecimals and storing them in a third BigDecimal which stores the total sum.

import java.math.BigDecimal;
public class Test {
 public static void main(String[] args) {
  //Adding 5 to aBigDecimal
  //Create aBigDecimal
  BigDecimal aBigDecimal = new BigDecimal("5");
  BigDecimal bBigDecimal = new BigDecimal("10");
  //Add the two together and store result in sumDecimal
  BigDecimal sumDecimal = aBigDecimal.add(bBigDecimal);
  //Print Results
  System.out.println("aBigDecimal + 10 = " + sumDecimal.toString());   
 }
}
aBigDecimal + 10 = 15
But what if you want to add 10 to aBigDecimal without creating bBigDecimal to store the value of 10? If you're only using the value 10 one time to perform one computation it's quite tiresome to create a second bBigDecimal object. This can be simplified by using an unreferenced object. You can create unreferenced objects without names directly in the arguments for the BigDecimal arithmetic methods.

import java.math.BigDecimal;
public class Test {
 public static void main(String[] args) {
  //Adding 5 to aBigDecimal
  //Create aBigDecimal
  BigDecimal aBigDecimal = new BigDecimal("5");
  //Add 10 to aBigDecimal and store the result in sumDecimal
  BigDecimal sumDecimal = aBigDecimal.add(new BigDecimal("10"));
  //Print Results
  System.out.println("aBigDecimal + 10 = " + sumDecimal.toString());   
 }
}
aBigDecimal + 10 = 15
The result is the same as in the previous example, but the method is different. We added "(new BigDecimal("10")" directly inside the arguments for the BigDecimal addition method. This created an unreferenced BigDecimal object with the value of 10 so we didn't have to create a second bBigDecimal to perform the one time computation.

Scanners With BigDecimals

It is important to understand how to get user input and store it as a BigDecimal. The method works quite similarly to how it did in the previous lesson. The example below demonstrates how you can ask a user to give you a monetary value and then print that value to the screen.

import java.math.BigDecimal;
import java.util.Scanner;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create a scanner
  Scanner userInput = new Scanner(System.in);
  
  //Ask the user for a value
  System.out.println("Enter some monetary value");
  BigDecimal numberEntered = userInput.nextBigDecimal();
  
  //Close Scanner
  userInput.close();
  //Print Result
  System.out.println("The value of numberEntered is " + numberEntered.toString());
 }
}
Output:
Enter some monetary value
20.20
The value of numberEntered is 20.20

Review Exercise 3.1: Sales Tax

Instructions:Create a simple program using BigDecimals that calculates a sales tax of 6% and prints out the total.
Suggested Methodology:
  1. Create a Scanner to retrieve user input as a BigDecimal
  2. Create a BigDecimal with value 0.06 for multiplying with total to calculate taxes
  3. Create an additional taxes BigDecimal and total BigDecimal to store the tax amount and the total.
  4. Use the .setScale method to set the rounding scale to 2 on each of the BigDecimals.
  5. Use the BigDecimal methods to calculate the taxes and totals
  6. Print out the results
Sample Output
Please enter item price:
100.00
Item Price: $100.00
Sales Tax: $6.00
Total Price: $106.00
View Solution

Intro to Java: Topic 03 - Money & Decision Making Overview


Topic 03: Money & Decision Making, discusses how to keep track of currency using BigDecimals. Additionally, you will learn how you can use Java to make decisions using if/then/else statements. We will learn how basic logic works with regards to computers. We will also discuss how switches may be used. For the final review exercise we will create a program that can calculate federal income tax based on set tax brackets.

Basic Calculator Java Source Code (2.4)

The code below demonstrates how to create a simple calculator as instructed in Intro to Java section 2.4

package basiccalc;
 
import java.util.Scanner;
 
public class Calculator {
 
    public static void main(String[] args) {
         
        //Create The Scanner
        Scanner userInput = new Scanner(System.in);
         
        //User Input
        System.out.println("Welcome to Calculator");
        System.out.println("Please enter your first value:");
        double x = userInput.nextDouble();
        System.out.println("Please enter your second value:");
        double y = userInput.nextDouble();
         
        //Close Scanner
        userInput.close();
         
        //Compute
        double sum = x + y;
        double product = x * y;
        double quotient = x / y;
        double remainder = x % y;
         
        //Print out the results
        System.out.println("Results are as follows:");
        System.out.printf("Sum: %f + %f = %f \n",x,y,sum);
        System.out.printf("Product: %f * %f = %f \n",x,y,product);
        System.out.printf("Quotient: %f / %f = %f \n",x,y,quotient);
        System.out.printf("Remainder: %f / %f = %f",x,y,remainder);
     
    }
 
}