🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Week 2 Variables & Datatypes.pdf

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Data types and Variables The building blocks Learning objectives: By the end of this lecture you should be able to: • distinguish between the eight primitive or scalar types of Java; • declare variables; • assign values to variables; • Programs must be able to work on data such as numbers,...

Data types and Variables The building blocks Learning objectives: By the end of this lecture you should be able to: • distinguish between the eight primitive or scalar types of Java; • declare variables; • assign values to variables; • Programs must be able to work on data such as numbers, characters and Strings • These data items must be stored in computer’s memory • Stored in named storage locations called variables What is a variable? • A variable is a memory location that has been given a name (identifier) so that it can be referred to in a program. • The variable holds a value, which must be of some specified type. • The value of a variable can be changed during the execution of the program. Simple data types in Java (primitives) The types of value used within a program are referred to as data types. price of a cinema ticket : how many tickets sold : real number integer In Java there are a few simple data types that programmers can use. Often referred to as the scalar types or primitives Primitive Data types The scalar types of Java Java type byte Allows for very small integers Range of values -128 to 127 short small integers -32768 to 32767 int big integers -2147483648 to 2147483647 long very big integers -9223372036854775808 to 9223372036854775807 float real numbers +/- 1.4 * 10-45 to 3.4 * 1038 double very big real numbers +/- 4.9 * 10-324 to 1.8 * 10308 char characters Unicode character set boolean true or false not applicable Primitive Data types The scalar types of Java Java type byte Allows for very small integers size 1 byte short small integers 2 bytes int big integers 4 bytes long very big integers 8 bytes float 7 significant digits 4 bytes double 15 significant digits 8 bytes char characters 2 bytes boolean true or false 1 bit Declaring variables in Java • This is the procedure of creating named locations in the computer's memory that will contain values while a program is running • These named memory locations are called variables because their values are allowed to vary over the life of the program. To create a variable in your program you must: 1. decide which data type you wish to store in variable. 2. give the variable a name (identifier) Choosing a suitable data type • Four Java types can be used to hold integers (byte, short, int and long). • Two Java types can be use to hold real numbers (double and float). • • Integers are positive and negative whole numbers Real numbers are positive and negative whole numbers, decimal point numbers, fractions, square root etc • Once name and type decided upon, the variable is declared as follows: dataType variableName ; int age; double averageAge; Choosing a suitable data type • Most common data types used in Java are: • int • double • char • String Variable Declaration datatype variableName; int x; /*declares variable x of type int*/ int counter; /*declares variable counter of type int*/ double price; /*declares variable price of type double*/ double length; /*declares variable length of type double*/ char letter; /*declares variable letter of type char*/ • a variable declaration is a statement and must end in semi-colon; Rules for Naming Identifiers • An identifier is the name of a variable, method or class. • Java imposes the following rules for identifiers – May use letters, numerals or underscores and dollar (A-Z a-z 09 _ and $) – Must start with letter or underscore (or dollar sign) – Cannot start with a digit – Cannot use a Java keyword – No spaces allowed – Case sensitive • Good programming practice – Variable and method names should start with lowercase letter – Class names should start with an uppercase letter Java Reserved Words abstract do if package synchronized boolean break double else implements import private protected this throw byte extends instanceof public throws case catch false final int interface return short transient true char finally long static try class const float for native new strictfp super void volatile null switch while continue goto default Good Programming Practice • Use meaningful variable names – makes a program self documenting i.e. fewer comments needed • The first letter of variable name/identifier should be lowercase. • Multiple word variable names can help make a program more readable. – But avoid running separate words together e.g. totalmonthlysales – Separate the words with underscores e.g. total_monthly_sales – or begin each word after the first with a capital letter e.g. totalMonthlySales (***use this one***) Declaring a variable: an example Create a variable to keep a player’s score in a computer game. a score will always be a whole number meaningful name/identifier int score ; Semi-colon The effect of declaring a variable in Java Computer Memory score Java Instruction int score ; Declaring variables Assume that the player of a game can choose a difficulty level (A, B, or C). int score; // to hold score char level; // to hold difficulty level Declaring variables of the same type Several variables can be declared on a single line if they are all of the same type. Assume that a player has a set number of lives in the game. A variable called lives stores the number of lives left. int score, lives; // both the same type char level ; // different type The effect of declaring many variables in Java Computer Memory score lives level Java Instructions int score, lives; char level ; Declaring variables of the same type int no1, no2, no3; //declares 3 variables of type int int i, j, k, l, m; //declares 5 variables of type int double length, height; //declares 2 variables of type double char grade, initial; //declares 2 variables of type char Assign a value to a variable in Java Assignments allow values to be put into variables. Written in Java with the use of the assignment operator = (Equals sign) Simple assignments take the following form: variableName = value; score = 0; Initializing variables You may combine the assignment statement with a variable declaration to put an initial value into a variable as follows: int score = 0; Note, the following declaration will not compile in Java: int score = 2.5 ; This will not compile because 2.5 is a double value – wrong type Uninitialized Variables • It is an error to use a variable that has never had a value assigned to it: int height, width ; width = height; // ERROR—uninitialized variable height • Remedy: assign a value to the variable before you use it: int height, width ; height = 30; width = height; // OK • Or initialize the variable when you declare it: int height = 30; int width = height; // OK Putting values into character variables When assigning a value to a character variable, you must enclose the value in single quotes. for example set the initial difficulty level to A char level = 'A'; Putting values into String variables When assigning a value to a String variable, you must enclose the value in double quotes. for example Set day of the week equal to Monday String day = "Monday"; Re-assigning variables Remember: you need to declare a variable only once. You can then assign to it as many times as you like. char level = 'A'; level = 'B'; level = 'C'; Output in Java To output a message on to the screen in Java we use the println() command System.out.println("Hello world"); We call these messages strings (collections of characters). Outputting variable values on the screen The values stored in a variable can also be printed on the screen using these output commands. for example double total; : total = 120.5; : System.out.print(“cost is ”); System.out.println(total); string (must be in quotes) Variable name Outputting variable values on the screen The two print statements in the last slide can be combined into one print statement by using + The + sign in this instance is known as the concatenation operator concatenation operator double total; string : total = 120.5; : System.out.print(“cost is ”+ total); Variable name Example1 public class Example1 { public static void main(String[] args) { //declare variable to hold year int year; //assign value to year year = 2023; //display current year on screen System.out.print("The current year is " +year); } } Constants • Constants (symbolic constants) are data items whose values do not change. For example: • the maximum score in an exam (100); • the number of hours in a day (24); • the mathematical value of  (3.14159). Constants • Constants are declared like variables, but are preceded by the keyword final • They are always initialised to their fixed value final int HOURS = 24; final double PI = 3.14; Constants • It is conventional to use all upper case letters in a constant name • If the name contains two or more words, they may be joined using an underscore final int DAYS_IN_WEEK = 7; Why use Constants? 1. A constant name is much easier to remember than a value. E.g. PI 2. Once declared in a program, constants cannot be modified. Attempting to do so will result in a compilation error. (PI = 4; //will cause error) 3. Constants make code easier to update, as the value is defined in one place only. 4. Constants greatly improve the readability of code. Program Example public class WeeksInYear { public static void main(String [] args) { final int DAYS_IN_YEAR = 365; final int DAYS_IN_WEEK = 7; int weeksInYear; weeksInYear = DAYS_IN_YEAR / DAYS_IN_WEEK; System.out.print("There are "+ weeksInYear + "weeks in a year"); } }

Use Quizgecko on...
Browser
Browser