Professional Documents
Culture Documents
PJ Dillon CS401
Identifiers
Keywords
Lexical elements (or identifiers) that have a special, predefined meaning in the language Cannot be redefined or used in any other way in a program Ex: public, private, if, class, throws See p. 32 in LL for complete list
Identifiers
Other Identifiers
Defined by programmer Java API defines quite a few for us
e.g. System, Scanner, String, out
are used to represent names of variables, methods and classes Cannot be keywords We could redefine those defined in Java API if we wanted to, but this is generally not a good idea Java IDs must begin with a letter, followed by any number of letters, digits, _ (underscore) or $ characters
Similar to identifier rules in most programming langs
Identifiers
Important Note:
Java identifiers are case-sensitive this means that upper and lower case letters are considered to be different be careful to be consistent! Ex: ThisVariable and thisvariable are NOT the same
Naming Convention:
Many Java programmers use the following conventions:
Classes: start with upper case, then start each word with an upper case letter Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException Methods and variables: start with lower case, then start each word with an upper case letter Ex: compareTo, lastIndexOf, mousePressed
Literals
Values that are hard-coded into a program
They are literally in the code!
Character
A single character in single quotes Ex: a, y, q
String
A sequence of characters contained within double quotes Ex: This is a string literal
Statements
Units of declaration or execution A program execution can be broken down into execution of the programs individual statements Every Java statement must be terminated by a semicolon (;) Variable declaration statement <type> <variable>, <variable>, ; Ex: int var1, var2; Assignment statement <variable> = <expression>; Ex. var1 = 100; var2 = 100 + var1; Method call <method ID>(<expression>,<expression>,...); System.out.println(Answer is + var1); Well discuss others later
Variables
Memory locations that are associated with identifiers Values can change throughout the execution of a program In Java, must be specified as a certain type or class
The type of a variable specifies its properties: the data it can store and the operations that can be performed on it
Ex: int type: discuss
incompatible types
Variables
Note: For numeric types, you even get an error if the value assigned will lose precision if placed into the variable
Generally speaking this means we can place smaller values into larger variables but we cannot place larger values into smaller variables
Ex: byte < short < int < long < float < double
Variables
Floating point literals in Java are by default double If you assign one to a float variable, you will get a loss of precision error as shown in the previous slide If you want to assign a more precise value to a less precise variable, you must explicitly cast the value to that variable type int i = 5; int j = 4.5; float x = 3.5; float y = (float) 3.5; double z = 100; i = z; y = z; z = i; j = (long) y; j = (byte) y;
Variables
In Java, variables fall into two categories: Primitive Types Simple types whose values are stored directly in the memory location associated with a variable Ex: int var1 = 100; var1 100
There are 8 primitive types in Java: byte, short, int, long, float, double, char, boolean See Section 2.3 and ex2a.java for more details on the primitive numeric types
Variables
Reference Types (or class types) Types whose values are references to objects that are stored elsewhere in memory Ex: String s = new String(Hello There); s
Hello There
There are many implications to using reference types, and we must use them with care Different objects have different capabilities, based on their classes We will discuss reference types in more detail in Chapter 3 when we start looking at Objects
In Java, all variables must be declared before they can be used Ex: x = 5.0; This will cause an error unless x has previously been declared as a double variable
cannot resolve symbol symbol : variable x location : class classname x = 5.0; ^
Variables
Java variables can be initialized in the same statement in which they are declared Ex: double x = 5.0; Multiple variables of the same type can be declared and initialized in a single statement, as long as they are separated by commas Ex: int i = 10, j = 20, k = 45;
See Sections 2.11 and 2.12 for more details One point that should be emphasized is the difference between the prefix and postfix versions of the unary operators
What is the difference between the statements:
X++; ++X;
References
What do we mean by references?
The data stored in a variable is just the address of the location where the object is stored
Thus it is separate from the object itself Ex: If I have a Contacts file on my PC, it will have the address of my friend, Joe Schmoe (stored as Schmoe, J.) I can use that address to send something to Joe or to go visit him if I would like However, if I change that address in my Contacts file, it does NOT in any way affect Joe, but now I no longer know where Joe is located
However, I can indirectly change the data in the object through the reference
Knowing his address, I can go to Joes house and steal his plasma TV
Using Objects
What do we mean by "objects"?
Let's first discuss classes
Using Objects
User of the class knows the general nature of the data, and the public methods, but NOT the implementation details
But does not need to know them in order to use the class
Ex: BigInteger
We call this data abstraction Java classes determine the structure and behavior of Java objects
More References
Back to references, let's now see some of the implications of reference variables
Declaring a variable does NOT create an object
We must create objects separately from declaring variables
StringBuffer S1, S2; Right now we have no actual StringBuffer objects just two variables that could access them To get objects we must use the new operator or call a method that will create an object for us S1 = new StringBuffer("Hello"); S1 now references an instance of a StringBuffer object but S2 does not
More References
So what value does S2 have?
For now we will say that we should not count on it to have any value we must initialize it before we use it If we try to access it without initializing it, we will get an error
Properties of objects (public methods and public instance variables) are accessed via "dot" notation
S1.append(" there Java maestros!");
More References
More References
We use the equals() method
This is generally defined for many Java classes to compare data within objects We will see how to define it for our own classes soon However, the equals() method is not (re)defined for the StringBuffer class, so we need to convert our StringBuffer objects into Strings in order to compare them:
It seems complicated but it will make more sense when we get into defining new classes
More references
Note the difference in the tests:
The == operator shows us that it is the same object The equals method show us that the values are in some way the same (depending on how it is defined)
More references
Why?
The method calls are associated with the OBJECT that is being accessed, NOT with the variable If there is no object, there are no methods available to call Result is NullPointerException common error so remember it!
Program Input
Weve already discussed basic output with the terminal window
System.out.println(Area is + area); Standard Output Stream
Streams
A Stream is a continuous, seemingly infinite supply of or sink for data An ordered sequence of bytes flows in a specified direction
in from some source can be sent out to some destination
For now, well concern ourselves with the two (three) given to us
Standard Input: System.in Standard Output: System.out
Scanner
Scanner is a class that reads data from the standard input stream and parses it into tokens based on a delimiter
A delimiter is a character or set of characters that distinguish one token from another By default the Scanner class uses white space as the delimiter
Scanner
If read as primitive types, an error will occur if the actual token does not match what you are trying to read
Ex:
Please enter an int: hello Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ex3.main(ex3.java:39)
These types of errors in Java are called exceptions Java has many different exceptions We'll look at exceptions in more detail later
Lets try an example:
ex4a.java ex4b.java
args is an array of Strings corresponding to the list of arguments typed by the user when the interpreter was executed
javalab$ java myProg.class 10 13 Steve
Passed in by the operating system User must know the order and format of each argument NOTE: Unlike C/C++, only the actual arguments are passed to the program Well discuss arrays in more detail soon For now, lets do an example: ex4c.java