CMT4001 -- Programming Software Applications
Week 2
Dr. Xiaohong Gao
TP B107, ext. 2252
Java Data Types and Operators
Contents
To become familiar with Java applications
To become familiar with variables in Java
To become familiar with Java primitive’s data types
To become familiar with arithmetic operators
A Simple Program
1 // Fig. 2.1: Welcome1.java
2 // A first program in Java34 public class Welcome1 { 5 public static void main( String args[])6 {7 System.out.println( "Welcome to Java
Programming!" );8 }
9 }
Welcome to Java Programming!
A Simple Program: Printing a Line of Text
1 // Fig. 2.1: Welcome1.java
// indicates the remainder of the line is a comment• Comments are ignored by the compiler• Use comments to document and describe code
Can also use multiple line comments: /* ... *//* This is a multiple
line comment. It can
be split over many lines */
Another line of comments that describes the programNote: line numbers are not part of the program; they are added for our reference
A Simple Program: Printing a Line of Text
3 A blank line•Blank lines and spaces make a program more readable•Blank lines, spaces, and tabs are known as whitespace •characters, and are ignored by the compiler
public class Welcome1 {
Begin a class definition for class Welcome1•Every Java program has at least one user-defined class•class keyword immediately followed by class name
–Keyword: words reserved for use by Java• Naming classes: capitalize every word
–SampleClassName
A Simple Program: Printing a Line of Text
public class Welcome1 {Name of class called identifier
•Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ )•Does not begin with a digit•Contains no spaces•Examples: Welcome1, $value, _value, button7•7button is invalid•Case sensitive (capitalization matters)
–a1 and A1 are differentFor now, use public keyword
•Certain details are not important now - mimic programs,• full discussions will come later
A Simple Program: Printing a Line of Text
public class Welcome1 { Saving files
• File name is class name and .java extension• Welcome1.java
Left brace• Begins body of every class• Right brace ends definition (line 9)
public static void main( String args[] )
Part of every Java application•Applications begin executing at main
• Parenthesis indicate main is a method• Java applications contain one or more methods
A Simple Program: Printing a Line of Text
5 public static void main( String args[] )• Exactly one method must be called main
Methods can perform tasks and return information• void means main returns no information• For now, mimic main's first line
6 {
Left brace begins body of method definition•Ended by right brace
A Simple Program: Printing a Line of Text
System.out.println( "Welcome to Java Programming!" );
Instructs computer to perform an action•Prints string of characters between double quotes
–String - series characters inside double quotes•White spaces in strings are not ignored by compiler
System.out - standard output object•Allows java to print to command window (i.e., MS-DOS prompt)
Method System.out.println displays a line of text•Argument inside parenthesis
Entire line known as a statement•All statements must end with a semicolon ;
A Simple Program: Printing a Line of Text
8 } Ends method definition
9 }
Ends class definitionSome programmers add comments to keep track of ending bracesLines 8 and 9 could be rewritten as:
8 } // end of the method main () 9 } // end of class Welcome1
Remember that the compiler ignores comments
A Simple Program
1 // Fig. 2.2: Welcome2.java
2 // Printing a line with multiple statements34 public class Welcome2 {
5 public static void main( String args[])6 {7 System.out.print ( "Welcome to Java);8 System.out.println(“Java programming”); 9 }
10 }System.out.print keeps the cursor on the
same line, so System.out.println continues
on the same line.
A Simple Program
Line numbers
1-2: Comments3: Blank4: Begin class Welcome25: Method main6: Begin main body7: Method System.out.print8: Method System.out.println9: end main10: end Welcome2
A Simple Program: Printing a Line of Text
Escape characters– Backslash ( \ )– Indicates that special characters are to be output
• Backslash combined with a character makes an escape sequence
• \n - newline• \t - tab
Usage– Can use in System.out.println or System.out.print to create new
lines• System.out.println( "Welcome\nto\nJava\nProgramming!" );
A Simple Program: Printing a Line of Text
1 // Fig. 2.3: Welcome3.java
2 // Printing multiple lines with just3 // a single statements45 public class Welcome3 {
6 public static void main( String args[])7 {8 System.out.print (“Welcome\9 \nto\nJava\nProgramming!”);10 } 11 }
Notice how a new line is output for
each \n escape sequence.
Welcometo
JavaProgramming!
Variables
A variable has three properties:
a memory location to store this value
the type of data stored in the memory location
the named used to refer to the memory location
Variables
The general syntax for declaring variables is:
<data type> <variables>
where variables is a sequence of identifiers separated by commas.
Example: int x; int y; or int x,y;
Variables
Variables – Variable names correspond to locations in the computer's memory– Every variable has a name, a type, a size and a value– Whenever a new value is placed into a variable it replaces (and
destroys) previous value – Reading variables from memory does not change them
Visual representation
number145
Data type
There are six numerical data types in Java:
• byte – integer• short –integer• int – integer• long –integer
• float – real• double - real
Example: int j, k, l; float numberOne, numberTwo; long bigInteger; double bigNumber;
Type Size Description
Integers
Real Numbers
Other Types
byte 8-bit Byte-length integershort 16-bit Short integerint 32-bit Integerlong 64-bit Long integer
floatdouble
32-bit64-bit
Single-precision floating-pointDouble-precision floating-point
charboolean
16-bit Unicode character
true or falseA single characterA boolean value(true or false)
Java’s primitive data types
Variables
Assignment statement
<variable> = <expression>;
Examples:
firstNumber = 234;
sum = firstNumber+ secondNumber;
solution = x*x-2*x+1;
Variables
int firstNumber,secondNumber;A after A is executed
firstNumber = 234;
secondNumber = 87;
firstNumber
secondNumber
The variables firstNumber and secondNumber are declared and set
in the memory
Variables
int firstNumber,secondNumber; after B is executed
firstNumber = 234;
secondNumber = 87;B
firstNumber
secondNumber
234
87
Values are assigned to thevariables firstNumber and secondNumber
Quick Check
Why are the following declarations all invalid?
int a, b, a;
float x, int;
float w, int x;
bigNumber double;
Another Java Application: Adding Integers
int number1; // first number to add int number2; // second number to add sum; // sum of number1 and number2
Declares variables number1, number2, and sum of type int•int can hold integer values (whole numbers): i.e., 0, -4, 97•Data types float and double can hold decimal numbers
Another Java Application: Adding Integers
// add the numbers
sum = number1 + number2;
Assignment statement
•First calculates sum of number1 and number2 (right hand side)•Next, uses assignment operator = to assign result to variable sum•Read as: sum gets the value of number1 + number2
Another Java Application: Adding Integers
System.out.printl(“The sum is”+ sum);
"The sum is " + sum•Uses the operator + to "add" the string literal "The sum is" and sum•Allows concatenation of a String and another data type
–Results in a new string•If sum contains 117, then "The sum is " + sum results in the new string "The sum is 117"•Note the space in "The sum is "
Arithmetic
Arithmetic calculations are used in most programs–Use * for multiplication and / for division, +, -
•No operator for exponentiation •Integer division truncates remainder7 / 5 evaluates to 1
–Modulus operator % returns the remainder 7 % 5 evaluates to 2
Operator precedence–Some arithmetic operators act before others (i.e., multiplication before addition)
•Use parenthesis when needed–Example: Find the average of three variables a, b and c
•Do not use: a + b + c / 3 •Use: (a + b + c ) / 3
Arithmetic
Operator(s) Operation(s) Order of evaluation (precedence)
() Parentheses Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses “on the same level” (i.e., not nested), they are evaluated left to right.
*, /, or % Multiplication Division Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Decision Making: Equality and Relational Operators
Standard algebraic equality operator or relational operator
Java equality or relational operator
Example of Java condition
Meaning of Java condition
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or equal to y
<= x <= y x is less than or equal to y
Equality operators
= == x == y x is equal to y
!= x != y x is not equal to y
<_
>_
=
Summary
• Java applications
• Variables in Java
• Java primitive’s data types
• Arithmetic operators