Professional Documents
Culture Documents
An Introduction
Agenda
Fundamentals Operators Flow Controls
Outline
Java Source File Structure Java Keywords Identifiers Literals Variables and Data Types Variable Declaration and Initialization Operators Primitive Casting Flow Controls
Objectives
At the end of this section, you should be able to: Recognize and create correctly constructed source code Recognize and create correctly constructed declarations Distinguish between legal and illegal identifiers Describe all the primitive data types and the ranges of the integral data types Recognize correctly formatted data types Learn to properly declare and initialize variables Understand the contents of the argument list of an applications main() method
Objectives (continued)
Operators:
Learn to use:
Unary operators Arithmetic operators String operators Relational operators Conditional operators Logical operators Assignment operators
Be familiar with object, shift and bitwise operators Identify the order of evaluation and change its precedence Learn how to cast primitive data types
Confidential Mr. Anuj
5
Objectives (continued)
Flow Controls:
Learn syntax and correct use of:
if-else() statement switch() statement while() statement do-while() statement for() statement break, continue and label statements
2. Import statement
Used to reference classes and declared in other packages.
/* * Created on Jul 14, 2005 * * First Java Program */ package com.jds.sample; import java.util.*; /** * @author JDS */ public class JavaMain { public static void main(String[] args) { // print a message System.out.println("Welcome to Java!"); } } class Extra { /* * class body */ }
3. Class declaration
A Java source file can have several classes but only one public class is allowed.
2. Block Comment
/* * insert comments here */
/* * Created on Jul 14, 2005 * * First Java Program */ package com.jds.sample; import java.util.*; /** * @author JDS */ public class JavaMain { public static void main(String[] args) { // print a message System.out.println("Welcome to Java!"); } }
3. Documentation Comment
/**
* insert documentation */
Whitespaces
Tabs and spaces are ignored by the compiler. Used to improve readability of code.
Class
Every java program includes at least one class definition. The class is the fundamental component of all Java programs.
A class definition contains all the variables and methods that make the program work. This is contained in the class body indicated by the opening and closing braces.
10
main() method
This line begins the main() method. This is the line at which the program will begin executing.
String args[]
Declares a parameter named args, which is an array of String. It represents command-line arguments.
11
Java statement
A complete unit of work in a Java program. A statement is always terminated with a semicolon and may span multiple lines in your source code.
System.out.println()
This line outputs the string Welcome to Java! followed by a new line on the screen.
Java Keywords
abstract assert boolean break byte case catch char class continue default do double else extends false final finally float for const if implements import instanceof int interface long native new null goto
13
package private protected public return short static strictfp super switch
synchronized this throw throws transient true try void volatile while
Identifiers
An identifier is the name given by a programmer to a variable, statement label, method, class, and interface An identifier must begin with a letter, $ or _ Subsequent characters must be letters, numbers, $ or _ An identifier must not be a Java keyword Identifiers are case-sensitive
14
Literals
A literal is a representation of a value of a particular type
Type Examples & Values true false a \uFFFF' \777
boolean
character integer floating-point object
escape sequences \n \t \b \f \r \ \ \\
15
16
17
17
Here is an example of the difference between strongly typed and weakly typed languages:
1: 2: 3: 4: JavaScript (weakly typed) var x; // Declare a variable x = 1; // Legal x = "Test"; // Legal x = true; // Legal Java (strongly typed)
1: int x; // Declare a variable of type int 2: x = 1; // Legal 3: x = "Test" // Compiler Error 4: x = true; // Compiler Error
18
18
short
int long
float
double
19
1. Class
2. Interface
20
Declaring a variable with reference data type Date String now = new Date(); name = Jason;
reference type
MEMORY
int age;
type Identifier name
age
17 0
22
Car myCar;
type Identifier name
myCar
reference
The heap
Bumble Bee
Identifier name
Car object
23
0x 0fed02e
Account obj1 Class Account
int num;
char type; double balance; Account obj2 0x 0fc024b
num = 241;
type = C balance = $4890.00 ;
24
24
Scope of Variable
Member Variables Declared inside the class but outside of all methods. Accessible by all methods of the class.
Local Variables Available only within the method where they were declared. Method parameters have local scope.
public class HelloWorld { //accessible throughout the class String name; public void otherMethod(){ float salary = 15000.00f; //cant access age variable from here } public static void main(String args[ ]) { //cant access salary variable from here int age=17; //cant access ctr variable from here for (int ctr=0 ; ctr<5 ; ctr++) { //age variable accessible here } } }
Confidential Mr. Anuj
25
Agenda
Fundamentals Operators Flow Controls
26
Unary Operators
Unary operators use only one operand
++ -+ Increment by 1, can be prefix or postfix Decrement by 1, can be prefix or postfix Positive sign Negative sign
Sample code:
int num=10; System.out.println("incrementing/decrementing..."); System.out.println(++num); System.out.println(--num); System.out.println(num++); System.out.println(num--); System.out.println("setting signs..."); System.out.println(+num); System.out.println(-num);
Sample output:
incrementing/decrementing... 11 10 10 11 setting signs... 10 -10
28
Arithmetic Operators
Arithmetic operators are used for basic mathematical operations
+ Add Subtract Multiply Divide
* / %
Modulo, remainder
Sample code:
int num1=15, num2=10; System.out.println("calculating..."); System.out.println(num1 + num2); System.out.println(num1 - num2); System.out.println(num1 * num2); System.out.println(num1 / num2); System.out.println(num1 % num2);
Sample output:
calculating... 25 5 150 1 5
29
String Operator
String operator (+) is used to concatenate operands If one operand is String, the other operands are converted to String
Sample code:
String fname = "Josephine", lname = Luv", mi = "T"; String fullName = lname + ", " + fname + " " + mi + "."; String nickName = "Jessy"; int age=21; System.out.println("My full name is: " + fullName); System.out.println("You can call me " + nickName + "!"); System.out.println("I'm " + age + " years old.");
Sample output:
My full name is: Luv, Josephine T. You can call me Jessy! I'm 21 years old.
30
Relational Operators
Relational operators are used to compare values boolean values cannot be compared with non-boolean values Only object references are checked for equality, and not their states Objects cannot be compared with null null is not the same as
< <= > >= == !=
Greater than
Greater than or equal to Equals
Not equals
31
Relational Operators
Sample code:
String name1 = "Marlon"; int weight1=140, height1=74; String name2 = "Katie"; int weight2=124, height2=78; boolean isLight = weight1 < weight2, isLightEq = weight1 <= weight2; System.out.println("Is " + name1 + " lighter than " + name2 + "? " + isLight); System.out.println("Is " + name1 + " lighter or same weight as " + name2 + "? " + isLightEq); boolean isTall = height1 > height2, isTallEq = height1 >= height2; System.out.println("Is " + name1 + " taller than " + name2 + "? " + isTall); System.out.println("Is " + name1 + " taller or same height as " + name2 + "? " + isTallEq); boolean isWeighEq = weight1 == weight2, isTallNotEq = height1 != height2; System.out.println("Is " + name1 + " same weight as " + name2 + "? " + isWeighEq); System.out.println("Is " + name1 + " not as tall as " + name2 + "? " + isTallNotEq); System.out.println("So who is heavier?"); System.out.println("And who is taller?");
Sample output:
Is Marlon lighter than Katie? false Is Marlon lighter or same weight as Katie? false Is Marlon taller than Katie? false Is Marlon taller or same height as Katie? false Is Marlon same weight as Katie? false Is Marlon not as tall as Katie? true So who is heavier? And who is taller?
32
Conditional operator
The ternary operator (?:) provides a handy way to code simple if-else() statements in a single expression, it is also known as the conditional operator
If condition is true, then exp1 is returned as the result of operation If condition is false, then exp2 is returned as the result of operation
Syntax:
condition ? exp1 : exp2;
Sample code:
int yyyy=1981, mm=10, dd=22; String mmm = mm==1?"Jan":mm==2?"Feb":mm==3?"Mar":mm==4?"Apr":mm==5?"May":mm==6?"Jun": mm==7?"Jul":mm==8?"Aug":mm==9?"Sep":mm==10?"Oct":mm==11?"Nov":mm==12?"Dec":"Unknown"; System.out.println("I was born on " + mmm + " " + dd + ", " + yyyy);
Sample output:
I was born on Oct 22, 1981
33
Logical Operators
!
Logical operators are used to compare boolean expressions ! inverts a boolean value & | evaluate both operands && || evaluate operands conditionally
&
| ^
&&
Truth Table
Op1 Op2 !Op1 Op1 & Op2 Op1 | Op2
||
Op1 ^ Op2
34
boolean b = (8>5) || (5>8); true; If the left operand of an || operation is true, the result is automatically true, and the right operand is not evaluated
false; Boolean Complement boolean c = !b; ( ! ): The NOT function inverts the value of boolean
Confidential Mr. Anuj
35
Logical Operators
Sample code: Sample output:
Are you a candidate for promotion? true int yrsService=8; Will you be promoted as a regular employee? false double perfRate=86; Will you be promoted as a supervisor? false double salary=23000; Will you be promoted as a manager? true char position='S'; Will S-supervisor, M-manager, less? false // P-probationary R-regular, you be paid more and work E-executive, T-top executive I hope you won't be demoted, are you? false boolean forRegular, forSupervisor, forManager, forExecutive, forTopExecutive; forRegular = yrsService>1 & perfRate>80 & position=='P' & salary<10000; forSupervisor = yrsService>5 & perfRate>85 & position=='R' & salary<15000; forManager = yrsService>7 & perfRate>85 & position=='S' & salary<25000; forExecutive = yrsService>10 & perfRate>80 & position=='M' & salary<50000; forTopExecutive = yrsService>10 & perfRate>80 & position=='E' & salary<75000; boolean isPromoted = forRegular||forSupervisor||forManager||forExecutive||forTopExecutive; boolean isLuckyGuy = forExecutive ^ forTopExecutive; System.out.println("Are you a candidate for promotion? " + isPromoted); System.out.println("Will you be promoted as a regular employee? " + forRegular); System.out.println("Will you be promoted as a supervisor? " + forSupervisor); System.out.println("Will you be promoted as a manager? " + forManager); System.out.println("Will you be paid more and work less? " + isLuckyGuy); System.out.println("I hope you won't be demoted, are you? " + !isPromoted);
36
Assignment Operators
Sample code:
double unitPrice=120, qty=2, salesAmount; double discRate=15, discAmount, vatRate=10, vatAmount; // compute gross sales salesAmount = unitPrice * qty; System.out.println("Gross Sales: " + salesAmount); // compute tax vatRate /= 100; vatAmount = salesAmount * vatRate; salesAmount += vatAmount; System.out.println("Tax: " + vatAmount); // compute discount discRate /= 100; discAmount = salesAmount * discRate; salesAmount -= discAmount; System.out.println("Discount: " + discAmount); System.out.println("Please pay: " + salesAmount);
Assign
Add and assign Subtract and assign Multiply and assign Divide and assign Modulo and assign
Sample output:
Gross Sales: 240.0 Tax: 24.0 Discount: 39.6 Please pay: 224.4
37
Casting
Casting is converting from one data type to another Implicit casting is an implied casting operations Explicit casting is a required casting operations Primitive casting is converting a primitive data type to another
Widening conversion is casting a narrower data type to a broader data type Narrowing conversion is casting a broader data type to a narrower data type
Casting between primitive and reference type is not allowed In Java, casting is implemented using () operator
38
widening conversion
char
byte
short
int
long
float
doubl e
narrowing conversion
39
implicit widening conversion implicit widening conversion implicit widening conversion implicit widening conversion implicit widening conversion (if target is broader ) implicit widening conversion (if formal parameter is broader)
logical
ternary ?: boolean (all others)
none
none none explicit casting (narrowing or widening conversion)
40
41
Summary of Operators
Evaluation order of operators in Java is as follows: Unary (++ -- + - ~ ()) Arithmetic (* / % + -) Shift (<< >> >>>) Comparison (< <= > >= instanceof == !=) Bitwise (& ^ |) Short-circuit (&& || !) Conditional (?:) Assignment (= += -= *= /=)
42
Agenda
Fundamentals Operators Flow Controls
43
Flow Controls
if-else() statement switch() statement while() statement do-while() statement for() statement break statement continue statement
Statement label
44
1. Selection
Perform statements based on condition
1. Iteration
Perform statements repeatedly based on condition
45
if-else() Construct
if-else() performs statements based on two conditions Condition should result to a boolean expression If condition is true, the statements following if are executed If condition is false, the statements following else are executed Can be nested to allow more conditions
if (condition) { // statement } else { // // statement } // braces optional required else clause is optional required
Syntax:
Example:
int age=10; if (age < 10) { System.out.println("You're just a kid."); } else if (age < 20){ System.out.println("You're a teenager."); } else { System.out.println("You're probably old..."); }
You're a teenager.
Output:
46
switch() construct
switch() performs statements based on multiple conditions exp can only be char byte short int, val should be a unique constant of exp case statements falls through the next case unless a break is encountered default is executed if none of the other cases match the exp Syntax:
switch (exp) { case val: // statements here case val: // statements here default: // statements here }
Example:
Output:
I'm a male.
47
while() loop
while() performs statements repeatedly while condition remains true
Syntax:
while (condition) { // braces optional // statements here } int ctr=10; while (ctr > 0) { System.out.println("Timer: " + ctr--); } Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: 10 9 8 7 6 5 4 3 2 1
Example:
Output:
48
do-while() loop
do-while() performs statements repeatedly (at least once) while condition remains true
Syntax:
do // statements here while (condition); int ctr=0; do System.out.println("Timer: " + ctr++); while (ctr < 10); // next statement Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: Timer: 0 1 2 3 4 5 6 7 8 9
Example:
Output:
49
for() loop
for() performs statements repeatedly based on a condition Init is a list of either declarations or expressions, evaluated first and only once Condition is evaluated before each iteration Exp is a list of expressions, evaluated after each iteration All entries inside () are optional, for(;;) is an infinite loop
Syntax:
for (init; condition; exp) { // braces optional // statements here } for (int age=18; age<30; age++) { System.out.println("Enjoy life while you're " + age); }
Example:
Output:
Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy Enjoy
life while you're 18 life while you're 19 life while you're 20 life while you're 21 life while you're 22 life while you're 23 life while you're 24 life while you're 25 life while you're 26 life while you're 27 life while you're 28 Confidential Mr. life while you're 29 Anuj
50
break
break exits loops and switch() statements
Syntax:
Example:
break; boolean isEating=true; int moreFood=5; while (isEating) { if (moreFood<1) break; System.out.println("Uhm, yum, yum..."); moreFood--; } System.out.println("Burp!");
Output:
Uhm, yum, Uhm, yum, Uhm, yum, Uhm, yum, Uhm, yum, Burp!
51
continue
continue is used inside loops to start a new iteration
Syntax: Example:
continue;
for (int time=7; time<12; time++) { if (time<10) { System.out.println("Don't disturb! I'm studying..."); continue; } System.out.println("zzzZZZ..."); } Don't disturb! I'm studying... Don't disturb! I'm studying... Don't disturb! I'm studying... zzzZZZ... zzzZZZ...
Output:
52
Statement Label
A label is an identifier placed before a statement, it ends with : break labelName is used to exit any labelled statement continue labelName is used inside loops to start a new iteration of the labeled loop
labelName: break labelName; continue labelName;
Output:
Syntax:
Example:
int[] scores = {3,9,10,0,8,10,7,1,9,8}; outer: for (int i=0; i<10; i++) { if (scores[i] <=0) break outer; if (scores[i] > 5) { inner: for (int j=0; j<3; j++) { if (scores[i] == 10){ System.out.println ("Perfect score! More claps!!!"); continue inner; } System.out.println ("Nice score! One clap!"); continue outer; } } if (scores[i] <= 5) System.out.println("More practice..."); }
More practice... Nice score! One clap! Perfect score! More claps!!! Perfect score! More claps!!! Perfect score! More claps!!!
53
return
return branching statement is used to exit from the current method. Two forms: return <value>; return;
Example 1: public int sum(int x, int y) { return x + y; } Example 2: public int sum(int x, int y) { x = x + y; if (x < 100){ return x; }else{ return x + 5; } } Example 2: public void getSum(int x) { System.out.println(x); return;
}
Confidential Mr. Anuj
54
Key Points
A Java source file can include package, import and class declarations in that order The main() method is the start of execution of a Java application Each Java statement is terminated by a semicolon ; Identifiers are case-sensitive Java keywords cannot be used as identifiers Each variable must be declared with a data type There are 8 primitive data types: boolean, char, byte, short, int, long, float and double There are 3 reference data types: class, array and interface
55
Key Points
if() and switch() are used for branching statements
while(), do-while() and for() are used for iterating statements break, continue and label are used to branch inside loops
57
59