Apr, 2011 Dating with Java Larry Li
Objective Hello world program Setup development environment Data types and variables Operators and Expressions Control Flow Method
Java Tech Structure Java code will compile to byte code JVM will run byte code Write Once, Run Anywhere
Setup Development Environment Download JDK Set environment variables(JAVA_HOME, CLASSPATH, PATH) JAVA_HOME : “c:\Sun\jdk1.6.0_24” PATH : “%JAVA_HOME%\bin” CLASS_PATH:”.;%JAVA_HOME\lib\dt.jar”;%JAVA_HOME\lib\tools.jar” JAVA_HOME : “c:\Sun\jdk1.6.0_24” PATH : “%JAVA_HOME%\bin” CLASS_PATH:”.;%JAVA_HOME\lib\dt.jar”;%JAVA_HOME\lib\tools.jar”
public class Hello{ public static void main(String[] args){ System.out.println(“Hello World”); } public class Hello{ public static void main(String[] args){ System.out.println(“Hello World”); } Our First Program
Compile and Run Java source file name is “ClassName.java” Use javac to compile java program (c:\javac Hello.java) Use java to run java program(c:\java Hello)
Datatypes TypeSizeMinimumMaximumWrapper typeDefault boolean---Booleanfalse char16bits\u0000\uffffCharacter\u0000 byte8bits Byte0 short16bits Short0 int32bits Integer0 long64bits Long0 float32bitsIEEE754 Float0.0F double64bitsIEEE754 Double0.0D void---Void- reference----null
Declare Variables int age = 25; Declaration must before the first statement that uses the local variable. Must initialize a local variable before using it. final int height = 179; Variables declared with modifier final must be assigned before use and cannot be changed once assigned
Legal Identifier A variable name is a sequence of letters, digits, and underscores. Must start with a letter or underscore. Can be as long(or short)as you want. Must not be a keyword or a literal value
Java Keywords abstractcontinuefornewswitch assertdefaultgoto*packagesynchronized booleandoifprivatethis breakdoubleimplementsprotectedthrow byteelseimportpublicthrows caseenuminstanceofreturntransient catchextendsintshorttry charfinalinterfacestaticvoid classfinallylongstrictfpvolatile const*floatnativesuperwhile
Literals Boolean literals : ”true”, ”false”. Null literals : ”null”. Numeric literals : “10”,”15L”,”1.1F”,”2.0”,”6.5E+1f”,”2.65e-8” Character literals : ‘A’,’\u0041’. String literal : “James Gosling”.
Arrays A variable declared with brackets,[],is an array reference. Must use new to actually create the array, array is object. float price[]; String[] title, author; price = new new float[44]; String[] names = new String[10]; names[1] = “James Gosling”; price[0] = 99.95F; int odds = {1,3,5,7,9}; float price[]; String[] title, author; price = new new float[44]; String[] names = new String[10]; names[1] = “James Gosling”; price[0] = 99.95F; int odds = {1,3,5,7,9};
Operators Precedence !, ~, ++, --, +(positive), –(negative),( ) (cast) *,/,% +,-,>=,instanceof ==,!= && || Condition ? X : Y =,+= …
Operators Assignment Mathematical operators Increment and decrement Relational operators Logical operators Conditional operator Implicit type conversions Casting operators
Assignment Assign a value to a variable. Left operand must be a variable. Assignment expression's value is the value that was assigned Evaluated right to left min = 5; 5 = x;// illegal! current = (min = 5); max = current = min = 5; min = 5; 5 = x;// illegal! current = (min = 5); max = current = min = 5;
Mathematical +,-,*,/,% +,-(unary operator) age+1; daysLeft -3; width * height; totalLines / numPages; curLine%6; -balance age+1; daysLeft -3; width * height; totalLines / numPages; curLine%6; -balance
Increment and decrement ++,-- Unary operator Operand must be a variable --age; weight--; salary++; ++numCloth; --age; weight--; salary++; ++numCloth;
Relational >,>=,<,<=,==,!=. Results a true or false value. x >= maxValue args.length != 2 x >= maxValue args.length != 2
Logical ||,&&,! |,& && and || operators use short-circuit evaluation. length 18 height >= 10 && height <= 20 !(height >= 10 && height <=20) length 18 height >= 10 && height <= 20 !(height >= 10 && height <=20)
Operate-Assign Operators +=,-=,etc. Correspond to all the basic arithmetic operators age -= 10; mySalary += hisSalary; age -= 10; mySalary += hisSalary;
Conditional Operator op1 ? op2 : op3 char status; int age = 16; Status = age >= 18 ? ‘a’ : ‘m’ char status; int age = 16; Status = age >= 18 ? ‘a’ : ‘m’
Implicit Type Conversions Operands of different data types in an expression are converted to a common type. Smaller data types are converted to larger data types. Conversions that would truncate data will not happen implicitly float fTotal; float f = 6.5F; int i = 5,iTotal; fTotal = f + i; iTotal = f + i;// ERROR float fTotal; float f = 6.5F; int i = 5,iTotal; fTotal = f + i; iTotal = f + i;// ERROR
Cast Operator Conversions can be forced by explicitly casting a value or expression to a new data type; If the value being cast is too large to fit in the smaller location, the bits of the value will be truncated. To convert to a String, do not use the cast operator. float f = 6.5F, g = 7.7F; int total = (int)(f + g); String s = “” + f;// if one operand is String float f = 6.5F, g = 7.7F; int total = (int)(f + g); String s = “” + f;// if one operand is String
Control Flow Statement Conditional Statements (if-else, switch) Loop(do-while, while, for) Continue, Break statement Label in loop
Statement A single statement is an expression followed by a semicolon. Curly braces group statements into compound statements, called blocks. int area; { area = width * length; System.out.println(“area is ” + area); } int area; { area = width * length; System.out.println(“area is ” + area); }
Conditional (if) Statement if, if-else if, else if (age 3){ //do stuff } else if ( age >= 16 ){ //do stuff } else{ //else do stuff } if (age 3){ //do stuff } else if ( age >= 16 ){ //do stuff } else{ //else do stuff }
Conditional (switch) Statement Use a switch statement when you are testing the same expression for several possible literal values. Only compare expression of type byte, short, int, char, enum. switch (choice){ case ‘a’: // do something break; case ‘b’ : // do something break; default : // do default break; } switch (choice){ case ‘a’: // do something break; case ‘b’ : // do something break; default : // do default break; }
Loops do-while, while, for do{ // do something }while (hasNext); while(hasNext){ // do something } for(int i=0; i<5 ;i++){ // do something } int odds[] = {1,3,5,7,9}; for(int n : odds){ System.out.println(n); } do{ // do something }while (hasNext); while(hasNext){ // do something } for(int i=0; i<5 ;i++){ // do something } int odds[] = {1,3,5,7,9}; for(int n : odds){ System.out.println(n); }
Continue/break statement int i=0; while(true){ if (i % 2 != 0){ cotinue; } System.out.println(i); if (i > 10){ break; } int i=0; while(true){ if (i % 2 != 0){ cotinue; } System.out.println(i); if (i > 10){ break; }
Continue/break statement int i=0; while(true){ if (i % 2 != 0){ cotinue; } System.out.println(i); if (i > 10){ break; } int i=0; while(true){ if (i % 2 != 0){ cotinue; } System.out.println(i); if (i > 10){ break; }
Label in Loop label: while(true){ break; continue; continue label; break label; } label: while(true){ break; continue; continue label; break label; }
Methods //defing float getRectangleArea(float width,float height){ float area = width * height; return area; } //calling int rectangleArea = getRectangleArea(thisWidth,thisHeight); //defing float getRectangleArea(float width,float height){ float area = width * height; return area; } //calling int rectangleArea = getRectangleArea(thisWidth,thisHeight); Calling methods Defining methods Method Parameters
Finished Today Q&A
Homework 1.Setup development environment 2.A program print your name 3.Compile and run this program 4.A program print your dog’s information, including : name,weight,length of tail, friendly or not 5.Write a program with a big integer, big = and a bigger, bigger = big+1,print the tow number and explain the result 6.A program can convert Fahrenheit to Celsius (C = F minus 32 multiply by five ninth)
Thank you Java Bench