Java Programming First Program and Variables Phil Tayco

Java Programming First Program and Variables Phil Tayco San Jose City College Slide version 1. 2 February 4, 2020

Your First Program /** * This program says Hello World on the screen */ public class First. Program. Project { public static void main(String[] args) { System. out. println("Hello World!"); // println is the function that handles // printing text on the screen } }

Your First Program public class First. Program. Project { • At this stage, think of a class as a module or file that contains your code – the actual definition of a class will be presented later • “First. Program. Project” is the name of the class – Classes should be named starting with a capital letter – Multiple words in the class name each start with a capital letter with no spaces between the words (“camelback” notation) • The “{“ represents the beginning of a body of code – All “{“ must have a corresponding “}” to represent the end of the body of code – Good practice is to always make sure the curly braces are present before continuing
![Your First Program public static void main(String[] args) { • There is a lot Your First Program public static void main(String[] args) { • There is a lot](http://slidetodoc.com/presentation_image_h2/1eba8ca65a015e99d5fba0406c7c74ca/image-4.jpg)
Your First Program public static void main(String[] args) { • There is a lot of code here that will also be defined later • The “main” represents the starting point of a program when executed • main is contained within the First. Program. Project class and is visually indicated by the indentation – Indentation is not absolutely required in Java but it is an important programming practice to follow • The beginning of the content for main is illustrated with its own “{“ – the closing “}” later represents the end of the main program

Your First Program System. out. println("Hello World!"); • “System. out. println” is the function that performs printing text on the screen • The “. ” notation can be viewed as drilling down into a specific component within a collection of elements – “System” is a package or library of different modules – “out” is a module (class) that is within the System package – “println” is a function that is within the “out” class

Your First Program • A function contains instructions that are executed to perform a specific action (when designed correctly) • Functions are designated with the use of parentheses that indicate information provided as part of what it will use to perform its actions • Here, we are sending in the text “Hello World!” – The text is denoted using double quotation marks – The characters within the quotes is referred to as a “String” of text and is often interpreted literally • Best way to read that code is that println is receiving the String “Hello World!” and will print it on the screen

Your First Program /** * This program says Hello World on the screen */ • These lines denote a “multiline comment” • Comments are text that is ignored by the Java compiler – they are there to help describe information to the human reader • Multiline comments start with “/*” and end with “*/” – everything in between is subsequently ignored by the compiler • Comments are useful for describing your code • There are guidelines for style and comment usage – overall, it is a good practice to follow

Your First Program // println is the function that handles // printing text on the screen • These lines are “single line comments” • They begin with “//” – text on the rest of the line is ignored by the compiler • Text on the next line is back to normal for the compiler • These 2 single line comments could have been done using multiline comments – it is a matter of style and preference for the programmer • Single line is often useful for addressing a specific line of code – multiline to describe a code section

Your First Program } } • These closing curly braces correspond to closing the main function and class module respectively • Note the closing curly braces line up with the appropriate open curly brace • Closing braces are necessary for code – lining them up is very useful to follow for style and helps with debugging • At this point, it is good to ensure your installation of Java and editor can run this program – hello world is traditionally a good first exercise to make sure you can compile and run a program

Variables and Data Types • With your first program out of the way, we can start paving the way for more useful and dynamic programs • At a very high level, a program is simply a set of instructions that manage areas in memory that contains specific values • Code acts in a specific way depending on those memory values • We call those areas in memory that store such a values as “variables”

Variables and Data Types • Variables in memory are like storage boxes with 2 essential properties • All variables have a label referred to as a “variable name” • All variables are designed to store a specific kind of information referred to as a “data type” • When creating a variable, the Java syntax is: <data type> <variable name>;

Variables and Data Types • There are simple data types already known by the Java compiler such as an integer, floating point number and a string of text • Variable names are labels that have rules that must be followed in Java – Rule 1: All variable names are unique – if you have multiple variables in your program, they cannot have the exact same name – Rule 2: All variables start with a letter or “_” (underscore) – they cannot start with a special character or number

Variables and Data Types • Variable names also have guidelines that should be followed in Java, but not absolutely required – Guideline 1: Use descriptive names that apply to the intent of the variable. “age” and “last. Name” tell the reader exactly what those variables intend to store. “x” and “a”, not so much – Guideline 2: Use a consistent label style. Java programmers use “camelback” notation (“first. Name”) but use of underscores is allowed (“first_name”). Either way, use the same style consistently throughout your code for better readability

Variables and Data Types • Data types define the kind and range of information that will be stored by the variable – “int” is a range of whole numbers from -2, 147, 483, 648 to 2, 147, 483, 647 – “double” is a large range of floating point numbers – “boolean” is a value of “true” or “false” – “char” is a single literal character enclosed in single quotation marks such as ‘x’, ‘&’, or ‘ 3’ – “String” is a sequence of characters enclosed in double quotation marks such as “Hello world!” • Online Java references are available to precisely describe data type definitions • Practicing use of them is a fundamental skill of programming

Variables and Data Types int age; • This line of code is a “variable declaration” • We are reserving a place in memory with a label “age” that will store integers • Note the “; ” at the end of the line. This means “end of statement” and is necessary to complete every statement of code • At this point in the body of code you are in, age is treated as the place where integers can be stored • Any attempt at another declaration of age is not allowed

Expressions • Once you have variables defined, you can store and manipulate values for them in many ways • The fundamental expression to store values is the assignment operator, “=“ age = 21; • This assigns the value of 21 to the variable age

Expressions • More important is the process of the expression • When Java sees the “=“ operator, it does a type comparison • Java checks the data types on both sides of the operator and they must look alike • In this example, 21 on the right side is an integer and age on the left side was declared as an integer. The types match so the line of code is syntactically correct

Compatibility • Incompatible types will result in a compile error and the program will not run int age = “ 21”; • This results in an immediate compiler error because we are trying to assign a String into an int • Some assignments will work, though, as long as there is no loss in precision

Compatibility double age = 21; • This actually stores the value 21. 0 into age because Java can convert the integer 21 into a double without a loss of precision • The other way does not work: int age = 21. 5; • For an assignment, Java will not convert the 21. 5 to a 21 or a 22 automatically – we have to force it with code called “casting”

Compatibility int age = (int) 21. 5; • This code is casting (or converting) the double 21. 5 into an integer version • For Java, casting a double to an int means “truncating” the decimal part (i. e. the. 5 is chopped off) • The value of age in this case will end up as 21 • Casting and dealing with type compatibility with assignments gets better with experience as you recognize situations more and more • The strict typing rules actually help you from making unexpected imprecision mistakes when the program is running • Knowing the compatibility an conversion rules with each type will help learning these over time

Displaying variable values System. out. println(“age”); • In this line of code, we are printing “age” on the screen. The double quotation marks indicate that the value to be printed a literal String System. out. println(age); • In this line of code, we are printing the value that is in the age variable. This can only be done if the age variable has already been declared (and should have a value assigned to it at this point) • If age has not been declared, you will get an “unrecognized symbol” compile error

Displaying variable values • Important to note is that all variable names are case sensitive: System. out. println(Age); • This line of code will result in an “unrecognized symbol” compile error • Even if we declared “int age; ” earlier, “Age” and “age” are treated as 2 separate and unique variables • A good programming practice is to use case consistently in your code for variable names • Java notation guideline says to start all variable names with a lower case letter

Arithmetic Operators • Declaring variables and storing values is a foundation of programming in any language, but not much is useful in the program until you start using and manipulating that information to make logical decisions public static void main(String[] args) { double length = 5. 1; double width = 2. 4; double area = length * width; System. out. println(“The area is “ + area); }

Arithmetic Operators • In this program, we first create 2 variables of type double and assign values to them at the same time • Declaring and assigning at the same time is a common practice called “initialization” public static void main(String[] args) { double length = 5. 1; double width = 2. 4; double area = length * width; System. out. println(“The area is “ + area); }

Arithmetic Operators • The variable “area” is initialized with an arithmetic expression • Here, the values in length and width are retrieved and multiplied together because of the “*” operator • The result of the operation is then assigned to the area variable public static void main(String[] args) { double length = 5. 1; double width = 2. 4; double area = length * width; System. out. println(“The area is “ + area); }

Arithmetic Operators • This example shows 2 arithmetic operators in action • Like the assignment operator, the process of evaluating the expression is important • In “length * width”, the same process of identifying data types is applied for 2 reasons: – Confirm compatibility between types – Determine the kind of evaluation to perform • Here, length and width are both doubles so they are compatible, and the “*” operation will be to multiply the 2 numbers mathematically • Many of the same compatibility and casting rules with assignments apply with arithmetic operators, but there are special cases too

Arithmetic Operators • The println uses a combination of a String and attaches at the end of it the value that’s in area • The operator used here is “+” and is adding 2 values to each other based on the data types used public static void main(String[] args) { double length = 5. 1; double width = 2. 4; double area = length * width; System. out. println(“The area is “ + area); }

Arithmetic Operators • In the second expression in the println, the same evaluation process on the “+” is applied • Here, the type on the left is a String but the type on the right is an integer • This usually would result in an incompatible types compile error, but the “+” operation with Strings has special meaning in Java • When “+” occurs both sides are Strings, the two literal character sequences are joined to make one String – “Hello “ + “World” would make “Hello World” • If one side is a String but the other is not, the other is automatically converted to a String first – “The area is “ + 24. 2 would make “The area is 24. 2”

Arithmetic Operators • The automatic conversion from int to String occurs because it is applied using the “+” • Joining multiple Strings together with “+” is called “concatenation” which is a popular operation to do with String values • As long as at least one part of the concatenation is a String, the other parts are converted to String types by Java if necessary • As a rule, when reviewing and writing code, anytime an arithmetic operator is used, go through the data type evaluation process • This helps anticipate any type compatibility issues and also understand how your code will exactly perform the operation coded

Arithmetic Operators • Which arithmetic operation you wish to apply will depend on the context of your program • This makes it important to not only know the arithmetic operators, but what they do when certain data types are encountered • There are 5 arithmetic operators in Java: – – – + (addition for numbers, concatenation for Strings) - (subtraction) * (multiplication) / (division, integer or floating point) % (modulus, integer division returning the resulting remainder) • Practice: Write code with different variable types and values on these operators to see the results

Division Operators • The “/” operator is for handling mathematical division • Depending on the data types, though, the same formula could result in 2 different values public static void main(String[] args) { int days. Old = 1000; System. out. println(days. Old / 365); System. out. println(days. Old / 365. 25); }

Division Operators • In the first println, days. Old and 365 are both integers. Since they are both integers, an “integer division” is first applied • Integer divisions perform a normal divide followed by the remainder removed (“truncated”) resulting in a simple integer value of 2 • In the second println, days. Old is an int, but 365. 25 is a double • Because the double is considered more precise than an int, the int in this operation is converted to a double (1000. 00 in this case) • A full floating point division is then applied resulting in a double data type value of 2. 737850787132101

Division Operators • This gets especially tricky when assigning the results to variables: double result = days. Old / 365; System. out. println(result 1); • At first, this looks like you are dividing 2 numbers and storing a floating point result into a double • However, the days. Old variable is an int and the 365 is also an int, so when the “/” operation occurs, it performs an integer division • This will result into a truncated value of just 2. That integer is then stored into result as a double!

Division Operators • The modulus operator isn’t quite as common in everyday math by humans, but it plays a valuable role in some situations in programs • Typically used with integers, mod performs an integer division but instead of storing the truncated quotient, it stores the remainder int rem = 23 % 5; • 23 divided by 5 is 4 with a remainder of 3 – the 3 is what gets stored into rem • This operation is often used with generating a specific range of random numbers or situations involving determining “leftover” amounts of data

User Input • Assigning values in the code to variables is called “hard coding values” • Hard coding values is useful for initializations and also for testing purposes but limits flexibility • Programs often pull data from other sources such as a database, file or user input • Basic user input allows for more dynamic program execution and results • Java provides packages that handle user input which we can reuse • Note: the text has examples of a custom package he calls “Text. IO”. We will not be using that in this class and instead start with the Scanner class described in section 2. 4. 6

User Input import java. util. Scanner; public class Input. Example { public static void main(String[] args) { Scanner input = new Scanner(System. in); int test = 0; System. out. println(“Enter an integer: ”); test = input. next. Int(); System. out. println(“You entered “ + test); } }

User Input import java. util. Scanner; • This line of code instructs the compiler to bring in the code precompiled and defined in a class called “Scanner” • Scanner is in a library package called “java. util” which is included when you install Java • All imports must appear before “public class…” declaration • If you have a project that creates a “package…” declaration at the top of the code, the import must appear after that

User Input Scanner input = new Scanner(System. in); • This line of code looks like another variable declaration and initialization, and it is! • There is much going on here which will be precisely defined later • For now, consider this line as creating a variable called “input” which will contain all the functionality to handle input from the console • “input” will contain functions that we will use to do things such as read integers, doubles and text

User Input System. out. println(“Enter an integer: ”); test = input. next. Int(); • The first line starts with a prompt to the user to enter a number – it is good practice to do simple prompts flow control of your program • The second line is using the input to wait for the user to enter an integer • When that occurs, the number is assigned to the variable test • Issues can happen here such as with the user entering “ten” – this will result in an error that crashes the program (because the String “ten” cannot be assigned to the int test variable) • Such issues are called “run-time errors”

User Input • The input variable using the Scanner functions can be used to read other types of values – next. Int() is used to read integers – next. Double() is used to read floating point numbers – next. Line() is used to read a String of text • Note: next. Line() can lead to errors. We will discuss these later so for now, we will avoid using it (though you are welcome to experiment!) • You may wonder how we can avoid run time errors, that will also be a concept we go over in this class • For now, keep it simple and assume valid user input for ints and doubles

Summary • In this module, you learned to print information, create variables, manipulate them and do simple user input • The combination of all this information is enough to write simple Java programs • This material is addressed in parts of Chapter 2 of the text • The next module will detail more on of Chapter 2 • We address sections 2. 1, 2. 2, 2. 4. 6, and 2. 5 in this and the next module • Section 2. 3 we will come back to from time to time and 2. 4 (except 2. 4. 6) will not be reviewed • Section 2. 6 is optional with more information about different Java development environments

Programming Exercise 1 • Write a box allocation program with the following requirements: • A box can hold 20 bottles. Each box costs $2. 99 • We want to ask the user how many bottles they want to box up • From that number, the program will calculate how many full boxes will be needed and how much that will cost • The program will also calculate how many bottles will be leftover and unboxed

Programming Exercise 1 • The sequence of the program should be as follows: • First display a welcome message to the user • Prompts the user to enter the number of bottles expected to be packed • Perform the necessary calculations and then display the results • Example: If the user enters 70 bottles, that should be 3 full boxes totaling $8. 97 with 10 bottles leftover unboxed

Programming Exercise 1 • Use variables, data types and println statements as appropriate to meet the requirements of the program • Use good clean output for on the screen but do not worry about displaying the total cost with only 2 decimal places (we’ll discuss formatting output later) • Do not worry about unexpected user input such as “seventy” or 15. 3 bottles. You can assume the user will properly enter an integer value
- Slides: 44