P. 1
Java Basics

Java Basics

|Views: 15|Likes:
Published by Dominic Louise

More info:

Published by: Dominic Louise on Sep 24, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PPT, PDF, TXT or read online from Scribd
See more
See less

08/21/2014

pdf

text

original

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

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

„y‟. 1024786074 – Character • A single character in single quotes • Ex: „a‟. „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.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 +/. 75-77 for more literals .

.<expression>. Ex: int var1.. System. <variable>. Ex. • Method call <method ID>(<expression>.println(“Answer is “ + var1).out. var2 = 100 + var1. var1 = 100.). • We‟ll discuss others later . var2. • Assignment statement <variable> = <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 (. …..) • Variable declaration statement <type> <variable>.

String required: int int i = "hello". 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”.Variables • Memory locations that are associated with identifiers • Values can change throughout the execution of a program • In Java.lang. incompatible types found: java. ^ .

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

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

char.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. short. long. boolean – See Section 2. double. var1 100 – There are 8 primitive types in Java: byte.3 and ex2a.java for more details on the primitive numeric types . float. int.

s Hello There – There are many implications to using reference 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”). 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 .

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

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) .

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

java . let‟s do another example • ex2a. left to right associativity same (lower) precedence. % +.Operators and Expressions – Precedence and Associativity • See chart on p. – same precedence. 81 and on p. also L to R – Ok. /. 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: *.

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

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

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 .

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.Using Objects – User of the class knows the general nature of the data.

S2. – S1 now references an instance of a StringBuffer object but S2 does not .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. – 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").

• Now any change to S1 or S2 will update the same object S1 S2 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.

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

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

.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!"). S1.

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

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

Streams • A Stream is a continuous. we‟ll concern ourselves with the two (three) given to us – Standard Input: System.out . 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.in – Standard Output: System.

nextFloat(). nextDouble() .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().

Scanner – If read as primitive types.java .Scanner.nextInt(Unknown Source) at java.util.util.main(ex3.next(Unknown Source) at java.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.util.throwFor(Unknown Source) at java. 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.Scanner.util.util.nextInt(Unknown Source) at ex3.InputMismatchException at java.java • ex4b.Scanner.Scanner.

java . let‟s do an example: ex4c.class 10 13 Steve • Passed in by the operating system • User must know the order and format of each argument • NOTE: Unlike C/C++.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. only the actual arguments are passed to the program • We‟ll discuss arrays in more detail soon • For now.

.089748  1 $ $ $8902 4:9 57393 6:.84..708 907010703...2.7.9 425. /49349..98 5:-.2..5503/ 9070.7843417010703. .3/ 5:-..98 $973:1107$ 30$973:1107 049070.0.0.7..5503/0/4-0.089748  W $.943 $ ..389.08 !74507908414-0.-08.3..2094/8.0880/.470#010703..425.08890.70.-08 .08  %904-0.

.

08 1 $ $ $8902 4:9 57393 6:. .

.

98 .3994.910.70904-0.425.34 W .

88 840300/94..:0 .8 2094/ %880307.98394$9738347/0794..0794:7 $973:11074-0.8 $ 94$973  $8902 4:9 57393 $.425../0130/1472.20.70/.8 2094/8349 70 /0130/14790 $973:1107.43.880894 .470#010703.425....934-0.9..88088443 40.98 0800494/013091474:743.08 W 0:809006:.07 9006:.70 902 1 $ 94$973 06:.3.

.

90/-:992. 08 W 980028..0247080380 03009394/013330.8808 ..425.

.9 %006:.82094/84:89.0.998908..4707010703.039090898 %04507.9902590/.:08.-0 W :7010703..204-0.5503/ %834947  ...90/49 349..08.947848:89.3349-0..3-0809943:9439.943 W 198.7.908..20 /0503/343498/0130/ #010703.047 7039.0880/.7:3 92007747708:98 $3: $ .7038420 .08.08 W 49090/110703.990.

9 9070.884..98 -03.8..0.7..422430774784 70202-079 09 89.-094 .0880/  %990.. .90 . #08:98:!43907..05943 .4707010703.90/990 %9..70342094/8...08 W  %02094/.-0 190708344-0.70....44.

3/.3307.7/ :95:9$970.2 W 4734 0 0935:917429484:7.88 422.8.70..70.4:95:99 9090723.:880/-.0.8  .08 $9.!747..3/4 $8902 4:9 57393 70.2 W $.  $9.//8.3/.3/307:20398 .7/35:9$970.235:9 W 0 .

550.43.2 8.943 W . W 347/070/ 806:03.330574.90/944:75747.28 W $970.850.4393:4:8 80023313908:554147 83147/.$970....3/.0 .3/.3/1742904:98/0 47/ W 4734 0 .10/ /70.0394:8 $9..9.7/35:9$8902 3 $9.4330.041-9081483./3.0899094 9700  .0734:780.94394.943 31742842084:7.8.98.3-080394:9948420/0893.422:3.7/ :95:9$8902 4:9 .2 .

..$.8$9738 W 309 W 30930 790../.2.17429089...970.7.890 /02907 %094038.88:8089085.90789.. /02907 W /029078.3-070../8/..3/...7.3/5.7808939494038-.80/43.3-070.33078.889.../30907.34907 W /01.7/ 35:98970.9 3094:-0 .:990$.85729.09508 W 30939 3094.3307..0.9.9/893:8 43094031742.3307 $..9074780941.

:9 35:982.059438 W ... :9 $.3/11070390..33904 .85729...0 ....3307 309 &3343$4:7....05943 ..:7190 ..9./ W  !0.....05943832470/09.3307 170. W %0809508410774783.7097394 70.30.. .9403/4083492.90 2.3 0 ...9.059433970.0/0.$.94:. :9 $.059438 W 0 44.82./../2..9..0 .3.9.3077474..0 . :9 $. :9 $....9:.3307 30939 &3343$4:7.8003907.. W 0- . .0 .3307 30939 &3343$4:7..70.90.09508 .3307 97447 &3343$4:7.9.....250 W 0.9.907 09 897.

2!74 .3 2094/ 5:-.41$9738.3 $973(.9.:90/ .3/1472..7:20398950/-90:80703903907570907.880/3-904507....89...9410.77.7:2039 W  %&30.88 $90.4/ 2....422.8 00.78 8.3.3/3078 W #0202-07902.9388902 W &8072:89349047/07.-.47708543/394908941 .0 W !.78 W .

832470/09. .880/94905747. ..7:20398.77.:88.9:. 4390..70 5..8443 W 4734 09 8/4.2 W 0 /8..30.2500.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->