Download pptx

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CMPE212 – Section 001 - Reminders
• Course Web Site:
http://research.cs.queensu.ca/home/cmpe212
• Please fill out the lab section quiz in onQ.
• Labs start this week.
• Exercises 1 and 3 are good preparation for
assignment 1.
Winter 2017
CMPE212 - Prof. McLeod
1
Today
• Class structure syntax, cont.
• Java vs. C…
• Java Expressions.
Winter 2017
CMPE212 - Prof. McLeod
2
OOP in Java
• A class or “object definition” or an “object”, consists of
instance variables and/or methods.
• By convention, instance variables are all declared before
the methods:
public class ShowStructure {
// instance variables or “attributes” here
// methods here
} // end class ShowStructure
Winter 2017
CMPE212 - Prof. McLeod
3
Attribute Declaration
• Syntax:
[private|public] [static] [final] type
attributeName [= literalValue];
• Note that the type part is not optional – this is why
java is a “declarative” language.
• And, a variable cannot change its type later
(“static typing”).
• You cannot use a variable unless you have
declared it first.
Winter 2017
CMPE212 - Prof. McLeod
4
Method Declaration (a “Header”)
• The syntax for simple method declaration:
[private|public] [static] [final] returnType
methodName ([parameterList]) {…}
• If main invokes methods or uses attributes in the
same class as itself then those attributes and
methods must also be declared static.
Winter 2017
CMPE212 - Prof. McLeod
5
Methods - the return Statement
• Unless the return type is void, the method must
contain at least one return statement. A void
method can also use a return statement without
anything after it, as a means of terminating the
method.
• A method always stops (terminates) when a
return statement is encountered.
• Syntax:
return [literal|expression];
Winter 2017
CMPE212 - Prof. McLeod
6
The return Statement - Cont.
• The type of “literal|expression” must match
the return type specified in the method declaration
statement.
Winter 2017
CMPE212 - Prof. McLeod
7
Method Examples
public void printHello() {
System.out.println(“Hello”);
} // end printHello
public void printHelloName(String yourName) {
System.out.println(“Hello “ + yourName);
} // end printHelloName
public void printAvg(int a, int b) {
System.out.println((a + b) / 2.0);
} // end printAvg
Winter 2017
CMPE212 - Prof. McLeod
8
Method Examples - Cont.
public double average(double a, double b) {
return (a + b) / 2;
} // end average
public int lowest(int a, int b) {
if (a <= b)
return a;
else
Does this have to be
return b;
here?
} // end lowest
Winter 2017
CMPE212 - Prof. McLeod
9
Attribute Examples
public double aVar;
public int aNum = 100;
private String hello = “Hello”;
Winter 2017
CMPE212 - Prof. McLeod
10
static Again
• If static methods are using attributes in the
same class, then those attributes must also be
static.
• Don’t worry the pre-compiler will also remind you!
Winter 2017
CMPE212 - Prof. McLeod
11
Example: A Simple Class
public class Simple {
public static int aNum = 100;
public static int sumNums(int num1, int num2) {
return num1 + num2;
}
public static void main(String[] args) {
int anotherNum = 200;
System.out.println(sumNums(aNum, anotherNum));
}
}
Winter 2017
CMPE212 - Prof. McLeod
12
Another Simple Class
// An example of the use of varargs (the ellipse...)
// Also a for each loop!
public class AnotherSimple {
public static int sumNums(int... nums) {
int sum = 0;
for (int num : nums)
sum += num;
return sum;
}
public static void main(String[] args) {
System.out.println(sumNums(2, 5, 7, 10, 3));
}
} // end AnotherSimple class
Winter 2017
CMPE212 - Prof. McLeod
13
Java versus C
• What is the main difference between C and Java?
• Java code must be contained within an Object.
Creating a program is now all about defining
Objects (or classes).
• In Java, you cannot have any code outside a
class definition.
• The only code you can have outside a method
definition are class attribute declarations.
Winter 2017
CMPE212 - Prof. McLeod
14
Java versus C, Cont.
(Java code examples in white boxes)
• What Java has (and C does not!):
• A class definition line.
• All code (methods and attributes) must be contained
within a class (within the { … } brackets).
• The class is saved in a text source code file called
“ResistorCodes.java”.
• A class is an Object, and an Object is defined in a
class.
Winter 2017
CMPE212 - Prof. McLeod
15
Java versus C, Cont.
• C has #include, Java has import:
• C has function prototypes, Java does not.
• C has global variables, Java does not.
• C has functions, Java has methods (what is the
difference?)
• C has a main() function, Java has a main
method:
Winter 2017
CMPE212 - Prof. McLeod
16
Java versus C, Cont.
• Some stuff is the same:
•
•
•
•
•
{ } used to delineate methods.
; at end of line.
// for in-line comments.
String literal enclosed in " ".
( ) contain arguments and parameter lists and
can be used to establish precedence in
expressions.
• Space used to delineate elements of expressions.
Winter 2017
CMPE212 - Prof. McLeod
17
What Makes an Expression?
• What are all the components available to a
programmer that can be used to put a line of code
together?
–
–
–
–
–
–
Variables
Literal Values
Keywords
Operators
Method Invocations
Punctuation
Winter 2017
CMPE212 - Prof. McLeod
18
Variable Declcaration
• Variables
– Both C and Java are declarative languages.
– Scope rules are the same.
– Syntax of simple variable declaration is the same.
– A variable is “statically typed” in both languages. In
other words, once a variable is typed, in cannot be
changed to another type.
Winter 2017
CMPE212 - Prof. McLeod
19
Primitive Types in Java
• Both C and Java have:
– char
– short
– int
– long
– float
– double
• Only Java has:
– boolean
– byte
Winter 2017
CMPE212 - Prof. McLeod
20
Primitive Types?
• What is a primitive type anyways?
• Everything else in Java is an Object.
• A variable declared as one of the types shown on
the previous slide is not an Object.
• Why does Java have primitive types?
Winter 2017
CMPE212 - Prof. McLeod
21
Integer Primitive Types
• byte, short, int, long
• For byte, from -128 to 127, inclusive (1 byte).
• For short, from -32768 to 32767, inclusive (2
bytes).
• For int, from -2147483648 to 2147483647,
inclusive (4 bytes).
• For long, from -9223372036854775808 to
9223372036854775807, inclusive (8 bytes).
• A “byte” is 8 bits, where a “bit” is either 1 or 0.
Winter 2017
CMPE212 - Prof. McLeod
22
Aside - Number Ranges
• Where do these min and max numbers come
from?
• Memory limitations and the system used by Java
(two’s complement) to store numbers determines
the actual numbers.
• The Wrapper classes can be used to provide the
values - for example:
Integer.MAX_VALUE // returns the value 2147483647
Winter 2017
CMPE212 - Prof. McLeod
23
Numeric Overflow?
• Do integers overflow in Java and what is the
behaviour?
• Do we get an error or a warning?
• See FactorialDemo.java
Winter 2017
CMPE212 - Prof. McLeod
24
Real Primitive Types
• Also called “Floating Point” Types:
• float, double
• For float, (4 bytes) roughly ±1.4 x 10-38 to ±3.4
x 1038 to 7 significant digits.
• For double, (8 bytes) roughly ±4.9 x 10-308 to
±1.7 x 10308 to 15 significant digits.
Winter 2017
CMPE212 - Prof. McLeod
25
Character Primitive Type
• char
• from '\u0000' to '\uffff' inclusive, that is,
from 0 to 65535 (base 10) or 0 to ffff (base 16, or
“hexadecimal”). A variable of the “char” type
represents a Unicode character. Can also be
represented as ‘a’ or ‘8’, etc.
Winter 2017
CMPE212 - Prof. McLeod
26
Aside - Unicode Characters
• See DisplayUnicode.java
– Shows a small slice of the available characters.
Winter 2017
CMPE212 - Prof. McLeod
27
Boolean Primitive Type
• boolean is either true or false.
Winter 2017
CMPE212 - Prof. McLeod
28
String Objects
• String’s are not primitive data types, but are Objects.
• A String is declared in the same way as a primitive type
using the keyword: String.
• You can also instantiate a String as you would a normal
object. The statement:
String message = “Hello World!”;
aliases the object message to the String literal object
“Hello World!”, which is the same as saying:
String message = new String(“Hello World!”);
Winter 2017
CMPE212 - Prof. McLeod
29
Legal Variable Names
• Java names may contain any number of letters,
numbers and underscore (“_”) characters, but
they must begin with a letter.
• Standard Java Naming Conventions:
– Names beginning with lowercase letters are variables
or methods.
– Names beginning with uppercase letters are class
names.
– Successive words within a name are capitalized
(“CamelCase”).
– Names in all capital letters are constants.
Winter 2017
CMPE212 - Prof. McLeod
30
Literal Values
• Integers, for example:
12
-142
0
333444891
• If you write these kinds of numbers into your
program, Java will assume them to be of type
“int”, and store them accordingly.
• If you want them to be of type “long”, then you
must append a “L” to the number:
43L
Winter 2017
9999983475L
CMPE212 - Prof. McLeod
-22233487L
31
Binary, Octal and Hex Literals
• Use the prefix 0b (or 0B) in front of the numbers to
get a binary literal.
• Octal – just use 0
• Hex use 0x
• You can use the underscore _ in-between digits,
to aid in visualizing the number.
• System.out.println(), by default displays the
numbers in base 10.
• Use printf to show the numbers in another
codex or base. (See Part 2 of Exercise 1.)
Winter 2017
CMPE212 - Prof. McLeod
32
Binary, Octal and Hex Literals, Cont.
• Summary examples of other literals:
–
–
–
–
binary:
binary with underscores:
octal:
hex:
Winter 2017
0b111010111
0b111_010_111
07321023
0xab10fc
CMPE212 - Prof. McLeod
33
Literal Values - Cont.
• Real or “Floating Point” numbers, for example:
4.5
-1.0
3.457E-10
-3.4E45
• These literals will be assumed to be of the
“double” type.
• If you want them to be stored as “float” types,
append an “F”:
3.456F
Winter 2017
5.678E-10F
CMPE212 - Prof. McLeod
-321.0F
34
Literal Values - Cont.
• char literals:
‘A’
‘5’
‘\u0032’
• boolean literals:
true
false
• String literals:
“Hello there!”
Winter 2017
“456.7”
CMPE212 - Prof. McLeod
“West of North”
35
Variable Declaration - Cont.
• int and double variables initially are given a
value of zero unless they are initialized to a value.
• Java may prevent you from using variables that
are not initialized.
• So, it is often good practice to initialize your
variables before use, for example:
int numDaysInYear = 365;
double avgNumDaysInYear = 365.25;
String greetingLine = “Hello there!”;
long counter = 0;
Winter 2017
CMPE212 - Prof. McLeod
36
Constants
• The Java keyword, final can be used to make
sure a variable value is no longer “variable”.
• It becomes a constant, because Java will not
allow your program to change its value once it has
been declared:
final int NUM_DAYS_IN_YEAR = 365;
final double MM_PER_INCH = 25.4;
Winter 2017
CMPE212 - Prof. McLeod
37
(Constants in C)
• You cannot define constants this way in C.
• Instead you used symbolic constants, which are
not the same thing.
• Java does not have these ugly things…
Winter 2017
CMPE212 - Prof. McLeod
38