Theory Session
How Java Works On Computer
When programming you will be writing source code using the syntax for the java programming language. This source code is translated into byte code by the compiler and is then stored in a .class file. The byte code is the same for each computer system.
For this byte code to execute, another program, called the Java virtual machine (JVM), translates the Java byte code into instructions understood by that computer. This extra step is necessary for one of the main advantages of Java: the same program can run in any computing environment! A computer might be running Windows, MacOS, Solaris, Unix, or Linux-each computer system has its own Java virtual machine program. Having a particular Java virtual machine for each computer system also allows the same Java .class file to be transported around the internet. The following figure shows the levels of translation needed in order to get executable programs to run on most computers.
Elements of Java Programming
The essential building block of Java programs is the class. In essence, a Java class is a sequence of characters (text) stored as a file, whose name always ends with .java. Each class is comprised of several elements, such a class heading (public
class class-name) and methods—a collection of statements grouped together to provide a service. Below is the general form for a Java class that has one method: main. Any class with a main method, including those with only a main method, can be run as a program.
A simple Java program (only one class)
|
General forms describe the syntax necessary to write code that compiles. The general forms in this textbook use the following conventions:
Boldface elements must be written exactly as shown. This includes words such as public static void main and symbols such as [, ], (, and ).
- Italicized items are defined somewhere else or must be supplied by the programmer.
|
Out Put
Enter an integer: -12
-12 squared = 144
The first line in the program shown above is a comment indicating what the program will do.
Comments in Java are always preceded by the // symbol, and are "ignored" by the program. The next line contains the word import, which allows a program to use classes stored in other files. This program above has access to a class named Scanner for reading user input. If you omit the import statement, you will get this error:
Scanner keyboard = new Scanner(System.in);
Scanner cannot be resolved to a type
Java classes are organized into over seventy packages. Each package contains a set of related classes. For example, java.net has classes related to networking, and java.io has a
collection of classes for performing input and output. To use these classes, you could either use
the import statement or simply precede the class name with the correct package name, like this:
java.util.Scanner keyboard = new java.util.Scanner(System.in);
The next line in the sample program is a class heading. A class is a collection of methods and
variables (both discussed later) enclosed within a set of matching curly braces. You may use any valid class name after public class; however, the class name must match the file name.
Therefore, the preceding program must be stored in a file named ReadItAndSquareIt.java.
The file-naming convention
class-name.java
The next line in the program is a method heading that, for now, is best retyped exactly as shown:
public static void main(String[] args) // Method heading
The opening curly brace begins the body of the main method, which is a collection of executable statements and variables. This main method body above contains a variable declaration, variable initializations, and four messages, all of which are described later in this chapter. When run as a program, the first statement in main will be the first statement executed. The boy of the method ends with a closing curly brace. This Java source code represents input to the Java compiler. A compiler is a program that translates source code into a language that is closer to what the computer hardware understands. Along the way, the compiler generates error messages if it detects a violation of any Java syntax rules in your source code. Unless you are perfect, you will see the compiler generate errors as the program scans your source code.
Tokens — The Smallest Pieces of a Program
As the Java compiler reads the source code, it identifies individual tokens, which are the smallest recognizable components of a program. Tokens fall into four categories:
Token | Examples |
Special symbols | ; () , . { } |
Identifiers | main args credits courseGrade String List |
Reserved identifiers | public static void class double int |
Literals (constant values) | "Hello World!" 0 -2.1 'C' true |
Tokens make up more complex pieces of a program. Knowing the types of tokens in Java should help you to:
- More easily write syntactically correct code.
- Better understand how to fix syntax errors detected by the compiler.
- Understand general forms.
- Compete programs more quickly and easily.
A special symbol is a sequence of one or two characters, with one or possibly many specific
meanings. Some special symbols separate other tokens, for example: {, ;, and ,. Other special
symbols represent operators in expressions, such as: +, -, and /. Here is a partial list of singlecharacter
and double-character special symbols frequently seen in Java programs:
() . + - / * =< >= // { } == ;
Identifiers
Java identifiers are words that represent a variety of things. String, for example is the name of a class for storing a string of characters. Here are some other identifiers that Java has already given meaning to:
sqrt String get println readLine System equals Double
Programmers must often create their own identifiers. For example, test1, finalExam, main,
and courseGrade are identifiers defined by programmers. All identifiers must follow these
rules:
- Identifiers begin with upper- or lowercase letters a through z (or A through Z), the dollar sign $, or the underscore character _.
- The first character may be followed by a number of upper- and lowercase letters, digits (0 through 9), dollar signs, and underscore characters.
- Identifiers are case sensitive; Ident, ident, and iDENT are three different identifiers.
main Vector incomeTax MAX_SIZE $Money$
Maine URL employeeName all_4_one _balance
miSpel String A1 world_in_motion balance
Invalid Identifiers
1A // Begins with a digit
miles/Hour // The / is not allowed
first Name // The blank space not allowed
pre-shrunk // The operator - means subtraction
double // This is reserved
Java is case sensitive. For example, to run a class as a program, you must have the identifier
main. MAIN or Main won't do. The convention employed by Java programmers is to use the
"camelBack" style for variables. The first letter is always lowercase, and each subsequent new
word begins with an uppercase letter. For example, you will see letterGrade rather than
lettergrade, LetterGrade, or letter_grade. Class names use the same convention, except
the first letter is also in uppercase. You will see String rather than string.
Reserved Identifiers
Reserved identifiers in Java are identifiers that have been set aside for a specific purpose. Their
meanings are fixed by the standard language definition, such as double and int. They follow the
same rules as regular identifiers, but they cannot be used for any other purpose. Here is a partial list
of Java reserved identifiers, which are also known as keywords.
Java Keywords
boolean default for new
break do if private
case double import public
catch else instanceOf return
char extends int void
class float long while
The case sensitivity of Java applies to keywords. For example, there is a difference between
double (a keyword) and Double (an identifier, not a keyword). All Java keywords are written in
lowercase letters.
Literals
A literal value such as 123 or -94.02 is one that cannot be changed. Java recognizes these
numeric literals and several others, including String literals that have zero or more characters
enclosed within a pair of double quotation marks.
"Double quotes are used to delimit String literals."
"Hello, World!"
Integer literals are written as numbers without decimal points. Floating-point literals are written
as numbers with decimal points (or in exponential notation: 5e3 = 5 * 103 = 5000.0 and 1.23e-4
= 1.23 x 10-4 = 0.0001234). Here are a few examples of integer, floating-point, string, and char5
acter literals in Java, along with both Boolean literals (true and false) and the null literal value.
The Six Types of Java Literals
Integer | Floating Point | String | Character | Boolean | Null |
-2147483648 | -1.0 | "A" | 'a' | true | null |
-1 | 0.0 | "Hello World" | '0' | false | |
0 | 39.95 | "\n new line" | '?' | ||
1 | 1.234e02 | "1.23" | ' ' | ||
2147483647 | -1e6 | "The answer is: " | '7' |
Note: Other literals are possible such as 12345678901L for integers > 2,147,483,647.
Comments
Comments are portions of text that annotate a program, and fulfill any or all of the following
expectations:
- Provide internal documentation to help one programmer read and understand another's program.
- Explain the purpose of a method.
- Describe what a method expects of the input arguments (n must be > 0, for example).
Describe a wide variety of program elements.
special symbol /* when closed with the corresponding symbol */.
/*
A comment may
extend over
many lines
*/
An alternate form for comments is to use // before a line of text. Such a comment may appear
at the beginning of a line, in which case the entire line is "ignored" by the program, or at the
end of a line, in which case all code prior to the special symbol will be executed.
// This complete Java program runs, but does nothing
public class DoNothing {
public static void main(String[] args) { // A method heading
// This program does nothing
}
}
Comments can help clarify and document the purpose of code. Using intention-revealing
identifiers and writing code that is easy to understand, however, can also do this.
Java has a third style of comments, known as javadoc comments. These begin with /** (note
the second asterisk) and end with */ , and contain documentation and special tags that show up in Web pages (when you run the javadoc program).
/** Debit this account by withdrawalAmount if it is no greater than this
* account's current balance. withdrawalAmount must be greater than 0.
* @param withdrawalAmount The requested amount of money to withdraw.
* @return true if 0 < withdrawalAmount <= the balance.
*/
public boolean withdraw(double withdrawalAmount)
Primitive Types
Java has two types of variables: primitive types and reference types. Reference variables store
information necessary to locate complex values such as strings and arrays. On the other hand,
Primitive variables store a single value in a fixed amount of computer memory. The eight
"primitive" (simple) types are closely related to computer hardware. For example, an int value
is stored in 32 bits (4 bytes) of memory. Those 32 bits represent a simple positive or negative
integer value. Here is summary of all data types in Java along with the range of value for the
primitive types:
Java's Data Types
Primitive Types Reference Types
integers: arrays (Later)
Name | Width | Range |
byte | (8 bits) | -128 .. 127 |
short | (16 bits) | -32,768 .. 32,767 |
int | (32 bits) | -2,147,483,648 .. 2,147,483,647 |
long | (64 bits) | -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807 |
Name | Width | Range |
float | (32 bits) | 1.40129846432481707e-45 .. ±3.40282346638528860e+38 |
double | (64 bits) | ±4.94065645841246544e-324 .. ±1.79769313486231570e+308 |
others: interfaces (Later)
Name | Width | Range |
char | (16 bits) | 0-65536 |
boolean | false .. true |
Declaring a primitive variable provides the program with a named data value that can change
while the program is running. An initialization allows the programmer to set the original value of
a variable. This value can be accessed or changed later in the program by using the variable
name.
General Form: Initializing (declaring a primitive variable and giving it a value you want)
type identifier; // Declare one variable
type identifier = initial-value; // For primitive types like int and double
Example: The following code declares one int and two double primitive variables while it
initializes grade.
int credits;
double grade = 4.0;
double GPA;
The following table summarizes the initial value of these variables:
Variable Name Value
credits ? // Unknown
grade 4.0 // This was initialized above
GPA ? // Unknown
If you do not initialize a variable, it cannot be used unless it is changed with an assignment
statement. The Java compiler would report this as an error.
Assignment
An assignment gives a value to a variable. The value of the expression to the right of the
assignment operator (=) replaces the value in the variable to the left of the assignment operator
(=).
General Form: Assignment
variable-name = expression;
The expression must be a value that can be stored by the type of variable to the left of the
assignment operator (=). For example, an expression that results in a floating-point value can be
stored in a double variable, and likewise an integer value can be stored in an int variable.
credits = 4;
grade = 3.0;
GPA = 0.0;
After the two assignments execute, the value of both variables is modified and the values can be shown like this:
Variable Value
credits 4
grade 3.0
GPA 0.0
In an assignment, the Java compiler will check to make sure you are assigning the correct type of value
to the variable. For example, a string literal cannot be assigned to a numeric variable. A
floating-point number cannot be stored in an int.
grade = "Noooooo, you can't do that"; // ERROR: Can't store string in a double
credits = 16.5; // ERROR: Cannot store a floating-point number in an int
Practical Session
- Create a class that class name should be your name. Save it in a different path (not in C:\). Compile it and Run it.
- Identify given code sample's basic elements that categorized to below five categories.
- Import statements
- Classes
- Methods
- Variables
- Comments
- Create your own class and it must include below elements.
- Import statement
- Class
- Method
- Variable
- Comment
- Declare 8 variables in Primitive Data Types and save it as class "PDT".
Try these variable declarations and check them in right syntax or not.(Save it as "Integers.java")Give them to a definition in given space.
- In assume and real mark √ or ×.
Declaration | Assume | Real | Definition |
byte b1=0; | |||
Byte b2=0; | |||
byte b3=128; | |||
byte b4=-128; | |||
byte b5=128; | |||
byte b6=132; | |||
short s1=4; | |||
Short s2=1245; | |||
int i1=128; | |||
int i2=12.0; | |||
int i3=-327682; | |||
int i4=00; | |||
int i5=38; | |||
int i6=046; | |||
int i7=0x26; | |||
Int i8=5000; | |||
long l1=0; | |||
long l2=-0; | |||
Long l3=5; | |||
long l4=32769; | |||
Try these variable declarations and check them in right syntax or not.(Save it as "Floatings.java")Give them to a definition in given space.
- In assume and real mark √ or ×.
Declaration | Assume | Real | Definition |
float f1=0.0; | |||
float f2=0.0f; | |||
float f3=12F; | |||
Float f4=-128.04F; | |||
float f5=128F; | |||
double d1=132.0; | |||
double d2=4.5d; | |||
double d3=1245.123D; | |||
double d4=128; | |||
double d5=12.; | |||
double d6=0.003323; | |||
double d7=6.022e23; | |||
double d8=3.14E-05; | |||
Double d9=23; | |||
Try these variable declarations and check them in right syntax or not.(Save it as "Booleans.java")Give them to a definition in given space.
- In assume and real mark √ or ×.
Declaration | Assume | Real | Definition |
boolean b1=true; | |||
boolean b2=false; | |||
Boolean b3=true; | |||
boolean b4=True; | |||
boolean b5=tRue; | |||
boolean b6="true"; | |||
boolean b7=0; | |||
boolean b8=null; | |||
boolean b9=0<5; | |||
No comments:
Post a Comment