Java Basics

PJ Dillon CS401

Slides adapted from Dr. Ramirez

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. mousePressed . ArrayIndexOutOfBoundsException ± Methods and variables: start with lower case. then start each word with an upper case letter ± Ex: StringBuffer. BufferedInputStream. lastIndexOf. then start each word with an upper case letter ± Ex: compareTo.

Literals ‡ Values that are hard-coded into a program ± They are literally in the code! ‡ Different types have different rules for specifying literal values ± They are fairly intuitive and similar across most programming languages ± Integer ‡ An optional +/. µy¶. µq¶ ± String ‡ A sequence of characters contained within double quotes ‡ Ex: ³This is a string literal´ ± See p. -78.followed by a sequence of digits ‡ Ex: 1024. 1024786074 ± Character ‡ A single character in single quotes ‡ Ex: µa¶. 75-77 for more literals .

var1 = 100. Ex: int var1.. var2. ‡ Method call <method ID>(<expression>. <variable>. ‡ We¶ll discuss others later . var2 = 100 + var1. «.out.).<expression>.Statements ‡ Units of declaration or execution ‡ A program execution can be broken down into execution of the program¶s individual statements ‡ Every Java statement must be terminated by a semicolon (.. Ex.) ‡ Variable declaration statement <type> <variable>.. ‡ Assignment statement <variable> = <expression>. System.println(³Answer is ³ + var1).

Variables ‡ Memory locations that are associated with identifiers ‡ Values can change throughout the execution of a program ‡ In Java. ^ .String required: int int i = "hello". incompatible types found: java.lang. 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 ± Java is fairly strict about enforcing data type values ‡ You will get a compilation error if you assign an incorrect type to a variable: Ex: int i = ³hello´.

5.5. ^ ± Ex: double x = 100. » This is ok . 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 ± Ex: int i = 3. possible loss of precision found : double required: int int i = 3.Variables ± Note: For numeric types.

5.5. Error check each of the statements in the box to the right . double z = 100. y = z.5. you must explicitly cast the value to that variable type int i = 5. int j = 4. 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. float x = 3. j = (byte) y. i = z.Variables ± Floating point literals in Java are by default double ‡ If you assign one to a float variable. j = (long) y. float y = (float) 3. z = i.

boolean ± See Section 2. double. char.3 and ex2a. float. long.java for more details on the primitive numeric types . short. 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.Variables ‡ In Java. int.

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´). based on their classes ± We will discuss reference types in more detail in Chapter 3 when we start looking at Objects . s Hello There ± There are many implications to using reference types. and we must use them with care ± Different objects have different capabilities.

^ Variables ‡ Java variables can be initialized in the same statement in which they are declared ± Ex: double x = 5.0. all variables must be declared before they can be used Ex: x = 5.0.‡ In Java. ± 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. as long as they are separated by commas ± Ex: int i = 10. k = 45. j = 20. .0. ‡ Multiple variables of the same type can be declared and initialized in a single statement.

the result of the computation ‡ Result replaced the expression in the statement ± Ex: Consider the assignment statement : x=1+2+3+4.Operators and Expressions ‡ Expressions are parts of statements that ± Describe a set of operations to be performed ± Are evaluated at run time ± Ultimately result in a single value. ‡ 1+2+3+4 is evaluated to be 10 when the program is run ‡ X ultimately gets assigned the value 10 ‡ Operators describe the operations that should be done ± Simple numeric operations ± Other more advanced operations (to be discussed later) .

however: » If both operands are integer. ±. // answer? m = i % j. i = 16.Operators and Expressions ‡ Numeric operators in Java include +. k. always producing an integer result ± discuss implications » The % operator was designed for integer operands and gives the remainder of integer division » However. % can be used with floating point as well int i. j = 7. j. % ± These are typical across most languages ± A couple points. m. /. *. // answer? . / will give integer division. k = i / j.

/. 678 ‡ Recall that the precedence indicates the order in which operators are applied ‡ Recall that the associativity indicates the order in which operands are accessed given operators of the same precedence ‡ General guidelines to remember for arithmetic operators: *. % +. left to right associativity same (lower) precedence. let¶s do another example ‡ ex2a.java . ± same precedence. 81 and on p. also L to R ± Ok.Operators and Expressions ± Precedence and Associativity ‡ See chart on p.

± See Sections 2.Operators and Expressions ‡ Java has a number of convenience operators ± Allow us to do operations with less typing ± Ex: X = X + 1. X++.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++. Y ±= 5. ++X.11 and 2. . Y = Y ± 5.

) » I can use that address to send something to Joe or to go visit him if I would like » However. it will have the address of my friend. I can indirectly change the data in the object through the reference ± Knowing his address. but now I no longer know where Joe is located ‡ However. Joe Schmoe (stored as Schmoe. J. I can go to Joe¶s house and steal his plasma TV .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. if I change that address in my Contacts file. it does NOT in any way affect Joe.

Using Objects ‡ What do we mean by "objects"? ± Let's first discuss classes ‡ Classes are blueprints for our data ± The class structure provides a good way to encapsulate the data and operations of a new type together ‡ Instance data and instance methods ‡ The data gives us the structure of the objects and the operations show us how to use them ‡ Ex: A String .

Using Objects ± User of the class knows the general nature of the data. and the public methods. Java objects are instances of Java classes . 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 ‡ To put it another way.

More References ‡ Back to references. ± S1 now references an instance of a StringBuffer object but S2 does not . 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").

we will get an error ± Multiple variables can access and alter the same object S2 = S1.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. ‡ Now any change to S1 or S2 will update the same object S1 S2 Hello .

append(" there Java maestros!").More References ± Properties of objects (public methods and public instance variables) are accessed via "dot" notation S1. NOT the objects StringBuffer S3 = new StringBuffer("Hello there Java maestros!"). ‡ S2 will also access the appended object ± Comparison of reference variables compares the references. == S2) System.println("Equal").out.out. // yes if (S1 == S3) System.println("Equal"). // no if (S1 ‡ What if we want to compare the objects? .

// yes ‡ It seems complicated but it will make more sense when we get into defining new classes .equals(S3.println("Same value").out. the equals() method is not (re)defined for the StringBuffer class.toString().toString())) System.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. so we need to convert our StringBuffer objects into Strings in order to compare them: if (S1.

. S1.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) ± References can be set to null to initialize or reinitialize a variable ‡ Null references cannot be accessed via the "dot" notation ‡ If it is attempted a run-time error results S1 = null.append("This will not work!").

More references ‡ Why? ± The method calls are associated with the OBJECT that is being accessed.java . there are no methods available to call ± Result is NullPointerException ± common error so remember it! ± Let's take a look at ex3. NOT with the variable ± If there is no object.

we¶ll get input from two sources ± Standard Input Stream ‡ Scanner class ± Command Line Arguments .Program Input ‡ We¶ve already discussed basic output with the terminal window ± System. ± Standard Output Stream ‡ For now.println(³Area is ³ + area).out.

in ± Standard Output: System. 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 ‡ Acts as a pipe connected to your program ± A channel providing communication to and from the outside world ‡ For now.Streams ‡ A Stream is a continuous. we¶ll concern ourselves with the two (three) given to us ± Standard Input: 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 ± The tokens can be read in either as Strings ‡ next() ‡ nextLine() ± Or they can be read as primitive types ‡ Ex: nextInt(). nextFloat(). nextDouble() .

java .util.java ‡ ex4b.Scanner.Scanner.util.main(ex3.util.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 ± Let¶s try an example: ‡ ex4a. 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.util.Scanner.InputMismatchException at java.Scanner.nextInt(Unknown Source) at java.Scanner ± If read as primitive types.throwFor(Unknown Source) at java.next(Unknown Source) at java.nextInt(Unknown Source) at ex3.

Command Line Args ‡ Remember the main() method public static void main(String[] args) ‡ 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 ‡ We¶ll discuss arrays in more detail soon ‡ For now.java . let¶s do an example: ex4c.

Sign up to vote on this title
UsefulNot useful