560 likes | 625 Views
02 Language Fundamentals. 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.
E N D
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 application’s 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
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 • Introduce the concept of return statement
Java Source File Structure declaration order 1. Package declaration Used to organize a collection of related classes. 2. Import statement Used to reference classes and declared in other packages. 3. Class declaration A Java source file can have several classes but only one public class is allowed. /* * 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 */ }
Java Source File Structure Comments /* * 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 */ } 1. Single Line Comment // insert comments here 2. Block Comment /* * insert comments here */ 3. Documentation Comment /** * insert documentation */ Whitespaces Tabs and spaces are ignored by the compiler. Used to improve readability of code.
Java Source File Structure /* * 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 */ } 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.
Java Source File Structure /* * 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 */ } Braces • Braces are used for grouping statements or block of codes. • The left brace ({) indicates the beginning of a class body, which contains any variables and methods the class needs. • The left brace also indicates the beginning of a method body. • For every left brace that opens a class or method you need a corresponding right brace (}) to close the class or method. • A right brace always closes its nearest left brace.
Java Source File Structure /* * 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 */ } 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.
Java Source File Structure /* * 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 */ } 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. Terminating character Semicolon (;) is the terminating character for any java statement.
Java Keywords abstract default if package synchronized assert do implements private this boolean double import protected throw break else instanceof public throws byte extends int return transient case false interface short true catch final long static try char finally native strictfp void class float new super volatile continue for null switch while const goto
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 printMeis not the same as PrintMe
Literals A literal is a representation of a value of a particular type
Variable and Data Types • A variable is a named storage location used to represent data that can be changed while the program is running • A data type determines the values that a variable can contain and the operations that can be performed on it • Categories of data types: • Primitive data types • Reference data types
Primitive Data Types • Primitive data types represent atomic values and are built-in to Java • Java has 8 primitive data types
Reference Data Types • Reference data types represent objects • A reference serves as a handle to the object, it is a way to get to the object • Java has 2 reference data types • Class • Interface
primitive type initial value identifier name reference type identifier name initial value Variable Declaration & Initialization • Declaring a variable with primitive data type • int age = 21; • Declaring a variable with reference data type • Date now = new Date(); • String name = “Jason”;
type Identifier name value Identifier name Primitive Type Declaration declaration MEMORY allot space to memory int age; age 0 17 initialization/assignment age = 17; stack
Identifier name Identifier name type Reference Type Declaration allot space to memory Car myCar; memory address location myCar reference The heap myCar = new Car(“Bumble Bee”); Bumble Bee Values Car object
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; //can’t access age variable from here } public static void main(String args[ ]) { //can’t access salary variable from here int age=17; //can’t access ctr variable from here for (int ctr=0 ; ctr<5 ; ctr++) { //age variable accessible here } } }
Agenda • Fundamentals • Operators • Flow Controls
Operators and Assignments • Unary operators • Arithmetic operators • String operator • Relational operators • Conditional operator • Logical operator • Assignment operators • Object operators • Shift operators • Bitwise operators • Evaluation order • Primitive Casting
Unary Operators • Unary operators use only one operand Sample output: 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); incrementing/decrementing... 11 10 10 11 setting signs... 10 -10
Arithmetic Operators • Arithmetic operators are used for basic mathematical operations Sample output: 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); calculating... 25 5 150 1 5
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 = "Santos", 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: Santos, Josephine T. You can call me Jessy! I'm 21 years old.
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 “”
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?
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 • Can be nested to accommodate chain of conditions 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
Logical Operators • Logical operators are used to compare boolean expressions • ! inverts a boolean value • & | evaluate both operands • && || evaluate operands conditionally Truth Table
Short-circuit Logical Operators (&&,|| and !) • Similar to the Boolean operators, but with an added ability to “short-circuit” part of the process, using a couple of mathematical rules: • If the left operand of an && operation is false, the result is automatically false, and the right operand is not evaluated • If the left operand of an || operation is true, the result is automatically true, and the right operand is not evaluated • Boolean Complement ( ! ): • The NOT function inverts the value of boolean false; boolean a = (5>8) && (8>5); true; boolean b = (8>5) || (5>8); false; boolean c = !b;
Logical Operators Sample code: Sample output: Are you a candidate for promotion? true Will you be promoted as a regular employee? false Will you be promoted as a supervisor? false Will you be promoted as a manager? true Will you be paid more and work less? false I hope you won't be demoted, are you? false int yrsService=8; double perfRate=86; double salary=23000; char position='S'; // P-probationary R-regular, S-supervisor, M-manager, E-executive, T-top executive 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);
Assignment Operators Sample code: • Assignment operators are used to set the value of a variable 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); Sample output: Gross Sales: 240.0 Tax: 24.0 Discount: 39.6 Please pay: 224.4
Casting • Castingis 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 • Reference castingis converting a reference data type to another • Upcasting is conversion up the inheritance hierarchy • Downcasting is conversion down the inheritance hierarchy • Casting between primitive and reference type is not allowed • In Java, casting is implemented using () operator
char byte short int long float double Primitive Casting Flow widening conversion narrowing conversion
public static void main(String args[]) { short age = 20; char sex = ‘M’; byte iq = 80; int height = 64; long distance =300; float price = 99.99f; double money = 500.00; age = sex; // will this compile? sex = iq; // will this compile? iq = (byte) height; // will this compile? distance = height; // will this compile? price = money; // will this compile? sex = (char) money; // will this compile? } Implementing Primitive Casting
Summary of Operators Evaluation order of operators in Java is as follows: • Unary (++ -- + - ~ ()) • Arithmetic (* / % + -) • Shift (<< >> >>>) • Comparison (< <= > >= instanceof == !=) • Bitwise (& ^ |) • Short-circuit (&& || !) • Conditional (?:) • Assignment (= += -= *= /=)
Agenda • Fundamentals • Operators • Flow Controls
Flow Controls • if-else() statement • switch() statement • while() statement • do-while() statement • for() statement • break statement • continue statement • Statement label
Types of Flow Control • Sequential • Perform statements in the order they are written • Selection • Perform statements based on condition • Iteration • Perform statements repeatedly based on condition
if-else() • 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) { // braces optional // statement required } else { // else clause is optional // statement required } Syntax: 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..."); } Example: Output: You're a teenager.
switch() • 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) { caseval: // statements here caseval: // statements here default: // statements here } Example: char sex='M'; switch (sex){ case'M': System.out.println("I'm a male."); break; case'F': System.out.println("I'm a female."); break; default: System.out.println("I am what I am!"); } Output: I'm a male.
while() • while() performs statements repeatedly whileconditionremains true Syntax: while (condition) { // braces optional // statements here } Example: int ctr=10; while (ctr > 0) { System.out.println("Timer: " + ctr--); } Output: Timer: 10 Timer: 9 Timer: 8 Timer: 7 Timer: 6 Timer: 5 Timer: 4 Timer: 3 Timer: 2 Timer: 1
do-while() • do-while() performs statements repeatedly (at least once) whileconditionremains true Syntax: do // statements here while (condition); Example: int ctr=0; do System.out.println("Timer: " + ctr++); while (ctr < 10); // next statement Output: Timer: 0 Timer: 1 Timer: 2 Timer: 3 Timer: 4 Timer: 5 Timer: 6 Timer: 7 Timer: 8 Timer: 9
for() • for() performs statements repeatedly based on a condition • Init is a list of either declarations or expressions, evaluated first and only once • Conditionis evaluated before each iteration • Expis 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 } Example: for (int age=18; age<30; age++) { System.out.println("Enjoy life while you're " + age); } Output: Enjoy life while you're 18 Enjoy life while you're 19 Enjoy life while you're 20 Enjoy life while you're 21 Enjoy life while you're 22 Enjoy life while you're 23 Enjoy life while you're 24 Enjoy life while you're 25 Enjoy life while you're 26 Enjoy life while you're 27 Enjoy life while you're 28 Enjoy life while you're 29
break • break exits loops and switch() statements Syntax: break; Example: 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, yum... Uhm, yum, yum... Uhm, yum, yum... Uhm, yum, yum... Uhm, yum, yum... Burp!
continue • continue is used inside loops to start a new iteration Syntax: continue; Example: for (int time=7; time<12; time++) { if (time<10) { System.out.println("Don't disturb! I'm studying..."); continue; } System.out.println("zzzZZZ..."); } Output: Don't disturb! I'm studying... Don't disturb! I'm studying... Don't disturb! I'm studying... zzzZZZ... zzzZZZ...
Statement Label • A label is an identifier placed before a statement, it ends with : • break labelNameis used to exit any labelled statement • continue labelName is used inside loops to start a new iteration of the labeled loop Output: More practice... Nice score! One clap! Perfect score! More claps!!! Perfect score! More claps!!! Perfect score! More claps!!! labelName: break labelName; continue labelName; Syntax: 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..."); } Example: