Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

JavaClass Lecture2

1. Expressions are evaluated based on the types of the operands, not their values. Since 3 and 4 are integers, their division results in an integer (0), which is then cast to a float and assigned to x. 2. To get a float result, one of the operands must be a float. For example, 3.0/4 or 3/4.0 would result in 0.75 being assigned to x. 3. Explicit type casting can be used to convert values between types. For example (int)3.7 assigns the value 3 to an int by truncating the decimal.

Uploaded by

api-3751900
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

JavaClass Lecture2

1. Expressions are evaluated based on the types of the operands, not their values. Since 3 and 4 are integers, their division results in an integer (0), which is then cast to a float and assigned to x. 2. To get a float result, one of the operands must be a float. For example, 3.0/4 or 3/4.0 would result in 0.75 being assigned to x. 3. Explicit type casting can be used to convert values between types. For example (int)3.7 assigns the value 3 to an int by truncating the decimal.

Uploaded by

api-3751900
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Introduction to Java

Lecture 2
Expressions are like C
• Assignment statements mostly look like those in C; you
can use =, +=, *= etc.
• Arithmetic uses the familiar + - * / %
• Java also has ++ and --
• Java has boolean operators && || !
• Java has comparisons < <= == != >= >
• Java does not have pointers or pointer arithmetic

15 March 2007 Java : Lecture 2 2


Scoping
• As in C/C++, scope is determined by the placement of curly
braces {}.
• A variable defined within a scope is available only to the
end of that scope.
{ int x = 12;
/* only x available */
This is ok in C/C++ but not in Java.
{ int q = 96;
/* both x and q available */
} { int x = 12;
/* only x available */ { int x = 96; /* illegal */
/* q “out of scope” */ }
} }
15 March 2007 Java : Lecture 2 3
Control statements are like C
• if (x < y) smaller = x;
• if (x < y){ smaller=x;sum += x;}
else { smaller = y; sum += y; }
• while (x < y) { y = y - x; }
• do { y = y - x; } while (x < y)
• for (int i = 0; i < max; i++)
sum += i;

• BUT: conditions must be boolean !


15 March 2007 Java : Lecture 2 4
Control statements
switch (n + 1) {
case 0: m = n - 1; break;
case 1: m = n + 1;
case 3: m = m * n; break;
default: m = -n; break;
}

• Java also introduces the try statement,


about which more later
15 March 2007 Java : Lecture 2 5
Arithmetic
• Operators: +, -, /, * , %
• The precedence of operators and parentheses is the
same as in algebra
• m % n means the remainder when m is divided by
n (for example, 17 % 5 is 2; 2 % 8 is 2)
• % has the same rank as / and *
• Same-rank binary operators are performed in order
from left to right

15 March 2007 Java : Lecture 2 6


Arithmetic
• The type of the result is determined by the
types of the operands, not their values; this
rule applies to all intermediate results in
expressions.
• If one operand is an int and another is a
double, the result is a double; if both
operands are ints, the result is an int.

15 March 2007 Java : Lecture 2 7


Arithmetic

• Caution: if a and b are ints, then a / b is


truncated to an int…
17 / 5 gives 3
3 / 4 gives 0
• …even if you assign the result to a double:
double ratio = 2 / 3;
The double type of the
result doesn’t help: ratio
still gets the value 0.0.
15 March 2007 Java : Lecture 2 8
Arithmetic
• To get the correct double result, use double
constants or the cast operator:
double ratio = 2.0 / 3;
double ratio = 2 / 3.0;
int m = ..., n = ...;
double factor = (double)m / (double)n;
double factor = (double)m / n; Casts
double r2 = n / 2.0;

15 March 2007 Java : Lecture 2 9


Arithmetic
• Caution: the range for ints is from
-231 to 231-1 (about -2·109 to 2·109)
• Overflow is not detected by the Java
compiler or interpreter:

15 March 2007 Java : Lecture 2 10


Arithmetic
• Compound assignment • Increment and
operators: decrement operators:

a = a + b; a += b; a = a + 1; a++;
a = a - b; a -= b; a = a - 1; a--;
a = a * b; a *= b;
a = a / b; a /= b;
a = a % b; a %= b;

15 March 2007 Java : Lecture 2 11


More About Java
• It is an error for a public class to have a file
name that is not identical to the class name (plus
the .java extension) in terms of both spelling and
capitalization.
• Choosing meaningful variable names helps a
program to be self-documenting (i.e., one can
understand the program simply by reading it rather
than by reading manuals or viewing an excessive
number of comments).
15 March 2007 Java : Lecture 2 12
Java isn't C!
• In C, almost everything is in functions
• In Java, almost everything is in classes
• There is often only one class per file
• There must be only one public class per file
• The file name must be the same as the name
of that public class, but with a .java
extension
15 March 2007 Java : Lecture 2 13
Java program layout
• A typical Java file looks like:
import java.awt.*;
import java.util.*;
public class SomethingOrOther {
// object definitions go here
. . .
}
This must be in a file named SomethingOrOther.java !

15 March 2007 Java : Lecture 2 14


Declaring Arrays
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled
myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line

15 March 2007 Java : Lecture 2 15


Assigning Values
• refer to the array elements by index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
• can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};

15 March 2007 Java : Lecture 2 16


Iterating Through Arrays
• for loops are useful when dealing with arrays:

for(int i = 0;i < myArray.length;


i++)
{
myArray[i] = getsomevalue();
}

15 March 2007 Java : Lecture 2 17


Name conventions
• Java is case-sensitive; maxval, maxVal and MaxVal
are three different names
• Class names begin with a capital letter, Class names
should be nouns.Try to keep your class names simple
and descriptive; class Raster , class Employee
• Use whole words-avoid acronyms and abbreviations
• Methods should be verbs, in mixed case with the first
letter lowercase, with the first letter of each internal
word capitalized. run() , runFast()

15 March 2007 Java : Lecture 2 18


Name conventions
• Variable name must begin with a lowercase letter
• Subsequent words are capitalized: theBigOne
• Underscores are not used in class, method, variable
names
• The names of variables declared class constants and
of ANSI constants should be all uppercase with
words separated by underscores ("_"). final int
MIN_WIDTH = 4
• These are very strong conventions!

15 March 2007 Java : Lecture 2 19


Strings
• String is not a primitive data type
• Strings work like any other objects, with two
exceptions:
 Strings in double quotes are recognized as literal
constants
 + and += concatenate strings (or a string and a number
or an object, which is converted into a string)

"Catch " + 22 "Catch 22"

15 March 2007 Java : Lecture 2 20


From Numbers to Strings
• The easiest way to convert x into a string is to concatenate
x with an empty string:
String s = x + "";

'A' "A"
123 "123"
-1 "-1"
.1 "0.1"
3.14 "3.14"
Math.PI "3.141592653589793"
• The same rules apply to System.out.print(x)
15 March 2007 Java : Lecture 2 21
Type Casting
Which of the following are legal?
• int x = 3.5;
Illegal: 3.5 is not an int
• float x = 3;
Legal: 3 is an int, which is also a float
• long i = 3;
Legal: 3 is an int, which is also a long
• byte x = 155;
Illlegal: 155 is to big to be a byte (> 127)
• double d = 3.14159F;
Legal: 3.14159F is a float, which is also a double
15 March 2007 Java : Lecture 2 22
What is “Type Casting”?
• Type casting: automatic conversion of
values from one type to another
e.g. int → double
float → double
int → long
• Type casts can be:
– Implicit: performed automatically
– Explicit: programmed by developer

15 March 2007 Java : Lecture 2 23


Implicit Type Casting in Java
• Hierarchy of primitive numerical types
double
float
long
int
short
byte
• Idea
– Higher types have more precision
– Lower types are “subsets” of higher types
• Java only performs implicit upcasts (casting from lower to higher
type)
e.g. int → double
float → double
int → byte

15 March 2007 Java : Lecture 2 24


Explicit Type Casting in Java
• To explicitly cast a value to a type t, use
(<t>) value
int x = (int)3.7;
– Assigns value 3 to x
– Reason: (int) operator converts double to int by
truncation (chopping off
– decimal) when double is small enough
– This is an example of downcasting
byte bt = (byte) 200;
– Assigns value -56 to bt
– Reason: (byte) operator “wraps around” values that are
too big
15 March 2007 Java : Lecture 2 25
Mixed Expressions
• What is result of
float x = 3 / 4;
– x assigned value 0.0F
– Why?
• 3, 4 are ints
• So integer / operation is used, yielding 0, before upcasting is performed
• To get floating point result, use explicit casting
float x = (float) 3 / (float) 4;
– Assigns x the value 0.75F
• Can also do following
float x = (float) 3 / 4;
– Why?
– (float) 3 returns a value type float (3.0F)
– 4 is an int
– In this case, Java compiler uses upcasting on “lower” type (here, int) to
– obtain values in same type before computing operation

15 March 2007 Java : Lecture 2 26

You might also like