480 likes | 654 Views
Specific topics of the Java Language Related to This Class. Classes and objects (section 1.1) Methods (section 1.2) Variables and expressions (section 1.3) Control flow (section 1.4) Arrays (section 1.5) Input and Output (section 1.6) Packages (section 1.8) Exceptions (section 2.3)
E N D
Specific topics of the Java Language Related to This Class • Classes and objects (section 1.1) • Methods (section 1.2) • Variables and expressions (section 1.3) • Control flow (section 1.4) • Arrays (section 1.5) • Input and Output (section 1.6) • Packages (section 1.8) • Exceptions (section 2.3) • Interfaces (section 2.4) • Casting (section 2.4.4) CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Classes, Types and Objects • In Java, data structures and algorithms are implemented using classes and objects. • Every object is an instance of a class, which defines the type of data that the object stores, as well as the kinds of operations that can act on that data. • Members of a class in Java: • Instant variables • Methods CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
How Classes Are Declared • The syntax for a Java class definition: [<class_modifiers>] class <class_name> [extends <superclass_name> ] [implements <interface_1>, <interface_2>,…] { // class methods and instance variables definitions go here… } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Example http://ww3.java3.datastructures.net/source/ch01/Java/Gnome-Gnome.html CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Class Modifier • abstract: describes a class that has abstract methods. A class that has nothing but abstract methods and has no instance variables is called an interface. • final: describes a class that has no subclasses. • public: describes a class that can be instantiated or extended by anything in the same package or by anything that imports the class. • All public classes are declared in their own separate file called <classname>.java . • There can only be one public class per file! • friendly: describes a class that can be instantiated or extended by anything in the same package. This is the default class modifier. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Base Types (primitive type) • Not objects boolean Boolean value: true or false (different from c++) char 16-bit Unicode character (different from c++) byte 8-bit signed integer short 16-bit signed integer int 32-bit signed integer long 64-bit signed integer float 32-bit floating-point number double 64-bit floating-point number CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Objects • The new operator creates a new object from a specified class and returns a reference to that object. • Allocate memory for new object and initialize all instance variables. • The appropriate constructor is called. • new operator returns a reference ( a memory address) to the object variable. • Syntax: <variable_name> = new <class_type>([param,param,…]); Example: myGnome = new Gnome(); CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Number Objects • Base type numbers are not objects. What if we want to store numbers as objects? • Java defines a wrapper class for each numeric base type : number classes CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
String Objects • A string is a sequence of characters that comes from some alphabet, which is a set of characters. • Each character in a string has index starting from 0. String P = “hogs and dogs”; P[2] = ‘g’ • Primary operation for combining strings: concatenation (+) String s = “kilo” + “meters”; S is “kilometers” now. • Every object in Java is assumed to have a built-in method toString() that returns a string associated with the object. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Instance Variables • Instance variables must have a type, which can either be a base type or a class. • Syntax for declaring an instance variable: [<variable_modifier>] <variable_type> <variable_name> [=<initial_value>]; public class Gnome { // Instance variables: protected String name; protected int age; protected Gnome gnome_buddy; private boolean magical = false; public double height = 2.6; // in feet public static final int MAX_HEIGHT = 3; // maximum height // Method definition would go here… } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Variable Modifiers • public: anyone can access public instance variables. • protected: only methods of the same package or of subclasses can access protected instance variables. • private: only methods of the same class (not methods of a subclass) can access private instance variables. • friendly: default, can be accessed by any class in the same package. • static: declare a variable that is associated with the class, not with individual instances of the class. • Static variables are used to store “global” information about a class. • Static variables exist even if no instance of their class is created. • final: must be assigned an initial value, and then can never be assigned a new value after that. • If it is a base type, then it is a constant. • If it is an object variable, then it will always refer to the same object. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Method • A method definition has two parts: • Signature: name and parameters. • Body: defines what the method does. • A method allows a programmer to send a message to an object. • Syntax: <method_modifiers>] <return_type> <method_name> ([params]) { // method body… } • Example: public void renameGnome(String s) { name = s; // Reassign the name instance variable of this gnome } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Method Modifiers • public: anyone can access public methods. • protected: only methods of the same package or of subclasses can access protected method. • private: only methods of the same class (not methods of a subclass) can access a private method. • friendly: default, can only be called by objects of classes in the same package. • abstract: no code. Abstract methods may only appear within an abstract class. public abstract void setHeight (double newHeight); • static: is associated with the class, not with specific instances of the class. • Static methods can be used to change the state of static variables associated with a class. • final: cannot be overridden by a subclass. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Parameters • All parameters in Java are passed by value. • Any time we pass a parameter to a method, a copy of that parameter is made for use within the method body. void f(int a) { int b = 1; a = a+1; f(b); } b=? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Another Example void f(Gnome a) { a. renameGnome (“newname”); } Gnome b = new Gnome(); // b. getRealName() returns “Rumple“ f(b); b. getRealName() returns ? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Constructor Methods • A constructor is a special kind of method that is used to initialize newly created objects. • Syntax is the same as that of any other method. But there are several differences: • The name of the constructor must be the same as the name of the class it constructs. • A constructor has no return value; • An abstract, static, or final constructor is not allowed. • Constructors are invoked in a unique way: they must be called using the new operator. • A class can have many constructors, but each must have a different signature. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
The main Method • Classes that define stand-alone programs must contain the main method. • The main method must be declared as follows: public static void main(String[ ] args) { //main method body … } java Aquarium 45 args[0] refers the string “45” CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Statement Blocks and Local Variables • The body of a method is a statement block, which is a sequence of statements and declarations to be performed between the braces “{“ and “}”. • Statement blocks can contain declarations of local variables. • Local variables are similar to instance variables, but they only exist while the statement block is being executed. • Example: http://ww3.java3.datastructures.net/source/ch01/Java/Gnome-Gnome.html CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Expressions • Variables and constants are used in expressions to define new values and to modify variables. • Expressions involve the use of literals, variables, and operators. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Literals • A literal is any “constant” value that can be used in an assignment or other expression. • The null object reference (this is the only object literal) • Boolean: true and false; • Integer: 176, -52, 176L, -52L • Floating point: 3.1415, 3.1415F, 2.14E2 • Character: ‘a’ or ‘?’ • Special character constants: ‘\n’, ‘\t’,’\b’, ‘\r’, ‘\f’, ‘\\’, ‘\’’, ‘\”’ • String literals: “dogs all around” or “jump” CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
The Assignment Operator “=“ • Syntax: • <variable> = <expression> • i=j=25; // works because “=“ operators are evaluated right-to-left. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Dot Operator “.” • Use dot operator to access the members of the object • Syntax: • <object_reference>.<method_name>([<param>,<param>,…]); • overn.cookDinner(food); • Or <object_reference>.<variable_name> • gnome.name • If an object reference is not final, then it can appear on the left-hand side of an assignment as well. • gnome.name = “Professor Smythe”; • gnome.age = 132; • The <object_reference> can also be any expression that returns an object reference. • Gnome g = new Gnome(); • String buddyName = (g.gnome_buddy).name; CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Arithmetic Operators • + addition • - substraction • * multiplication • / division • % modulo • n % m = r, such that n = mq + r, for an integer q and 0 <= r < n. • 13 % 3 =? • 3 % 13 = ? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Increment and Decrement Operators • ++ increment operator • -- decrement operator • int i = 8; • int j = i++; • int k = ++i; • int m = i--; • int n = 9 + i++; • what is i, j, k, m, n now? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Logical Operators • < less than • <= less than or equal to • == equal to • != not equal to • >= greater than or equal to • > greater than • Operators that operate on boolean values: • ! not(prefix) • && conditional and • || conditional or CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Bitwise Operators • ~ bitwise complement (prefix unary operator) • & bitwise and • | bitwise or • ^ bitwise exclusive-or • << shift bits left, filling in with zeros • >> shift bits right, filling in with sign bit • >>> shift bits right, filling in with zeros CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Operational Assignment Operators • Syntax: • <variable> <op> = <expression>; • This is equivalent to • <variable> = <variable> <op> <expression>; • i = 5; • i += 5; • i = ? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Operator Precedence • determine the order in which operations are performed when the absence of parentheses brings up evaluations ambiguities. • Table 1.3, p22 in the textbook • What is: 5 + 21 / 4 % 3 = (5 + ((21 / 4) % 3)) = (5 + ( 5 % 3 )) = (5 + 2) = 7 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Casting in Expressions • change the type of a variable. • Syntax: • (<desired_type>) <variable>; CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Ordinary Casting • Possible among all integer and floating types, may lose precision • Possible among some class references double d1 = 3.2; double d2 = 3.9999; int i1 = (int) d1; // i1 has value 3 int i2 = (int) d2; // i2 has value 3 double d3 = (double) i2; // d3 has value 3.0 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Casting with Operators int i1= 3; int i2 = 6; dresult = (double) i1 /(double) i2; // dresult is 0.5 dresult = i1 / i2; //dresult is 0.0; CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Implicit Casting • Applied automatically when no information lost • float → double • byte → short → int→ long • int→ double int iresult, i = 3; double dresult, d = 3.2; dresult = i / d; // dresult is 0.9375 iresult = i / d; // compilation error, loss of precision iresult = (int) i/d; // iresult is 0 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Implicit Casting with String Objects • Explicit casting of an object or base type to a string is not allowed. String s = (String) 4.5; //wrong String t = “Value =“ + (String) 13; //wrong String u = 22; //wrong • Use toString method or perform an implicit cast via the concatenation operation. String s = “” + 4.5; // correct, but poor style String t = “Value = “ + 13; String u =Integer.toString(22); CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Control Flow – if/else • Syntax if (<boolean_expr>) <true_statement> [else if (<boolean_expr>) <else_if_statement>] [else <else_statement>] • Unlike C and C++, the expression in an if statement in Java must be a Boolean expression. if ( i = 5) //wrong CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Switch int i = 3; switch (i) { case 3: System.out.println(“3”); break; case 5: System.out.println(“6”); break; default: System.out.println(“Default”); break; } What is printed? What if no break statements? CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Loops while (<boolean_expression>) <loop_body_statement> for ([<initialization>];[<condition>];[<increment>]) <body_statement> example: for(int i = 0; i < 100, i++) { ...} do <loop_body_statement> while (<boolean_expression>) CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Explicit Control-Flow Statements • Returning from a Method • If a Java method is declared with return type of void, then flow of control returns when it reaches the last line of code in the method or when it encounters a return statement with on argument. • If a method is declared with a return type, it exits when it reaches a return statement. public boolean checkBDay (int date){ if (date == Birthdays.MIKES_BDAY) { return true; } return false; } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
The break Statement • It is used to “break” out of the innermost switch, for, while, or do-while statement body. • The break statement can also be used in a labeled form to jump out of an outer-nested loop or switch statement. public static boolean hasZeroEntry (int[ ][ ] a) { boolean foundFlag = false; zeroSearch: for (int i=0; i<a.length; i++) { for (int j=0; j<a[i].length; j++) { if (a[i][j] == 0) { foundFlag = true; break zeroSearch; } } } return foundFlag; } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
The continue Statement • Syntax: continue [<label>]; • The continue statement can only be used inside loops. • The continue statement causes the execution to skip over the remaining steps of the loop body in the current iteration. public static boolean hasZeroEntry (int[ ][ ] a) { boolean foundFlag = false; zeroSearch: for (int i=0; i<a.length; i++) { for (int j=0; j<a[i].length; j++) { if (a[i][j] == 0) { foundFlag = true; continue zeroSearch; } } } return foundFlag; } CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Arrays • An array is a number collection of variables all of the same type. • Index starts from 0. • <array_name>.length holds allocated number of elements. int [ ] myArray = new int[20]; myArray.length is 20 • Two-dimensional array is actually an array of array: float[ ][ ] x = new float[8][10]; x[4].length is 10 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Simple Output Methods • System.out is a built-in static object, that performs output to the “standard output” device. • Methods: • print(Object o):print the object o using its toString method. • print(String s): print the string s. • print(<base_type> b): print the base type value b. • println(String s): print the string s, followed by the newline character. • flush():print and empty the contents of the print buffer. System.out.print(“Java values: “); System.out.print(3.1415); System.out.print (‘,’); System.out.print(15); System.out.print(“ (double,char,int). “); Java values: 3.1415,15 (double,char,int). CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Simple Input Methods • System.in, perform input from the Java console window. • System.in object is an instance of the java.io.InputStream class, which is defined to proceed one character at time. • java.io.BufferedReader and java.io.InputStreamReader processe input in a streaming and buffered way. java.io.BufferedReader stndin; //standard input (buffered) String line; double sum, d = 0.0; int i = 0; stndin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); System.out.print(“Input a double: “); System.out.flush(); if ((line = stndin.readLine() != null) d = Double.valueOf(line).doubleValue(); System.out.println(“Input an int: “); System.out.flush(); if ((line = stndin.readLine()) != null) i = Integer.valueOf(line).intValue(); sum = d + i; System.out.println(“Their sum is “ + sum + “.”); Input a double: 6.1078 Input an int: 209 Their sum is 215.1078. CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
Packages • A set of related classes under a common subdirectory. • Every file in a package starts with the line: package <package_name>; • The subdirectory containing the package must be named the same as the package. • Using other packages: public boolean Temperature(TA.Measures.Thermometer thermometer, int temperature) { ....} • Import packages: import <packageName>.<classNames>; package Project; import TA.Measures.Thermometer; import TA.Measures.Scale; or import TA.Measures.* public boolean Temperature(Thermometer thermometer, int temperature) { ....} CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas
An Example Program • CreditCard http://ww3.java3.datastructures.net/source/ch01/Java/CreditCard-CreditCard.html • Test http://ww3.java3.datastructures.net/source/ch01/Java/Test-CreditTest.html • Output http://ww3.java3.datastructures.net/source/ch01/Java/output2-credit.html CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas