Summary

This document introduces fundamental concepts in Java programming, including data types, variables, and identifiers. It explores integer and real data types, character representations, along with the rules for defining identifiers, declaring variables, and assigning values. The document covers the basics of Java syntax and provides examples to illustrate the concepts, making it suitable for beginners learning the basics of Java.

Full Transcript

Okay, here's the conversion of the provided text into a structured Markdown format. I have done my best to: * Transcribe the text accurately. * Preserve important information and formatting. * Convert tables to Markdown. * Format the text using headings, lists, and other Markdown elements....

Okay, here's the conversion of the provided text into a structured Markdown format. I have done my best to: * Transcribe the text accurately. * Preserve important information and formatting. * Convert tables to Markdown. * Format the text using headings, lists, and other Markdown elements. **Getting Started With Java – Data Types & Variables** The basic unit of information on a computer is called a **bit**, which has two states: *on* or *off* (1 or 0). Bits are generally grouped into units of 8, which is called a *byte*. A single byte can store all of the possible combinations of the 8 bits, or $2^8 = 256$ values. In Java, as with most programming languages, there are various data types, which are used to represent and (as variables) store different types of data. Each data type has different demands on how much space it requires in the computer's memory, and this is measured in bytes. **Integer Data Types** We have already referred to a single byte representing 256 states of the 8 bits. Another way to look at this is to imagine each of those states representing a number. In the case of a single byte of data, Java uses the `byte` integer data type to represent the numbers from -128 to 127. | Type | Size (bits) | Size (bytes) | Range | Approximate Range | | :---- | :---------- | :----------- | :------------- | :----------------- | | byte | 8 | 1 | -2<sup>7</sup> to 2<sup>7</sup>-1 | ±100 | | short | 16 | 2 | -2<sup>15</sup> to 2<sup>15</sup>-1 | ±30000 | | int | 32 | 4 | -2<sup>31</sup> to 2<sup>31</sup>-1 | ±2 000 000 000 | | long | 64 | 8 | -2<sup>63</sup> to 2<sup>63</sup>-1 | $+9 \times 10^{18}$ | The `int` type is adequate for most tasks and will generally be your default integer data type. Integer constants must not be written with a decimal point, and they cannot contain any separators between digits. For example, each of the following is an illegal integer constant: (a) 37.0 contains a decimal point (b) -12 562 contains a blank space between digits (c) 1,233,985 contains commas between digits **Real Data Types** | Type | Size (bits) | Size (bytes) | Precision | Approximate Range | | :----- | :---------- | :----------- | :----------------------- | :----------------------- | | float | 32 | 4 | at least 6 decimal places | $\pm 3.4 \times 10^{38}$ | | double | 64 | 8 | at least 15 decimal places | $\pm 1.8 \times 10^{308}$ | Due to memory and speed considerations, the `float` data type was traditionally used more frequently. With modern computers, however, the `double` data type does not result in the same performance issues, and it should be used for most calculations involving real numbers. Each of the following is a valid floating point constant. 5. 23 .3 2818. -0.0002 6.7 Floating point constants can also be written in a form similar to that used in scientific notation. (a) 5.6e2 represents the value $5.6 \times 10^2$ = 560 (b) 37E-4 represents the value $37 \times 10^{-4}$ = 0.0037 (c) -0.667e-2 represents the value $-0.667 \times 10^{-2}$ = -0.00667 **Character Data Type** Java follows a character representation called `Unicode`, which uses 16 bits, or 2 bytes, to represent characters. This allows for 65536 possible characters, so all of the world's characters and symbols, along with specialized symbols and shapes, can be represented in Unicode. Characters in Java are of type `char`. **Identifiers** In order to create useful programs, we need the ability to store information and retrieve that information as needed. Information is stored in the memory of the computer in specially reserved areas known as variables. In order to keep track of these variables, we use identifier names (or simply *identifiers*) for each *variable*, *method*, or *class* in our program. The rules for creating any type of identifier are: 1. Any character used in an identifier must be a letter or the alphabet, a digit (0, 1, ..., 9), or an underscore character (\_). 2. The first character cannot be a digit. 3. By convention, classes are given identifiers using PascalCase, where each word begins with a capital letter. 4. By convention, *variables* and *methods* are given identifiers using camelCase, where the first letter is lowercase, and any other words in the identifier are uppercase. 5. You cannot use any of the following *reserved words*, each of which has a predefined meaning in the Java language. * abstract * assert * boolean * break * byte * case * catch * char * class * const * continue * default * double * do * 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 **Declaring Variables** To reserve space in memory for variables, we need to write a *declaration statement*, where we specify the type of a variable and its identifier (i.e., name). A simple declaration might look like ```java <type> <identifier>; ``` For example: ```java int count; float area; boolean finished; ``` Note the declaration statement, like any other statement in Java is *terminated* (i.e., ended) by the semicolon character. It is possible to declare multiple variables of the same type using a single declaration statement of the form ```java <type> <identifier1>, <identifier2>, ..., <identifierk>; ``` For example: ```java float radius, circumference, area; ``` **Exercises** 1. What is the smallest type of integer that can be represented by each of the following types? (a) 50 000 (b) -3 000 000 000 (c) -125 (d) 128 2. State, with reasons, which of the following are not legal Java integer constants. (a) -47 (b) 23. (c) -0 (d) 22 900 3. Rewrite in standard decimal form. (a) 2.94e1 (b) 0.0004e3 (c) -2e-3 (d) 26.77e-3 (e) -54E-3 (f) -.3e1 4. What is the difference between identifiers used for classes and those used for variables and methods? 5. Identify, with reasons, any identifiers that should not be used for Java variables. (a) digitSum (b) retail price (c) switch (d) heightPlusDepth (e) this&That (f) priceIn$ (g) number-of-wins (h) ageDuGarcon (i) average\_age (j) This **Assigning Values to Variables** Declaring a variable reserves space in the computer's memory for information of a particular data type (e.g., int, or float, or char). This variable does not become useful until we assign a value to it. Once variables are declared, there are many ways to give them values, the simplest of which is the *assignment statement*. There are several ways to assign a value to a variable. 1. When declaring the variable ```java int total = 15; ``` 2. Immediately after declaring the variable ```java int total; total = 15; ``` 3. After declaring the variable, but later in the program ```java int total; total = 15; ``` 4. Using the value from another variable ```java int a = 5; int b; b = a; ``` **String Variables** Java is an object-oriented language. There are eight primitive data types (byte, short, int, long, float, double, char, boolean), but an unlimited number of potential objects. One of the most useful objects, which we will use extensively, is the `String` object. We can declare a string variable and assign it a value in a manner which looks identical to the other data types. ```java String firstName; // declares a string variable called firstName firstName = "Bob"; // assigns the value “Bob” to the string firstName ``` There is a subtle yet important difference between our `String` variable and variables containing the primitive data types. The string variable *doesn't actually contain a string*. Instead, it contains a *reference* to a string object, which is stored elsewhere in memory. For example, consider the following code: ```java String firstName = "Bob"; firstName = "Doug"; ``` The string variable is declared and initialized to refer to the string “Bob”. On the next line, the string variable refers to the string “Doug”. Both the strings “Bob” and “Doug” still exist in memory, but there is no way to get back to “Bob”. **string variables** The image shows two string variables, "Doug" and "Bob". **Converting Between (Numeric) Data Types** The assigning a value to a variable, it is important that the data type match the value. For numeric data types, it is possible to convert from a smaller data type to a larger data type, but not the reverse. legal conversions: byte $\rightarrow$ short $\rightarrow$ char $\rightarrow$ int$\rightarrow$ long$\rightarrow$ float $\rightarrow$ double It is possible to force Java to accept a conversion, even if it breaks Java's own rules. This is called a *cast*, and it is essentially a promise to the compiler that you know what you are doing. It has the form: `<variable> = (<data type>) <questionable data>;` For example, ```java short a; a = (short) 75000; System.out.println(a); ``` **Output of variables** The print and println methods can be used to output variables or combinations of variables. Keep in mind that the variable must have been given a value before you try to output it, or you will get an error. ```java class printValue{ public static void main(String[] args){ int length = 5; int width = 10; System.out.print("The length is " + length); System.out.print(" and the width is" + width); } } ``` Output ``` The length is 5 and the width is 10 ``` **Constants** Java allows us to associate an identifier with a constant value through the use of the `final` modifier in the declaration of a variable. By convention, constants are given identifiers which are all upper case, which helps easily identify them when reading code. ```java final int CLASS_SIZE = 30; final char TERMINATOR = '*'; ``` Once an identifier has been declared to be final, its value can never be changed. **Exercises** 1. Draw diagrams like those shown in the lesson to illustrate the result of executing the following statements. (a) ```java int a = 1; String b = "2"; ``` (b) ```java String a = "first"; String b = "second"; ``` (c) ```java String a = "one"; String b = a; a = "two"; ``` (d) ```java String a = "ein"; String b = "zwei"; a = b; b = "drei"; ``` 1. What would be printed by the following fragment? ```java String c = "cat"; String d = "dog"; String s = c; c = d; d = s; System.out.println ("c is" + c); System.out.println ("d is" + d); ``` 2. A code fragment is a small section of code taken from inside a program. If you wish to test a code fragment, you need to make sure it is part of a complete program. What would be printed by each code fragment? Try to do this in your head or on paper first, and then check your answer with a classmate and/or as part of a Java program. (a) ```java int i = -47; int j = 45; System.out.println ("The value of i is" + i + "\nwhile The value of j is" + j + "."); ``` (b) boolean done = false; ```java System.out.println ("We are not" + done + "Vet."); ``` (c) ```java double x = 0.012; double y = 2.7374e1 ; System.out.println ("x -> " + x + "\ny -> " + y); ``` 1. What would be printed by the following code fragment (you will need to put the program framework around this code fragment to run it)? (a) ```java final double Pl = 3.1415; double diameter = 10; double radius, area; radius = diameter / 2; area = Pl * radius * radius ; System.out.print ("A circle of radius " + radius); System.out.println (" has an area of " + area); ``` I hope this is helpful! Let me know if you have any other questions.

Use Quizgecko on...
Browser
Browser