Chapter 2

Elementary Programming

Github Code

Blog

Intellij

Motivations

  • In the preceding chapter, you learned how to create, compile, and run a Java program.
  • You will learn how to solve practical problems programmatically.
  • You will learn Java primitive data types and related subjects, such as variables, constants, data types, operators, expressions, and input and output.

Introducing Programming with an Example

  • Computing the Area of a Circle
  • Area = πr²
Area = πr²

                        

Reading Input from the Console

  • Create a Scanner object
  • 
                                Scanner input = new Scanner(System.in);
    
                            
  • Use the method nextDouble() to obtain to a double value. For example,
  • 
                                System.out.print("Enter a double value: ");
                                Scanner input = new Scanner(System.in);
                                double d = input.nextDouble();
                                
                                
    
                            
Reading input from the console Area = πr²

                        

Implicit Import and Explicit Import


                        java.util.* ; // Implicit import
                        java.util.Scanner; // Explicit Import

                    
  • No performance difference

Identifiers

  • An identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).
  • An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.
  • An identifier cannot be a reserved word.
  • An identifier cannot be true, false, null, int or boolean .
  • An identifier can be of any length
  • Names are case sensitive ("myVar" and "myvar" are different variables)

                        //valid
                        _myvariable
                        _5variablename
                        $test_variable
                        TestVariable
                        //invalid
                        int
                        boolean
                        null
                    

Variable

  • A variable provides us with named storage that our programs can manipulate
  • Data Storage and Strongly Typed
  • Style camel case int myData
  • Start each word after the first with upper case e.g studentNumber, bankAccountNumber

                        data type variable name = value;

                    

                        int a, b, c;         // Declares three ints, a, b, and c.
                        int a = 10, b = 10;  // Example of initialization
                        byte B = 22;         // initializes a byte type variable B.
                        double pi = 3.14159; // declares and assigns a value of PI.
                        char a = 'a';        // the char variable a iis initialized with value 'a'
                    

Variables


                        // Compute the first area
                        double  radius = 1.0;
                        double  area = radius * radius * 3.14159;
                        System.out.println("The area is “ + area + " for radius "+radius);

                    

Primitive Data Types

  • The Java programming language is statically-typed, which means that all variables must first be declared before they can be used.
  • Primitive values do not share state with other primitive values.
  • Primitive type is predefined by the language and is named by a reserved keyword.
  • The eight primitive data types supported by the Java programming language are
  • byte, short int ,long, float,double,boolean ,char
  • Primitive Data Types are stored by value

Stored by Value


                  int firstValue=10;
                  int secondValue=firstValue;
                  System.out.println(secondValue); 
                

                       

Declaring Variables


                       int x;         // Declare x to be an integer variable;
                       double radius; // Declare radius to be a double variable;
                       char a;        // Declare a to be a character variable;
         
                    

Assignment Statements


                        x = 1;          // Assign 1 to x;
                        radius = 1.0;   // Assign 1.0 to radius;
                        a = 'A';        // Assign 'A' to a;
         
                    

Declaring and Initializing in One Step


                        int x = 1;
                        double radius = 1.o;
                        char mychar='A'; 
                    

CheckDataType

Sample code on Github CheckDataType code

                    
                    

Constants

  • Constant in Java is a value that cannot be changed once assigned
  • Constants are not supported directly in Java. Instead, an alternative way to define a constant in Java is using the final keyword.

                             final datatype identifier_name = constant;
                        

                                public class Main {
                                    public static void main(String[] args) {
                                //what is the output of this code?
                                        final int VALUE=123;
                                        VALUE=567;
                                        System.out.println(VALUE);
                                    }
                                }
                            

Naming Conventions

  • Choose meaningful and descriptive names.
    • Variables and method names.
    • Use lowercase. If the name consists of several words, concatenate all in one, use lowercase for the first word, and capitalize the first letter of each subsequent word in the name.
    • For example, the variables radius and area, and the method computeArea.

                                 double area=0.0;
                                 double radius;
                                 double computeArea;
                            

Naming Conventions, cont

  • Class names
    • Capitalize the first letter of each word in the name. For example, the class name ComputeArea.
    • 
                                                 public class ComputeArea
                                             
  • Constants
    • Capitalize all letters in constants, and use underscores to connect words. For example, the constant PI and MAX_VALUE
    • 
                                                  final double PI=3.14d;
                                                  final float MAX_VALUE=10.2f;
                                             

Numerical Data Types

Reading Numbers from the Keyboard


                    import java.util.Scanner;
                    public class Main {
                        public static void main(String[] args) {
                            Scanner input = new Scanner(System.in);
                            System.out.print ("Enter the Qty: ");
                            int qty = input.nextInt();
                            System.out.println(qty);
                        }
                    }
                       
                

Reading User Input

How do you print your full name using Scanner class?


                    import java.util.Scanner;
                    public class Main {
                        public static void main(String[] args) {
                            Scanner input = new Scanner(System.in);
                            System.out.print ("Enter your full name: ");
                            String name = input.nextLine();
                            System.out.println(name);   
                        }
                    }
                          
                   

Numeric Operators


                                        +, -, *, /, and %
                                        5 / 2 yields an integer 2.
                                        5.0 / 2 yields a double value 2.5
                                        5 % 2 yields 1 (the remainder of the division) 
                                        3-2
                                        
                                        
                                   

NOTE

  • Calculations involving floating-point numbers are approximated because these numbers are not stored with complete accuracy. For example,

                                        System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
                                         displays 0.5000000000000001, not 0.5, and 
                                        System.out.println(1.0 - 0.9);
                                        displays 0.09999999999999998, not 0.1.
                                    
  • Integers are stored precisely. Therefore, calculations with integers yield a precise integer result.
  • Exponent Operations

    
                                                System.out.println(Math.pow(2, 3)); // Displays 8.0 
                                                System.out.println(Math.pow(4, 0.5)); // Displays 2.0
                                                System.out.println(Math.pow(2.5, 2));// Displays 6.25
                                                System.out.println(Math.pow(2.5, -2)); // Displays 0.16
    
                                            

    Number Literals

    • A literal is a constant value that appears directly in the program
    • For example, 34, 1,000,000, and 5.0 are literals in the following statements:
    
                                                    int i = 34;
                                                    long x = 1000000;
                                                    double d = 5.0; 
                                                    
        
                                                

    Integer Literals

    • An integer literal can be assigned to an integer variable as long as it can fit into the variable.
    • A compilation error would occur if the literal were too large for the variable to hold.
    • For e.g
    
                                                        byte b = 1000 ; //byte can hold -128 to 127 max
            
                                                    
  • An integer literal is assumed to be of the int type, whose value is between -231 (-2147483648) to 231–1 (2147483647).
  • 
                                                        int j=2147483647+1;
                                                         System.out.println(j);
                                            
                                                    
  • Two billion plus
  • Floating-Point Literals

    • Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value.
    • For example, 5.0 is considered a double value, not a float value
    • You can make a number a float by appending the letter f or F
    • Make a number a double by appending the letter d or D
    
                                                            For example, you can use
                                                            float myFloatValue= 100.2f or 100.2F for a float number, 
                                                            double myDoubleValue= 100.2d or 100.2D for a double number. 
                                                        

    double vs float

    • The double type values are more accurate than the float type values
    
                                                                System.out.println("1.0 / 3.0 is " + 1.0 / 3.0); //16 digits
    
                                                                System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F); //8 digits
    
                                                                double myDoubleValue= 100.2d or 100.2D for a double number. 
                                                            

    Scientific Notation

    • Floating-point literals can also be specified in scientific notation,
    • E (or e) represents an exponent and it can be either in lowercase or uppercase.
    
                                                                    for example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456
                                                                    1.23456e-2 is equivalent to 0.0123456.
    
                                                                

    Arithmetic Expressions

    How to Evaluate an Expression

    • Though Java has its own way to evaluate an expression behind the scene, the result of a Java expression and its corresponding arithmetic expression are the same

    Problem: Converting Temperatures

    Augmented Assignment Operators

    Increment and Decrement Operators

    • Using increment and decrement operators makes expressions short, but it also makes them complex and difficult to read.
    • Avoid using these operators in expressions that modify multiple variables, or the same variable for multiple times such as this: int k = ++i + i.

    per/post increment code

    Github code

    Numeric Type Conversion

    
                                                                        byte i = 100;
                                                                        long k = i * 3 + 4;
                                                                        double d = i * 3.1 + k / 2;
                                                                        
                                                                        
                                                                    

    Type Casting

    
                                                                        Implicit casting
                                                                        double d = 3; (type widening)
           
                                                                    
    
                                                                        Explicit casting
                                                                        int i = (int)3.0; (type narrowing)
                                                                        int i = (int)3.9; (Fraction part is truncated)
                                                                     
    
                                                                        What is wrong?	int x = 5 / 2.0;
                                                                     

    Casting in an Augmented Expression

    • In Java, an augmented expression of the form x1 op= x2 is implemented as x1 = (T)(x1 op x2),
    • where T is the type for x1. Therefore, the following code is correct.
    
                                                                        int sum = 0;
                                                                        sum += 4.5; // sum becomes 4 after this statement
                                                                        
                                                                        sum += 4.5 is equivalent to sum = (int)(sum + 4.5). 
                                                                        
                                                                     

    Common Errors and Pitfalls

    • Undeclared/Uninitialized Variables and Unused Variables
    • Integer Overflow.
    • Round-off Errors
    • Unintended Integer Division
    • Redundant Input Objects

    Undeclared/Uninitialized Variables and Unused Variables

    
                                                                        double interestRate = 0.05;
                                                                        double interest = interestrate * 45;
                                                                    

    Integer Overflow

    
                                                                        int value = 2147483647 + 1; 
                                                                        // value will actually be -2147483648
                                                                    

    Round-off Errors

    
                                                                        System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
    
                                                                        System.out.println(1.0 - 0.9);
                                                                        
    
                                                                    

    Unintended Integer Division

    
                                public class Main {
                                    public static void main(String[] args) {
                                        int value1=1;
                                        int value2=2;
                                        double average=(value1+value2)/2;
                                        System.out.println(average);
                                    }
                                }
                                                                                
            
                                                                            
    
                                public class Main {
                                    public static void main(String[] args) {
                                        int value1=1;
                                        int value2=2;
                                        double average=(value1+value2)/2.0;
                                        System.out.println(average);
                                
                                    }
                                }
            
                            

    Redundant Input Objects

    
                                                                                Scanner input = new Scanner(System.in);
                                                                                System.out.print("Enter an integer: ");
                                                                                int v1 = input.nextInt();
                                                                                 
                                                                                Scanner input1 = new Scanner(System.in);
                                                                                System.out.print("Enter a double value: ");
                                                                                double v2 = input1.nextDouble();
                                
                                                                            

    Problem: Compute Loan

    Problem: Money Compute

    Assignments

    Thank you /Questions