500 likes | 606 Views
Lecture 1 Ch2 Everything is an Object. Manipulate objects with references. String s; //a references for string s here you’ve created only the reference, not an object. Create a new object with the ‘ new ’ keyword String s = new String( "asdf" );. Primitive types. Scoping.
E N D
Manipulate objects with references String s; //a references for string s • here you’ve created only the reference, not an object. Create a new object • with the ‘new’ keyword String s = new String("asdf");
Scoping Most procedural languages have the concept of scope. This determines both the visibility and lifetime of the names defined within that scope. { int x = 12; // Only x available { int q = 96; // Both x & q available } // Only x available // q “out of scope” }
Creating new data types: class • used the keyword class class ATypeName { /* Class body goes here */ } • Creating a new object with a new class ATypeName a = new ATypeName();
Fields and methods • you can put two types of elements in your class: fields and methods an example of a class with some fields class DataOnly { int i; f loat f; boolean b; } DataOnly d = new DataOnly(); d.i = 47; d.f = 1.1f; // ‘f’ after number indicates float constant d.b = false;
Methods, arguments, and return values • The fundamental parts of a method are the name, the arguments, the return type, and the body. returnType methodName( /* Argument list */ ) { /* Method body */ } The return type is the type of the value that pops out of the method after you call it. The argument list gives the types and names for the information you want to pass into the method. The method name and argument list together uniquely identify the method
Calling a method • You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list objectName.methodName(arg1, arg2, arg3); The argument list • specifies what information you pass into the method int storage(String s) { return s.length() * 2; }
boolean flag() { returntrue; } float naturalLogBase() { return 2.718f; } void nothing() { return; } void nothing2() {} Building a Java program • Using other components - using the ‘import’ keyword tells the compiler to bring in a package import java.util.ArrayList; //tell the compiler that you want to use Java’s ArrayList class import java.util.*;
The static keyword • if you want to have only one piece of storage for a particular piece of data, regardless of how many objects are created, or even if no objects are created. class StaticTest { staticint i = 47; } StaticTest st1 = new StaticTest(); StaticTest st2 = new StaticTest(); • st1.i and st2.i are the same with the value 47 they refer to the same piece of memory
static Method class StaticFun { staticvoid incr() { StaticTest.i++; } } • Calling the static method StaticFun sf = new StaticFun(); //1st way sf.incr(); //2nd way StaticFun.incr();
Your first Java program // HelloDate.java import java.util.*; publicclass HelloDate { publicstaticvoid main(String[] args) { System.out.println("Hello, it's: "); System.out.println(new Date()); } } Compiling and running javac HelloDate.java java HelloDate
Comments • The traditional C-style comment was inherited by Java . • everything inside the /* and */ is ignored /* This is a comment that continues across lines */ • many programmers will begin each line of a continued comment with a *, /* This is a comment * that continues * across lines */ • The single-line comment, which starts at a // // This is a one-line comment
Common documentation • In Java, writing code is not the only important activity. • Documenting is at least as important. • The tool to extract the comments is called javadoc • The output of javadoc is an HTML file that you can view with your Web browser.
Syntax of javadoc • There are three “types” of comment documentation, which correspond to the element the comment precedes: class, variable, or method • All of the javadoc commands start with /** and end with */. /** A class comment */ publicclass DocTest { /** A variable comment */ publicint i; /** A method comment */ publicvoid f() {} } • javadoc will process comment documentation for only public and protected members
Syntax of javadoc • Two primary ways to use javadoc: - embed HTML - use “doc tags.” • Standalone doc tags are commands that start with a ‘@’ and are placed at the beginning of a comment line.
Embedded HTML • This allows you full use of HTML. /** * <pre> * System.out.println(new Date()); * </pre> */ • asterisks at the beginning of a line are thrown away by javadoc, along with leading spaces • Don’t use headings such as <h1> or <hr> as embedded HTML, because javadoc inserts its own headings and yours will interfere with them.
Some example of tags • @see: referring to other classes - Javadocwill generate HTML with the @see tags hyperlinked to the other documentation @see classname @see fully-qualified-classname @see fully-qualified-classname#method-name • @version @version version-information • @author @author author-information
Some example of tags • @since indicate what version of the JDK is used • @param @param parameter-name description • @return @return description • @throws @throws fully-qualified-class-name description
Documentation example //: c02:HelloDate.java import java.util.*; /** The first Thinking in Java example program. * Displays a string and today's date. * @author Bruce Eckel * @author www.BruceEckel.com * @version 2.0 */ publicclass HelloDate { /** Sole entry point to class & application * @param args array of string arguments * @return No return value * @exception exceptions No exceptions thrown */ publicstaticvoid main(String[] args) { System.out.println("Hello, it's: "); System.out.println(new Date()); } } ///:~
Using Java Operators • Addition (+), subtraction and unary minus (-), multiplication (*), division (/), and assignment (=) • Precedence - Operator precedence defines how an expression evaluates when several operators are present. Java has specific rules that determine the order of evaluation - multiplication and division happen before addition and subtraction a = x + y - 2/2 + z; a = x + (y - 2)/(2 + z);
Assignment • Aliasing during method calls //: c03:PassObject.java // Passing objects to methods may not be what // you're used to. class Letter { char c; } publicclass PassObject { staticvoid f(Letter y) { y.c = 'z'; } publicstaticvoid main(String[] args) { Letter x = new Letter(); x.c = 'a'; System.out.println("1: x.c: " + x.c); f(x); System.out.println("2: x.c: " + x.c); } } ///:~
Assignment • The result: • 1: x.c: a • 2: x.c: z
Mathematical operators • Addition (+), subtraction (-), division (/), multiplication (*) and modulus (%, which produces the remainder from integer division). • x += 4, x -= 4, x *= 4, x /= 4, x %= 4 • Unary minus and plus operators • The unary minus (-)and unary plus (+) are the same operators as binary minus and plus x = -a; x = a * -b; (confused) x = a * (-b);
Auto increment and decrement • pre-increment: ++a • pre-decrement: --a • post-increment: a++ • post-decrement: a--
Logical operators • The logical operators are : • AND (&&) • OR (||) • NOT (!) • They can produce a boolean value of true or false based on the logical relationship of its arguments. • We can’t use a non-boolean (e.g. int,char…)as if it were a boolean in a logical expression as in C and C++.
//: c03:Bool.java // Relational and logical operators. import java.util.*; public class Bool { public static void main(String[] args) { Random rand = new Random(); int i = rand.nextInt() % 100; int j = rand.nextInt() % 100; prt("i = " + i); prt("j = " + j); prt("i > j is " + (i > j)); prt("i < j is " + (i < j)); prt("i >= j is " + (i >= j)); prt("i <= j is " + (i <= j)); prt("i == j is " + (i == j)); prt("i != j is " + (i != j)); // Treating an int as a boolean is not legal Java //! prt("i && j is " + (i && j)); //! prt("i || j is " + (i || j)); //! prt("!i is " + !i); prt("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)) );
prt("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)) ); } static void prt(String s) { System.out.println(s); } } ///:~ One output listing looked like this: i = 85j = 4 i > j is truei < j is false i >= j is true i <= j is false i = = j is false i != j is true (i < 10) && (j < 10) is false (i < 10) || (j < 10) is true Note that a boolean value is automatically converted to an appropriate text form if it’s used where a String is expected.
Short-circuiting • “Short circuiting” means that the expression will be evaluated only until the truth or falsehood of the entire expression can be unambiguously determined. As a result, all the parts of a logical expression might not be evaluated. (e.g.c03:ShortCircuit.java)The tests are used in the expression: if(test1(0) && test2(2) && test3(2)) If test1(0) produced a true result, the expression evaluation continues. Then, if the second test produced a false result. Since this means that the whole expression must be false, “Short circuiting”happens.
Bitwise operators • The bitwise operators allow you to manipulate individual bits in an integral primitive data type. • Bitwise operators perform boolean algebra on the corresponding bits in the two arguments to produce the result. • Bitwise operators are: • AND(&) • OR( | ) • XOR(^) • NOT(~)
Shift operators • The shift operators also manipulate bits. They can be used solely with primitive, integral types. • The left-shift operator (<<) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator (inserting zeroes at the lower-order bits). • The signed right-shift operator (>>) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator. • If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int.
Ternary if-else operator • Ternary if-else operator has three operands. • The expression is of the form: boolean-exp ? value0 : value1 • If boolean-exp evaluates to true, value0 is evaluated and its result becomes the value produced by the operator. • If boolean-exp is false, value1 is evaluated and its result becomes the value produced by the operator.
Here’s an example: static int ternary(int i) { return i < 10 ? i * 100 : i * 10; } You can see that this code is more compact than what you’d need to write without the ternary operator: static int alternative(int i) { if (i < 10) return i * 100; else return i * 10; } The second form is easier to understand, and doesn’t require a lot more typing.
String operator + • The + operator can be used to conjoin strings • If an expression begins with a String, then all operands that follow must be Strings int x = 0, y = 1, z = 2; String sString = "x, y, z "; System.out.println(sString + x + y + z); Here, the Java compiler will convert x, y, and z into their String representations instead of adding them together first. And if you say: System.out.println(x + sString); Java will turn x into a String.
Casting operators • Java will automatically change one type of data into another when appropriate. Casting allows you to make this type conversion explicit, or to force it when it wouldn’t normally happen. Here’s an example: void casts() { int i = 200; long l = (long)i; long l2 = (long)200; }
Literals • Hexadecimal (base 16), which works with all the integral data types, is denoted by a leading 0x or 0X followed by 0—9 and a—f either in upper or lowercase.e.g. short s = 0x7fff; // max short hex value int i1 = 0x2f; // Hexadecimal (lowercase) • Octal (base 8) is denoted by a leading zero in the number and digits from 0-7.e.g. int i3 = 0177; // Octal (leading zero)
A trailing character after a literal value establishes its type. – L,l -- long, –F,f --float –D,d -- double – e -- ten to the power e.g. long n1 = 200L; // long suffix float f3 = 1f; // float suffix float f4 = 1e-45f; // 10 to the power = 1*10^(-45)
Execution control • if-else you can use if in two forms: if(Boolean-expression) statement or if(Boolean-expression) statement else statement
return The return keyword has two purposes: – it specifies what value a method will return (if it doesn’t have a void return value) – it causes that value to be returned immediately. public class IfElse2 { static int test(int testval, int target) { int result = 0; if (testval > target) return +1; else if(testval < target) return -1; else return 0; // Match } public static void main(String[] args){ System.out.println(test(10, 5)); System.out.println(test(5, 10)); System.out.println(test(5, 5)); } } ///:~
Iteration • while The form for a while loop iswhile (Boolean-expression) statement • do-while The form for do-while is do statement while(Boolean-expression);
for The form of the for loop is: for(initialization;Booleanexpression;step) statement • break and continue– breakquits the loop without executing the rest of the statements in the loop. – continue stops the execution of the current iteration and goes back to the beginning of the loop to begin the next iteration.
label label1:outer-iteration { inner-iteration { //… break; // 1 //… continue; // 2 //… continue label1; // 3 //… break label1; // 4 } }
In case 1, the break breaks out of the inner iteration and you end up in the outer iteration. • In case 2, the continue moves back to the beginning of the inner iteration. • But in case 3, the continue label1 breaks out of the inner iteration and the outer iteration, all the way back to label1.Then it does in fact continue the iteration, but starting at the outer iteration. • In case 4, the break label1 also breaks all the way out to label1, but it does not re-enter the iteration. It actually does break out of both iterations.
Switch Its form is:switch (integral-selector) { case integral-value1 : statement; break; case integral-value2 : statement; break; case integral-value3 : statement; break; case integral-value4 : statement; break; case integral-value5 : statement; break; // ... default: statement; } If you want to use, for example, a string or a floating-point number as a selector, it won’t work in a switch statement. For non-integral types, you must use a series of if statements.
Exercise • 1. Write a program that prints values from one to 100. • 2. Modify Exercise 4 so that the program exits by using the break keyword at value 47. Try using return instead.