1 / 130

Introduction to Variables and Values in Java

Learn about variables and values in Java programming, including how to declare variables, assign values, and use different data types. Explore primitive types and their representations, as well as naming conventions and identifiers.

Download Presentation

Introduction to Variables and Values in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Primitive Types,Strings, and Console I/O • Variables and Expressions • The Class String • Keyboard and Screen I/O • Documentation and Style Reading => Section 1.2

  2. Variables and Values • Variables are memory locations that store data such as numbers and letters. • The data stored by a variable is called its value. • The value is stored in the memory location. • A variables value can be changed.

  3. Variables and Values public class EggBasket { publicstaticvoid main (String[] args) { int numberOfBaskets, eggsPerBasket, totalEggs; numberOfBaskets = 10; eggsPerBasket = 6; totalEggs = numberOfBaskets * eggsPerBasket; System.out.println ("If you have"); System.out.println (eggsPerBasket + " eggs per basket and"); System.out.println (numberOfBaskets + " baskets, then"); System.out.println ("the total number of eggs is " + totalEggs); } } Output: If you have 6 eggs per basket and 10 baskets, then the total number of eggs is 60

  4. Variables and Values • Variables: numberOfBaskets eggsPerBasket totalEggs • Assigning values: numberOfBaskets = 10; eggsPerBasket = 6; totalEggs = numberOfBaskets * eggsPerBasket; • A variable must be declared before it is used. • When you declare a variable, you provide its name and type. int numberOfBaskets, eggsPerBasket, totalEggs; • A variable’s type determines what kinds of values it can hold, e.g., integers, real numbers, characters.

  5. Syntax and Examples • Variable declaration syntax: type variable_1, variable_2, …; • Examples: int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual; • A variable is declared just before it is used or at the beginning of a “block” enclosed in { }: public static void main(String[] args) { /* declare variables here */ : }

  6. Types in Java • In most programming languages, a type implies several things: • A set of values • A (hardware) representation for those values • A set of operations on those values • Example - type int: • Values – integers in the range -2147483648 to 2147483647 • Representation – 4 bytes, binary, “two’s complement” • Operations – addition (+), subtraction (-), multiplication (*), division (/), etc. • Two kinds of types: • Primitive types • Class types

  7. Types in Java • A primitive type: • values are “simple,” non-decomposable values such as an individual number or individual character • int, double,char • A class type: • values are “complex”objects • a class of objects has both data and methods • “Think WHIRLED peas.”is a value of class type String • ‘November 10, 1989’is a value of class type date (non-Java)

  8. Java Identifiers • An identifier: • a name given to something in a program • name of a variable, name of a method, name of a class, etc. • created by the programmer, generally • Identifiers may contain only: • letters • digits (0 through 9) • the underscore character (_) • and the dollar sign symbol ($) which has a special meaning • the first character cannot be a digit. • Identifiers may not contain any spaces, dots (.), asterisks (*), or other characters not mentioned above: 7-11 netscape.com util.* (not allowed)

  9. Java Identifiers, cont. • Java is case sensitive i.e., stuff, Stuff, and STUFF are different identifiers. • keywords or reserved words have special, predefined meanings: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while • Keywords cannot be used as identifiers • Identifiers can be arbitrarily long.

  10. Naming Conventions • Choose names that are helpful, or rather readable, such as count or speed, but not c or s. • Class types: • begin with an uppercase letter (e.g. String). • Primitive types: • begin with a lowercase letter (e.g. int). • Variables of both class and primitive types: • begin with a lowercase letters (e.g. myName, myBalance). • multiword names are “punctuated” using uppercase letters.

  11. Primitive Types • Four integer types: • byte • short • int (most common) • long • Two floating-point types: • float • double (most common) • One character type: • char • One boolean type: • boolean

  12. Primitive Types, cont.

  13. Examples of Primitive Values • Integer values: 0 -1 365 12000 • Floating-point values: 0.99 -22.8 3.14159 5.0 • Character values: `a` `A` `#` ` ` • Boolean values: true false

  14. Motivation for Primitive Types • Why are there several different integer types? • storage space • operator efficiency • More generally, why are there different types at all? • reflects how people understand different kinds of data, e.g., letter vs. numeric grades. • helps prevent programmer errors.

  15. Assignment Statements • An assignment statement is used to assign a value to a variable: int answer; answer = 42; • The “equal sign” is called the assignment operator. • In the above example, the variable named answer is assigned a value of 42, or more simply, answer is assigned 42.

  16. Assignment Statements, cont. • Assignment syntax: variable = expression ; whereexpressioncan be • a literal or constant (such as a number), • another variable, or • an expression which combines variables and literals using operators

  17. Assignment Examples • Examples: int amount; int score, numberOfCards, handicap; int eggsPerBasket; char firstInitial; : amount = 3; firstInitial = ‘W’; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; => last line looks weird in mathematics, why?

  18. Assignment Evaluation • The expression on the right-hand side of the assignment operator (=) is evaluated first. • The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

  19. Simple Screen Output • The following outputs the String literal “The count is“ followed by the current value of the variable count. System.out.println(“The count is “ + count); • “+”means concatenation if at least one argument is a string

  20. Simple Input • Sometimes data is needed and obtained from the user at run time. • Simple keyboard input requires: import java.util.*; or import java.util.Scanner; at the beginning of the file.

  21. Simple Input, cont. • A “Scanner” object must be initialized before inputting data: Scanner keyboard = new Scanner(System.in); • To input data: eggsPerBasket = keyboard.nextInt(); which reads one int value from the keyboard and assigns it to the variable eggsPerBasket.

  22. Simple Input, cont. • class EggBasket2

  23. Command-Line Arguments • Frequently input is provided to a program at the command-line. public class UseArgument { public static void main(String[] args) { System.out.print(“Hi, ”); System.out.print(args[0]); System.out.println(“. How are you?”); } } • Sample interaction: % javac UseArgument.java % java UseArgument Alice Hi, Alice. How are you? % java UseArgument Bob Hi, Bob. How are you?

  24. Command-Line Arguments • Frequently multiple values are provided at the command-line. public class Use3Arguments { public static void main(String[] args) { System.out.print(“The first word is ”); System.out.print(args[0]); System.out.print(“, the second is ”); System.out.print(args[1]); System.out.print(“, and the third is ”); System.out.println(args[2]); } } • Sample interaction: % javac Use3Arguments.java % java Use3Arguments dog cat cow The first word is dog, the second is cat, and the third is cow

  25. Command-Line Arguments • Command-line arguments can be numeric. public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]); // Notice the variable declaration int b = Integer.parseInt(args[1]); // Notice the comments…lol int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } } • Sample interaction: % javac IntOps.java % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46

  26. Literals • Values such as 2, 3.7, or ’y’ are called constants or literals. • Integer literals can be preceded by a + or - sign, but cannot contain commas. • There are two distinct properties that every integer literal has: • format – either decimal, hexadecimal or octal, and • type – either long or int • Both the format and the type of an integer literal can be determined by…looking at it!

  27. Integer Literal Formats • Decimal: • 0, 10, 37, 643, 829, etc. • first digit must NOT be zero, for any non-zero integer • Hexadecimal: • consists of the leading characters 0x or 0X followed by one or more hexadecimal digits, i.e., 0 through F (lower and upper case equivalent) • each letter may be either upper case or lower case • 0xA (decimal 10), 0x0 (decimal 0), 0xFF (decimal 255), 0xf0 (decimal 240), 0x34A2, 0Xff decimal (255), etc. • Octal: • Consists of the leading digit 0 followed by one or more octal digits, i.e., 0 through 7 • 010 (decimal 8), 023 (decimal 19), 037 (decimal 31)

  28. Integer Literal Formats • What is the format? • 0 • 2 • 0372 • 0xDadaCafe • 1996 • 0x00FF00FF • 0A3C • 0945 • 450xA

  29. Integer Literal Formats • The format used to specify an integer literal has no impact on its corresponding internal value. • All of the following println statements output the same thing: int x; x = 16; System.out.println("Value:" + x); x = 020; System.out.println("Value:" + x); x = 0x10; System.out.println("Value:" + x);

  30. Integer Literal Type • An integer literal is of type long if it is suffixed with an letter L or l; otherwise it is of type int. • note that capital L is preferred • Integer literals of type long: • 2L • 0372L • 0xDadaCafeL • 1996L • 0x00FF00FFL • 0l • 0777L • 0x100000000l • 2147483648L • 0xC0B0L

  31. Integer Literal Type • See the program: • http://www.cs.fit.edu/~pbernhar/teaching/cse1001/literals

  32. Floating Point Literals • Just like with integer literals… • Floating point literals can also be preceded by a + or - sign, but cannot contain commas. • There are two distinct properties that every floating point literal has: • format – either fully expanded notation or scientific notation • type – either float or double • Both the format and the type of a floating point literal can be determined by…looking at it!

  33. Floating Point Literal Formats • Floating-point constants can be written: • with digits after a decimal point, as in 3.5 or • using scientific notation • Examples: • 865000000.0 can be written as 8.65e8 • 0.000483 can be written as 4.83e-4 • The number in front of the “e” does not need to contain a decimal point, e.g. 4e-4

  34. Floating Point Literal Type • An floating point literal is of type float if it is suffixed with an letter F or f; otherwise it is of type double. • Floating point literals of type float: • 2.5F • 0.0f • 8.65e8f • 4e-4F • 3f • +35.4f • -16F

  35. Assignment Compatibilities • Java is said to be strongly typed, which means that there are limitations on mixing variables and values in expressions and assignments. int x = 0; long y = 0; float z = 0.0f; x = y; // illegal x = z; // illegal y = z; // illegal z = 3.6; // illegal (3.6 is of type double) y = 25; // legal, but interesting…

  36. Assignment Compatibilities • Sometimes automatic conversions between types do take place: short s; int x; s = 83; x = s; double doubleVariable; int intVariable; intVariable = 7; doubleVariable = intVariable;

  37. Assignment Compatibilities, cont. • A value of one numeric type can be assigned to a variable of any type further to the right, as follows: byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. • Makes sense intuitively because, for example, any legal byte value is a legal short value. • On the other hand, many legal short values are not legal byte values.

  38. Assignment Compatibilities, cont. • Example – all of the following are legal, and will compile: byte b; short s; int i; long l; float f; double d; b = 10; s = b; i = b; l = i; f = l; // This one is interesting, why? d = f;

  39. Assignment Compatibilities, cont. • Example – NONE (except the first) of the following will compile: byte b; short s; int i; long l; float f; double d; d = 1.0; f = d; l = f; i = l; s = i; b = s;

  40. Type Casting • A type cast createsavalue in a new type from an original type. • A type cast can be used to force an assignment when otherwise it would be illegal (thereby over-riding the compiler, in a sense). • Example: double distance; distance = 9.0; int points; points = (int)distance; • The above would be illegal without (int).

  41. Type Casting, cont. • The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0. • The type of distance does NOT change and remains double. • What happens if distance contains 9.7? • Any nonzero value to the right of the decimal point is truncated (as oppossed to rounded). • Remember the rule – “cast with care,” because the results can be unpredictable.

  42. Characters as Integers • Like everything else, each character is represented by a binary sequence. • The binary sequence corresponding to a character is a positive integer. • Which integer corresponds to each character is dictated by a standardized character encoding. • each character is assigned a unique integer code • the codes are different for upper and lower case letters, e.g., 97 may be the integer value for ‘a’ and 65 for ‘A’ • some characters are printable, others are not • Why should different computers use the same code? • ASCII and Unicode are common character codes

  43. Unicode Character Set • Most programming languages use the ASCII character encoding. • American Standard Code for Information Interchange (ASCII) • (only) encodes characters from the north American keyboard • uses one byte of storage • Java uses the Unicode character encoding which includes ASCII. • The Unicode character set: • uses two bytes of storage • includes characters from many different alphabets other than English (in contrast to ASCII) • codes characters from the North American keyboard the same way that ASCII does

  44. ASCII/Unicode

  45. Assigning a char to an int • A value of type char can be assigned to a variable of type int to obtain its Unicode value. • Example: char answer = ’y’; System.out.println(answer); System.out.println((int)answer); >y>121 • See the program at: http://www.cs.fit.edu/~pbernhar/teaching/cse1001/charTest

  46. Initializing Variables • A variable that has been declared, but not yet given a value is said to be uninitialized. int x, y, z; x = y; x = z + 1; • Some languages automatically initialize a variable when it’s declared, other languages don’t. • Others (Java) initialize in some circumstances, but not in others. • Variables declared to be of a primitive type are NOT automatically initialized. • In other cases Java will initialize variables; this will be discussed later.

  47. Initializing Variables • Some languages report an error when a variable is used prior to initialization by the program. • Sometimes at compile time, other times at run-time. • Some languages won’t report an error, and will even let you use an uninitialized variable. • In such cases the initial value of the variable is arbitrary! • The program might appear to run correctly sometimes, but give errors on others. • Java: • The compiler will (try) to catch uninitialized variables. => Always make sure your variables are initialized prior to use!

  48. Initializing Variables, cont. • In Java, a variable can be assigned an initial value in it’s declaration. • Examples: int count = 0; char grade = ’A’; // default is an A • Syntax: type variable1 = expression1, variable2 = expression2, …;

  49. Arithmetic Operations • Arithmetic expressions: • are formed using the +, -, *,/ and % operators • operators have operands, which are literals, variables or sub-expressions. • Expressions with two or more operators can be viewed as a series of steps, each involving only two operands. • The result of one step produces an operand which is used in the next step. • Note that Java is left-associative. • Example: int x = 0, y = 50, z = 20; double balance = 50.25, rate = 0.05; x = x + y + z; balance = balance + (balance * rate)

  50. Expression Type • An arithmetic expression can have operands of different numeric types. • x + (y * z) / w • Note that this does not contradict our rules for assignment. • Every arithmetic expression has a (resulting) type. • Given an arithmetic expression: • If any operand in the expression is of type double, then the expression has type double. • Otherwise, if any operand in the expression is of type float, then the expression has type float. • Otherwise, if any operand in the expression is of type long, then the expression has type long. • Otherwise the expression has type int.

More Related