Skip to content

Week 2 - Variables and Operators

Variables and Operators

Declaring Variables

  • Allocate Storage Location of that Data-Type
  • Type informs java of possible Values.

    1
    2
    3
    4
    5
    String aString;
    int anInt;
    double a64BitFloat;
    float a32BitFloat;
    char aCharacter;
    
  • Note the capital letter in String

    • A string is Special Object in Java
    • OK, so why don’t we have to create strings like we create other objects i.e. String aString = new String("aString");?
      • Java founders determined Strings were so common, Strings needed to be treated differently (i.e. reference the same literal string even if assigned to 2 different variables.
      • Consider the following blocks of code:
        1
        2
        3
        4
        5
        6
        7
        String a = "Next iteration";
        String b = "Next iteration";
        System.out.println("What will this be?" +  ((a == b) ? "True" : "False") ); // ? are they the same ?
        
        for (int i = 0; i < 10; i++) {
          System.out.println("Next iteration"); // If the literal String weren't a reference, this would instantiate the string every single loop.
        }
        
      • Thus, Strings are interned to:
        • Lower memory requirements.
        • Make comparisons faster.
      • BUT WAIT, if strings are shared/cached references, wouldn’t changing the string for variable a also change it for b?
        • Yes, but that’s why the designers also made literal strings immutable. String methods that modify a string will return new string, not the original literal.
        • This is also why you should not compare strings with == but a.equals(b) because == compares the reference while the other compares the string.
  • Declare variables of the same type on 1 line!

    1
    int a, b, c = 5; // This is OK!
    
  • Variables names must be unique (within its scope), and not a reserved keyword like static, private, public, final, class, etc.

1
2
3
4
5
6
7
8
public class Example {
    public static void main(String[] args) {
        double pi = 3.14;
        double pi = 3.141592653;  // Nope, Nope, Nope!

        System.out.println("The value of pi is: " + pi);
    }
}
  • Variables are case sensitive
1
2
int firstName = 1;
int FirstName = 2;
  • Camel Case is Java’s preferred naming convention.
1
int firstName;

Other Naming Conventions

  • Variable names cannot contain certain special symbols, such as exclamation marks (!).
  • Spaces are not allowed.
  • Numbers can be used within a variable name as long as the name does not begin with a number.
  • A variable’s name cannot already be in use.

Excercise

  • What is wrong with these variable names?
Bad Variables
1
2
3
4
last day of month = 20
1day = 1952
beware! = 1910
1920 = 1

Assignment - Initialize a Variable

  • Stores/Updates variable value, but you must assign the right data-type.
1
2
String a = "123";
String a = 123; // Error: wrong type.
  • You only have to define the variable type when declaring it, any assignment after must leave off the type.
    • The variable type persists.
      1
      2
      int value = 10;
      value = 4;
      
  • Variables of different type(s) can be assinged as long as there is no loss in precision.
    1
    2
    double fpNum = 42.5;
    fpNum = 42;
    

State - Forget diagrams (like in the book) - Use IntelliJ debug

  • Why waste your time, use the state diagrams that already exist in your IDE ;-)
  • Breakpoints & variable analysis is the modern way to debug variables.

Arithmetic Operators

  • Symbols for doing Math
  • See Arithmetic Operators
  • Type aware, int division is int only result! (i.e. 59/60 == 0)

Operations with Floating Point

  • Fractional numbers, with fractional precision, BUT NOT PERFECT!, which leads to rounding errors.
  • 1 or more double numbers will cause operators to use floating point calculations.
  • If you’re equation depends on fractional precision use doubles to avoid 59/60 error, or convert to whole numbers like $$$ libraries do.
  • Java will implicitly convert integer assignment to a double, however.

Operators for Strings

  • + concatenates
    • Many variables can be joined to a string using the + operator:
Variable/String Concatenation
1
2
3
4
5
6
7
8
9
String text = "contains text";
int wholeNumber = 123;
double floatingPoint = 3.141592653;
boolean trueOrFalse = true;

System.out.println("Text variable: " + text);
System.out.println("Integer variable: " + wholeNumber);
System.out.println("Floating-point variable: " + floatingPoint);
System.out.println("Boolean: " + trueOrFalse);
StdOut
1
2
3
4
Text variable: contains text
Integer variable: 123
Floating-point variable: 3.141592653
Booolean: true
  • .equals("compares"); compares!

Errors

  • Compile Errors - Syntax errors, Keywords as variable names, etc. causes Parser to barf.
  • Runtime Errors - Errors that cause exceptions only when the program is run i.e. FileNotFoundException
  • Logic Error - Compiles and runs without errors, but the output is invalid. double percent = 59 / 60;

Show how to Read Strings, Integers, Doubles, and More

Read an String
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.Scanner;

public class Program {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Write text and press enter ");
        String text = scanner.nextLine();
        System.out.println("You wrote " + text);
    }
}
Read an Integer
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import java.util.Scanner;

public class Program {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Write a value ");
        int value = Integer.parseInt(scanner.nextLine().trim());
        System.out.println("You wrote " + value);
    }
}
Read a Double
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Write a value ");
        double value = Double.parseDouble(scanner.nextLine().trim());
        System.out.println("You wrote " + value);
    }
}

Exercise

  1. Write a program that asks the user for an integer value. The program should then add 1 to the value provided by the user, and print that new value.
  2. Write a program that asks the user for a floating-point number using the variable type Double. The program then prints the user’s input value.
  3. Make the following code ouput:
StdOut
1
2
3
4
Summary:
    Chicken: 4
    Bacon: 5.600000
    Tractor: John Deer!
Replace variables
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int chicken = 3;
        double bacon = 5.5;
        String tractor = "None!";
        String summary = """

                Summary:
                    Chicken: %d
                    Bacon: %f
                    Tractor: %s
                """;
        Scanner s = new Scanner(System.in);
        try {
            System.out.printf("Chicken: %d%n", chicken);
            String input = s.nextLine().trim();
            chicken = (input.isEmpty()) ? chicken : Integer.parseInt(input);
            System.out.printf("Bacon: %f%n", bacon);
            input = s.nextLine().trim();
            bacon = (input.isEmpty()) ? bacon : Double.parseDouble(input);
            System.out.printf("Tractor: %s%n", tractor);
            input = s.nextLine().trim();
            tractor = (input.isEmpty()) ? tractor : input;
            System.out.printf(summary, chicken, bacon, tractor);
        } catch (NumberFormatException nfe) {
            System.out.println("Error parsing number.");
        }
    }
}

Talk About Assignment!