Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming First Program and Variables

Similar presentations


Presentation on theme: "Java Programming First Program and Variables"— Presentation transcript:

1 Java Programming First Program and Variables
Phil Tayco San Jose City College Slide version 1.1 February 5, 2019

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

3 Your First Program public class FirstProgramProject { 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 “FirstProgramProject” 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

4 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 FirstProgramProject 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

5 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

6 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

7 Your First Program These lines denote a “multiline comment”
/** * 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

8 Your First Program These lines are “single line comments”
// 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

9 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

10 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”

11 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>;

12 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

13 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 “lastName” 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 (“firstName”) but use of underscores is allowed (“first_name”). Either way, use the same style consistently throughout your code for better readability

14 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

15 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

16 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

17 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 Incompatible types will result in a compile error and the program will not run

18 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

19 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

20 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); }

21 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); }

22 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); }

23 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); }

24 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 Since they are both floating point numbers, the “*” operation will be to multiply the 2 numbers mathematically

25 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 “ would make “The area is 24.2”

26 Arithmetic Operators Joining multiple Strings together with “+” is called “concatenation” which is a popular operation to do with String values 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

27 Arithmetic Operators Here, the “/” operator is for handling mathematical division Applying the same process will result in 2 different values public static void main(String[] args) { int daysOld = 1000; System.out.println(daysOld / 365); System.out.println(daysOld / ); }

28 Arithmetic Operators In the first println, daysOld and 365 are both integers. Since they are both integers, an “integer division” is 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, daysOld is an int, but is a double Because the double is considered more precise than an int, the int in this operation is “upgraded” to a double ( in this case) A full floating point division is then applied resulting in a double data type value of

29 Arithmetic Operators Which 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

30 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 “TextIO”. We may not be using that in this class and instead start with the Scanner class described in section 2.4.6

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

32 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

33 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

34 User Input System.out.println(“Enter an integer:”); test = input.nextInt(); 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”

35 User Input The input variable using the Scanner functions can be used to read other types of values nextInt() is used to read integers nextDouble() is used to read floating point numbers nextLine() is used to read a String of text Note: nextLine() 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

36 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

37 Programming Exercise 1 Write a box allocation report program with the following requirements: First display a welcome message to the user The program then prompts the user to enter the number of bottles expected to be packed The program then calculates and reports how many boxes will be needed as follows: Small boxes can hold 8 bottles Large boxes can hold 20 bottles The report shows how many small boxes you’ll need for the number of bottles given and also how many large boxes The report also shows how many bottles will be left over if use small boxes or large boxes

38 Programming Exercise 1 In addition, small boxes cost $4.99 and large boxes cost $ the report should also show how much it will cost if small boxes are used and if large boxes are used For example, if the user entered 100 bottles, the report would show if you use small boxes, you will need 12 boxes, have 4 bottles left over, and cost of $59.88 The report will also show that if you use large boxes, you will need 5 boxes, have 0 left over, and cost $34.95

39 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 You are welcome to look ahead or research other ways to get and display data You are also welcome to add more dynamics to the program covered in chapter 3 (selection statements and loops)


Download ppt "Java Programming First Program and Variables"

Similar presentations


Ads by Google