Chapter 2 Java Basic. Outline 1. Defining of Classes 2. Constructors( 构造器 ) 3. The"this"Keyword 4. The"static"Keyword 5. Lifetimes of Variables (变量的生存期)

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Programming Languages and Paradigms The C Programming Language.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
HistCite 结果分析示例 罗昭锋. By:SC 可能原因:文献年度过窄,少有相互引用.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
线性代数习题课 吉林大学 术洪亮 第一讲 行 列 式 前面我们已经学习了关 于行列式的概念和一些基本 理论,其主要内容可概括为:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
第 3 章 控制流分析 内容概述 – 定义一个函数式编程语言,变量可以指称函数 – 以 dynamic dispatch problem 为例(作为参数的 函数被调用时,究竟执行的是哪个函数) – 规范该控制流分析问题,定义什么是可接受的控 制流分析 – 定义可接受分析在语义模型上的可靠性 – 讨论分析算法.
编译原理总结. 基本概念  编译器 、解释器  编译过程 、各过程的功能  编译器在程序执行过程中的作用  编译器的实现途径.
 符号表  标识符的作用: 声明部分:定义了各种对象及对应的属性和 使用规则。 程序体:对所定义的对象进行各种操作。 $ididname IdnameAttributeIR  必要性 Token : 新表-符号表(种类、类型等信息):
Introduction to Programming G51PRG University of Nottingham Revision 2 Essam Eliwa.
The switch Statement, DecimalFormat, and Introduction to Looping
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Java Programming, Second Edition Chapter Four Advanced Object Concepts.
Java 程序设计 Java Programming Fall, Contents for Today Java Program Structure  How to Compile a Java Program  How to Run a Java Program Environment.
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CSC Java Programming, Fall, 2008 Week 2: Java Data Types, Control Constructs, and their C++ counterparts, September 4.
Sahar Mosleh California State University San MarcosPage 1 A for loop can contain multiple initialization actions separated with commas Caution must be.
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.
BUILDING JAVA PROGRAMS CHAPTER 2 PRIMITIVE DATA TYPES AND OPERATIONS.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
Slides prepared by Rose Williams, Binghamton University Chapter 5 Defining Classes II.
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.
项目七: PLC 功能指令应用 带进位循环左移指令 XXXXX. 项目七: PLC 功能指令应用 FX2 系列可编程控制器移位控制指令有移位、循环移位、字移位 及先进先出 FIFO 指令等 10 条指令。 带进位循环右移指令 RCR 带进位循环左移指令 RCL 字右移位指令 WSFR 先入先出读出指令.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
1 Operations Making Things Happen (Chap. 3) Expressions.
Variables, Primitives, and Objects A Visual Learner’s Guide.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
EC 营客通产品操作(九) EC 营客通产品操作(九) 400 电话 400 电话. 400 电话有助于提升企业形象,无论企业地址变更、机构 变化、人员变动,联系方式永远不变。且在 EC 上申请的 400 电话可以在 EC 平台上进行统一的 400 电话接听及 400 电话客服的管理。
CSC 212 Object-Oriented Programming and Java Part 2.
Java Programming, Second Edition Chapter Two Using Data Within a Program.
COMP Primitive and Class Types Yi Hong May 14, 2015.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 1 Java Programming Review. Introduction Java is platform-independent, meaning that you can write a program once and run it anywhere. Java programs.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chad’s C++ Tutorial Demo Outline. 1. What is C++? C++ is an object-oriented programming (OOP) language that is viewed by many as the best language for.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Topics introduced today (these topics would be covered in more detail in later classes) – Primitive Data types Variables Methods “for” loop “if-else” statement.
C++ Lesson 1.
JAVA MULTIPLE CHOICE QUESTION.
Chapter 7 User-Defined Methods.
The switch Statement, and Introduction to Looping
Java Primer 1: Types, Classes and Operators
User-Defined Functions
Chapter 2.
Chapter 2 Variables.
Expressions and Assignment
The System.exit() Method
Java Programming Language
Just Enough Java 17-May-19.
Problem 1 Given n, calculate 2n
Presentation transcript:

Chapter 2 Java Basic

Outline 1. Defining of Classes 2. Constructors( 构造器 ) 3. The"this"Keyword 4. The"static"Keyword 5. Lifetimes of Variables (变量的生存期) 6. Primitive Types( 基本类型 ) 7. Conditionals( 条件语句 ) 8. Objects AND Methods 9. LOOPS (循环语句)

3 1. Defining Classes Fields are variables stored in objects. Fields are used to store data. Difference between Fields and Methods? Fields never have parameters, and no parentheses( 圆括号 ) appear after them. Methods perform actions on the objects.

4 1. Defining Classes A class definition for the Human class. class Human{ // fields public int age;//The Human’s age (an integer). public String name;//The Human’s name. // methods public void introduce(){ System.out.println("I’m "+name+" and I’m "+age+" years old."); }

5 1. Defining Classes Human kayla=new Human();//Create kayla. kayla.age=12;//Set kayla’s fields. kayla.name="Kayla";

6 1. Defining Classes Question : What’s the output? kayla.introduce();//Have kayla introduce herself. The output is: I’m Kayla and I’m 12 years old.

7 1. Defining Classes If we want to mix two or more objects, we can class Human{ //Include all the stuff from the previous definition of Human here. // … public void copy(Human original){ age=original.age; name=original.name; } 在 Java 中,当前类可以接受和处理当前类的对象 NOTE

8 2. Constructors( 构造器 ) Code to initialize a new object class Human{ //… public Human(String givenName)// same name as class { age=12; name=givenName; } What’s the return object of contructors?

2. Constructors 缺省的构造器 If you write your own Human constructor, even if it takes parameters, the default ( 缺省的 )constructor goes away. If you want to have the default constructor and another constructor, you must define both explicitly (显式). // no constructor class C1{ } // one constructor class C2{ public C2(int k){} } C1 c1= new C1();// OK C2 c2= new C2();// compile error

2. Constructors Override the default constructor (覆盖了缺省的 控制器) class Human{ public Human(){ age=0; name="Untitled"; }

3. The"this"Keyword Use “this” in default constructor class Human{ //Include all the stuff from the previous definitions here. public Human(){ this.age=0;// age = 0 is also ok this.name=“Untitled”; } In this case, “this ” is optional( 选填项 ). 反义词: Compulsory 必选的

3. The"this"Keyword Use “this” in another method public void change (int age)// have priority against fields { String name="Chang"; // name is a local variable this.age=age; this.name=name;// use “this” to refer to object’s fields } If the parameters or local variables of a method have the same name as the fields of an object, then the former have priority, and the "this“ keyword is needed to refer to the object’s fields.

3. The"this"Keyword Execution of change() method kayla this 12 age name Kayla 8 age name Chang Parameters & local variables of change() Before kayla this 8 age name Kayla 8 age name Chang Parameters & local variables of change()After

3. The"this"Keyword You CANNOT change the value of"this"! Such as “this=kayla ” What’s the result of this mistake? A compile-time error.

4. The"static"Keyword A static field is a single variable shared by a whole class of objects; its value does not vary from object to object. Object variables or static fields (class variables)? How could we count the number of Human objects?

4. The"static"Keyword A good solution class Human{ public static int numberOfHumans; public int age; public String name; public Human(){ numberOfHumans++;//The constructor increments //the number by one. } int kids=Human.numberOfHumans/4; //Good. //This works too, but has nothing to do //with kayla specifically.Don’t do this;it’s bad (confusing)style. int kids=kayla.numberOfHumans/4;

4. The"static"Keyword Methods can be static too class Human{... public static void printHumans(){ System.out.println(numberOfHumans); } In a static method, THERE IS NO "this"!

5. Lifetimes of Variables ( 变量 ) -A local variable (declared in a method) is gone forever as soon as the method in which it ’ s declared finishes executing. (If it references an object, the object might continue to exist, though.) -An instance variable (non-static field) lasts as long as the object exists. -An object lasts as long as there ’ s a reference to it. -A class variable (static field) lasts as long as the program runs.

6. PRIMITIVE TYPES( 基本类型 ) Not all variables are references to objects. Some variables are primitive types. byte 8-bit -128…127 Range short 16-bit …32767 ….. int 32-bit … ….. long 64-bit …..

6. PRIMITIVE TYPES double 64-bit Range float 32-bit ± E+38 (6~7 significant digits) ….. boolean 1-bit true or false char 16-bit Unicode Character Set ….. ± E+308 (15 significant digits) …..

6. PRIMITIVE TYPES Object types vs Primitive types Object types Primitive types Variable contains a referencevalue How defined?class definitionbuilt into Java How created?"new" "6", "3.4" , "true" How initialized?constructor default (usually zero) How used?methodsoperators ("+", "*", etc.)

6. PRIMITIVE TYPES Operations on int, long, short, and byte types. -x x * y x + y x / y <-- rounds toward zero (drops the remainder). x - y x % y <-- calculates the remainder of x / y. Except for “%”, these operations are also available (适 用于) for doubles and floats.

6. PRIMITIVE TYPES More operations in java.lang library the Math class - the Math class. x = Math.abs(y); // Absolute value. Also see Math.sqrt, Math.sin, etc. - the Integer class. int x = Integer.parseInt("1984"); // Convert a string to a number. - the Double class. double d = Double.parseDouble("3.14");

6. PRIMITIVE TYPES Converting types: integers can be assigned to variables of longer types. int i = 43; long k = 43L; k = i; // Okay, because longs are a superset of ints. i = k; // Compiler ERROR. i = (int) k; // Okay. The string “(int)” is called a cast( 转换 ), and it casts the long into an int. Integers can be directly assigned to floating-point variables, but the reverse requires a cast.

7. CONDITIONALS An “if” statement uses a boolean expression to decide whether to execute a set of statements. The forms are : Form 1 if (boolValue) { statements; } Form 1 if (boolValue) { statements1; } else{ statements2; } Form 2 Form 3 if (boolValue1) { statements1; } else if ( boolValue2 ) { statements2; } else{ statements3 ; } Clauses can be nested (嵌套) and daisy-chained (多路选择)

8. OBJECTS AND METHODS String s1;//Step 1:declare a String variable. s1=new String();//Step 2:assign it a value:a new empty string. String s2=new String();//Steps 1&2 combined. s1 〝〞 s2 〝〞 We get … s1="Yow!";//Construct a new String;make s1 a reference to it. s2=s1;//Assign s2 the value of s1. s1 Yow! s2

What if we want to have a copy of the object? 8. OBJECTS AND METHODS s2=new String(s1);//Construct a copy of s1;make s2 a reference to it. s1 Yow! s2 Yow! They refer to two different, but identical,objects.

8. OBJECTS AND METHODS //Construct a copy of s1;make s2 a reference to it. s2=new String(s1); s1 Yow! s2 Yow! -Java looks inside the variable s1 to see where it’s pointing. -Java follows the pointer to the String object. -Java reads at the characters stored in that String object. -Java creates a new String object that stores a copy of those characters. -Java makes s2 reference the new String object. 这行代码被执行时,内存里发生了什么?

Three String constructors: 8. OBJECTS AND METHODS (1)new String() constructs an empty string , it’s a string, but it contains no characters. (2)"cs 4" constructs a string containing the characters " cs 4 ". (3) new String(s1) takes a parameter s1. Then it makes a copy of the object that s1 references.

Some other methods of String s2=s1.toUppercase();//Create a string like s1, but in all upper case. String s3=s2.concat ("!!");//Also written:s3=s2+"!!"; String s4="*".concat (s2).concat ("*");//Also written:s4="*"+s1+"*"; s2 YOW! s3 YOW!!! s4 *YOW!* 8. OBJECTS AND METHODS An important fact: When Java executed the line s2=s1.toUppercase(); the String object "Yow!“ did not change. Instead, s2 itself changed to reference a new object. s1 Yow!

Strings are immutable (无法更改) 8. OBJECTS AND METHODS Once they’ve been constructed, their contents (内容) never change. If you want to change a String object, you’ve got to create a brand new String object that reflects the changes you want. This is not true for all objects in Java Most Java objects let you change their contents.

9.LOOPs (循环语句) “while” “for” “do” “break” “continue” Like an"if"statement, but the body of the statement is executed repeatedly, as long as the condition remains true. A convenient shorthand that can be used to write some"while" loops in a more compact way. Has just one difference from a"while"loop.If Java reaches a"do"loop, it_always_executes the loop body at least once. A"break"statement immediately exits the innermost loop or"switch"statement enclosing the"break", and continues execution at the code following the loop or"switch". (1)It only applies to loops; (2)It doesn’t exit the loop; it jumps past the end of the loop body, but it’s still inside the loop.

33 Assignment Homework: 每周抄写 不少于 20 个专业相关的单词, 要求有例句,音标,无重复。每周学委 收齐后上交,算平时成绩。

34 The End