Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java an object-oriented programming language Introduced by James Golsling in 1995 (at Sun ). supports development of full fledged applications and browser-run applets includes support for concurrency and security C++-like syntax, but no pointers, thus safer code supported by powerful vendor: Oracle Java Application Standalone programs - run using a Java Virtual Machine interpreter Widely used for Networking Database applications Multi-tiered architectures Important features of Java Portability - Java code compiles into platform independent byte-code, which is interpreted on each platform by a java-virtual -machine. Automatic garbage collection (no memory allocation/leakage worries) No pointer arithmetic (safer code) Multiple inheritance supported only for interfaces Rigorous support for exception (error) handling Supports method execution across a network via Remote Method Invocation Comes with an extensive library of predefined classes (Java API) - 1 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 2 of 11 Object-Oriented Development It is popular because of issues of productivity and overall speed of development. Key idea focus modeling and implementation on the individuals of the problem domain rather then system functions, build system description around the objects, because domain objects usually comprise the most stable part of the system (usually don t change much even if system requirements change dramatically). Class: a general description of objects of similar kind. Includes data and methods that operate on that data Example: a banking application operates on accounts Class: Account Data (properties): Owner, Number, Open Date, Transactions Methods (behaviors): Compute Balance Key OO concepts: 1. Objects and Classes problem domain entities classified according to their properties 2. Encapsulation and Information Hiding package an object s data attributes and behavior together restrict access to data 3. Specialization (a.k.a. inheritance) detect commonalities between classes create class hierarchy to inherit common properties without repeating them Example: Checking account, Savings account classes are subclasses of Account. Inherit properties of Account, Class: Checking Account Data (properties): All those of Account class + Service Fee Methods (behaviors): All those of Account class + Deposit, Withdraw 4. Communication with messages to invoke an object send it a message, let the object itself handle it 5. Polymorphism often same operation exists in many classes, example: Print each class implements it differently, but uses the same name for it Compared to structured development, OO provides additional flexibility, potential for reuse and robustness in face of changes. Click to see an illustration. From Java source code to execution - 2 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 3 of 11 Java application is a collection of classes. Here s the simplest example with one class containing just a single method called main. Create a Java source file called HelloWorldApp.java. The name of the file must match the name of the class. Java is case sensitive, e.g. main is different from Main, Hello is different from hello /* HelloWorldApp.java * Prints Hello, World! */ public class HelloWorldApp { public static void main(string[] args) { // print Hello World! System.out.println("Hello, World! Welcome to Bentley."); In compiled languages: Source Code Processor- Specific Compiler Binary File Runtime System In Java: Source Code Hello.java Compiler javac.exe Bytecode Hello.class Java Virtual Machine (JVM) interprets byte-code Java Virtual Machine Processor- Specific Interpreter java.exe Runtime System - 3 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 4 of 11 LEXICAL ELEMENTS: Words and symbols that make up a language, including comments, keywords, identifiers, punctuation, literals, and operators. Example: /* This is an example of a simple Java program that prints the value stored to the variable x */ public class DeclareVar{ public static void main(string[] args){ int x; x = 5; // declare variable x // store the value 5 to x System.out.println("x = " + x); // print the value of x // end of main method // end of class DeclareVar Comments: // for a single line, till the end of line /* Start a multiple line comment with the slash and asterisk End it with an asterisk and a slash */ Punctuation: a ; is used to indicate the end of a statement. Variable - is a named location to store data It can hold only one type of data All program variables must be declared before using them. A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: e.g. int, float, double, char, String x 5 Identifiers: names for elements in a program, including classes, methods, and variables May consist of letters, digits, the underscore(_) and $ (reserved for system identifiers) Must not start with a digit Can t be a keyword: word that has a meaning in the language, such as if, boolean, or class. Can t include spaces, punctuation symbols Are case sensitive: x is not the same as X! By convention: class names start with an uppercase letter, variables and methods start with the lowercase. - 4 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 5 of 11 DATA TYPES: Each variable has a name and a type. Type refers to the values that can be stored in a variable. Java has primitive and class types. 1. Primitive: built into Java, define non-decomposable values. (1) Numeric: byte 8 bits = 1 byte -128 to 127 short 16 bits -32768 to 32767 int 32 bits -2 31 to 2 31-1 Default for integer literal long 64 bits specify by adding an l or L: 23L float 32 bits specify by adding f or F: 37.23F double 64 bits default for floating point literal ex. of floating point types: 3.12342, 2.18e-25 (= 2.18 x 10-25 ) (2) char: stores a single character, digit, or symbol. Always surrounded by single quotes, such as a or 9. Stored in 2-bytes (as opposed to many other languages allows for many alphabets) Each character is stored as its code number in Unicode. (3) boolean: true or false. All variables must be declared either before or when they are first used: ASSIGNMENT OPERATOR = Used to set, or assign a variable is to store a given value in the location denoted by the variable name. Not the same as equality in algebra, It means - Store the value of the expression on the right side to the variable on the left side. Examples: Can have any expression on the right hand side of = Restriction: the type of the variable must be compatible with the type of the expression on the right hand side. // declare integer variable and store value to it int x; x = 3; //declare new integer and store value of x to it int y = x; // evaluated right to left: // set value stored to x = value stored to y = 4 x = y = 4; - 5 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 6 of 11 // declare two doubles and store values to them double u, v; u = 2.32; v = x; //declare two integers and store value to one of them int a = 2, b; // declare a character variable and store a value to it char letter = a ; //declare two boolean variables and store values to them boolean done = false; boolean start = true; 2. Classes : all other data types (i.e., non-primitives) are defined as class types. String: stored as object of class String. Always enclosed in double quotes. // declare a string variable and store a value to it String prompt = enter your name ; OPERATORS Arithmetic Operators: only operate on numerical data. +, -, *, /, %, ( ) (1) integer division: results from dividing one int by another. Returns whole number quotient, ignoring remainder (truncates). 21 / 4 =? 7 / 2 =? (2) %: modulus, or remainder. 21 % 4 =? 8 % 2 =? /* Illustration of % operator */ public class Remainder{ public static void main(string[] args){ int x = 7; int y = 3; int z = (x/y)*y + x%y System.out.println("z = " + z); // print value of z // end of main method // end of class Remainder - 6 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 7 of 11 Order of precedence (elements in the same row have the same precedence): () +(unary) (unary) * / % + - = (assignment) Unary operators take one operand. Example: -3 + 5 // unary operator is ( ) before the three; the (+) is a binary operator here Read from left to right when evaluating an expression. Example: int x = 4, y = 5, z = 3, answer; answer = y - x * z; answer = (y - x) * z; answer = y / x + z; answer = y / (x + z); answer = x - y % z + y; answer = (x - y) % (z + y); Java automatically converts from int to double when the data types are mixed: double x = 4; x = 3.4 * 2; //4 is converted to a double //2 treated as a double Rule for implicit conversion: any numeric value can be assigned to a numeric value of any type that supports a larger range of values. ints are converted to doubles in mixed-type expression. doubles are not converted to ints in mixed-type expression. Explicit type casting: double x = 4.3; // int y = (int)x; // truncates and stores 4 in y int z = (int)'a'; // explicitly converts char to an int - 7 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 8 of 11 Relational Operators: also called Comparison Operators. Used with operands: <operand> operator <operand> Use them for making decisions: true or false for outcome. Include: > < >= <= ==!=! is a not operator, so!= means not equal = is an assignment operator, while == is a comparison operator) x = 3; // assigns 3 to x y = x + 1; // increment x by 1 and store to y // compare x and y x == y; // evaluates to true or false // Demo of comparison operators and boolean type public class Comparison { public static void main(string [] args) { int grade = 87; System.out.println( grade>50 ); // set a = boolean that condition evaluates to boolean a = (grade == 100); System.out.println("Student earned 100% is " + a); Examples: boolean state; int i = 5; int j = 9; state = (i > j); state = (i == j); state = (i 3) <= j; state = (i!= j); - 8 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 9 of 11 OUTPUT Print: use print and println methods. println moves the cursor to the beginning of the next line after completing the print. Examples: System.out.print(x); //print the value of x System.out.println(x); //print the value of x followed by a //new line System.out.println( The result is + result); System.out.println( The sum of 2 + 3 is + 2 + 3); // prints The sum of 2 + 3 is 23 System.out.println( The sum of 2 + 3 is + (2 + 3)); // prints The sum of 2 + 3 is 5 Special characters: \n //newline \t //tab \b //backspace \ //double quote \\ //backslash Example: /* */ This is a printing demo. Shows special characters within a string public class PrintJava { public static void main(string [] args) { System.out.println("This\nwill start a new line"); System.out.println(3+"\n"+ 4 + "\non different lines"); System.out.println("first column\tsecond column"); System.out.println("with \"double quotes around it\""); System.out.println("directory c:\\cs603\\homework"); - 9 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 10 of 11 INPUT Using Scanner class: Use Scanner class to read from keyboard. Scanner a class for text input processing from keyboard, file, or string. To read input from the keyboard: a. Need to include the following line above the class definition import java.util.scanner; This statement tells Java to Make the Scanner class available to the program Find the Scanner class in a library of classes (i.e., Java package) named java.util b. Need to create an object of Scanner class inside the main method as follows: Scanner kb = new Scanner (System.in); Once a Scanner object has been created, a program can then use that object to read user input from the keyboard using methods of the Scanner class These methods are type-specific kb.nextint(); - returns an integer entered by the user. Skips all white space (space, tab, end-of-line characters) that appear before the integer. kb.nextdouble(); - double kb.nextboolean(); kb.next(); - returns the String value consisting of characters up to, but not including the next white space (or end of line). Essentially, reads one word, where word is a sequence of non-white space characters. kb.nextline(); - returns the String value consisting of characters up to, but not including the end of the current line. Unlike the other methods, does not skip the end-of-line character, instead treats it as the end of the line. int x = kb.nextint(); double y = kb.nextdouble(); String word = kb.next(); String line = kb.nextline(); Subtle point: The method nextline of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off. This can cause problems when combining it with different methods for reading from the keyboard such as nextint - 10 -
Handout 1 CS603 Object-Oriented Programming Fall 15 Page 11 of 11 Example: Given the code, Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); String s1 = keyboard.nextline(); String s2 = keyboard.nextline(); and user input, 2 Heads are better than 1 head. what are the values of n, s1, and s2? Answer: n will be set to 2, s1 will be equal to "", and s2 will be equal to "Heads are better than" Explanation: \n below denotes the invisible end of line character. Here s what the user input looks like 2\nHeads are better than\n1 head.\n If the following results were desired instead n equal to 2, s1 equal to "heads are better than", and s2 equal to "1 head" then an extra invocation of nextline() would be needed to get rid of the end of line character '\n'. Scanner keyboard = new Scanner(System.in); int n = keyboard.nextint(); keyboard.nextline(); // to get rid of \n after number String s1 = keyboard.nextline(); String s2 = keyboard.nextline(); This only happens when the program needs to read a new line with nextline() after using any other Scanner reading methods (next(), nextint(), nextdouble(), etc..) - 11 -