6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 Specific topics of the Java Language Related to This Class Classes and.

Slides:



Advertisements
Similar presentations
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
Advertisements

IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Java Syntax Primitive data types Operators Control statements.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Review Java.
Classes, Types and Objects Data Structures Chapter 1 Prof. Vidya Manian Dept. of Electrical and Comptuer Engineering ICOM 4035Java Programming BasicsECE,
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
JAVA 0. HAFTA Algorithms FOURTH EDITION Robert Sedgewick and Kevin Wayne Princeton University.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
CompSci 100E 2.1 Java Basics - Expressions  Literals  A literal is a constant value also called a self-defining term  Possibilities: o Object: null,
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Information and Computer Sciences University of Hawaii, Manoa
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Lecture 5: Some more Java!
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Starting JavaProgramming
Chapter 2: Basic Elements of Java
Fundamentals 2.
Expressions and Assignment
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming Language
In this class, we will cover:
Chap 2. Identifiers, Keywords, and Types
Problem 1 Given n, calculate 2n
Presentation transcript:

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 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)

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 2 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

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 3 How Classes Are Declared The syntax for a Java class definition: [ ] class [extends ] [implements,,…] { // class methods and instance variables definitions go here… }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 4 Example /Java/Gnome-Gnome.html

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 5 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.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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 6 Base Types (primitive type) Not objects booleanBoolean value: true or false (different from c++) char 16-bit Unicode character (different from c++) byte8-bit signed integer short16-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

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 7 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: = new ([param,param,…]); Example: myGnome = new Gnome();

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 8 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 Base TypeClass NameCreation ExampleAccess Example byteByten= new Byte((byte) 34);n.byteValue(); shortShortn= new Short((short) 100);n.shortValue(); intIntegern= new Integer(1045);n.intValue(); longLongn= new Long(10849L);n.longValue(); floatFloatn= new Float( 3.943F);n.floatValue(); doubleDoublen= new Double( 3.934);n.doubleValue();

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 9 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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 10 Instance Variables Instance variables must have a type, which can either be a base type or a class. Syntax for declaring an instance variable: [ ] [= ]; 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… }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 11 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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 12 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: ] ([params]) { // method body… } Example: public void renameGnome(String s) { name = s; // Reassign the name instance variable of this gnome }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 13 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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 14 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=?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 15 Another Example void f(Gnome a) { a. renameGnome (“newname”); } Gnome b = new Gnome(); // b. getRealName() returns “Rumple“ f(b); b. getRealName() returns ?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 16 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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 17 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”

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 18 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: /Gnome-Gnome.html /Gnome-Gnome.html

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 19 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.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 20 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: , F, 2.14E2 Character: ‘a’ or ‘?’ Special character constants: ‘\n’, ‘\t’,’\b’, ‘\r’, ‘\f’, ‘\\’, ‘\’’, ‘\”’ String literals: “ dogs all around ” or “ jump ”

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 21 The Assignment Operator “ = “ Syntax: = i=j=25; // works because “=“ operators are evaluated right-to-left.

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 22 Dot Operator “. ” Use dot operator to access the members of the object Syntax:. ([,,…] ); overn.cookDinner(food); Or. 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 can also be any expression that returns an object reference. Gnome g = new Gnome(); String buddyName = (g.gnome_buddy).name;

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 23 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 = ?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 24 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?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 25 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

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 26 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

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 27 Operational Assignment Operators Syntax: = ; This is equivalent to = ; i = 5; i += 5; i = ?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 28 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: / 4 % 3 = (5 + ((21 / 4) % 3)) = (5 + ( 5 % 3 )) = (5 + 2) = 7

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 29 Casting in Expressions change the type of a variable. Syntax: ( ) ;

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 30 Ordinary Casting Possible among all integer and floating types, may lose precision Possible among some class references double d1 = 3.2; double d2 = ; int i1 = (int) d1; // i1 has value 3 inti2 = (int) d2; // i2 has value 3 double d3 = (double) i2; // d3 has value 3.0

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 31 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;

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 32 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 iresult = i / d; // compilation error, loss of precision iresult = (int) i/d; // iresult is 0

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 33 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);

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 34 Control Flow – if/else Syntax if ( ) [else if ( ) ] [else ] Unlike C and C++, the expression in an if statement in Java must be a Boolean expression. if ( i = 5) //wrong

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 35 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?

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 36 Loops while ( ) for ([ ];[ ];[ ]) example: for(int i = 0; i < 100, i++) {...} do while ( )

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 37 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; }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 38 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; }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 39 The continue Statement Syntax: continue [ ]; 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; }

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 40 Arrays An array is a number collection of variables all of the same type. Index starts from 0..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

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 41 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( 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: ,15 (double,char,int).

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 42 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: Input an int: 209 Their sum is

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 43 Packages A set of related classes under a common subdirectory. Every file in a package starts with the line: package ; 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. ; package Project; import TA.Measures.Thermometer; import TA.Measures.Scale; or import TA.Measures.* public boolean Temperature(Thermometer thermometer, int temperature) {....}

6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 44 An Example Program CreditCard 01/Java/CreditCard-CreditCard.html 01/Java/CreditCard-CreditCard.html Test 01/Java/Test-CreditTest.html 01/Java/Test-CreditTest.html Output 01/Java/output2-credit.html 01/Java/output2-credit.html