Basic Java Syntax

Basic Java Syntax

Basic Java Syntax COMP 401, Spring 2013 Lecture 2 1/15/2013 Hello, WorlD – take 2 • Same as before, but with Eclipse. – Eclipse Workspace – Creang new project – Creang a new package – Creang new class – Seng up runNme arguments in a “Run Configuraon” FunDamental CharacterisNcs of Java • Strongly typeD – Variables must be DeclareD with a type specifieD. • Dichotomy between value types anD reference types. – In some OO languages, everything is an object. – Not quite true in Java. • Some basic Data types are objects (e.g., String, arrays) • Other basic Data types are not (integers, real numbers, booleans) • Garbage collecteD memory – Memory is automacally allocateD when objects are createD. – Memory is automacally reclaimeD when no possible reference to an object can exist. A WorD About Types Value Types Reference Types • Integers • String • Real numbers • Array • Booleans • Objects typeD by their class • Character • Classes themselves Values types are DefineD enNrely by their value. Reference types are structures in memory. • ADDress in memory uniquely iDenNfies them. • The “value” of a variable that holDs a reference type is this adDress. • AssociateD with “methoDs” anD “fielDs” • FielDs are also known as “members” Value Types • Integers – byte, short, int, long – Difference is in size (1, 2, 4, or 8 bytes) – No “unsigned” version – Decimal (255), hexiDecimal (0xff), anD binary (0b11111111) literal formats • Real Numbers – float, Double – Difference is in precision. • Characters – char – Characters in Java are 16-bit UnicoDe values – Literals use single-quote: ‘c’ – Non-printable escape sequence: ‘\u####’ where # is hex Digit. • Example: ‘\u00F1’ for ñ • Logical – boolean – Literals are true anD false Reference Types • String • Array • Objects DefineD by programmer – TypeD by its “class” • Classes themselves – Type of a class is “Class” • null – ValiD literal value for all reference types – Basically inDicates that there is no value. • The “.” operator “Dereferences” a reference type in orDer to access associateD methoDs anD fielDs. Strings • String class a = “A String ”;! – Sequence of chars a.length();! !9! • Some common methoDs: a.charAt(3);! – length() !‘t’ – charAt(int idx) a.concat(“am I”);! – concat(String otherString) !“A String am I” • Can also use “+” a + “am I”;! – equals(Object obj) Same as above • Be careful about using “==” a.equals(“B string”);! – substring(int start, int end) !false – trim() a.substring(2,5);! • Strings are immutable “Stri” – Operaons that change/alter a string a.trim();! are really giving you a new one. “A String” ! Arrays • Container for a fixed number of int[] iarray;! !Declared, but not created.! values with the same type. iarray = new int[10];! • Zero baseD inDexing. !Now it’s created, but • Variables for arrays DeclareD by uninitialized.! using [] aer type. len = iarray.length;! !Length available as public – Type of the variable is Array field. Note, not a method.! – Type of each entry is specifieD by iarray[0] = 3;! type name before [] !0th item set! • Empty arrays can be createD with iarray[-1];! new keyword. !Illegal index! – Size must be proviDeD. iarray[10];! – What Do I mean by “empty”? !Index out of bounds! int[] iarray = {1,2,(2+1)};! • Literal array syntax can be useD !Declared and items to create array from literal values initialized all in one.! (or expressions). Variables • Variable names should start with a leter anD can contain leters, Digits, $, or _ – Can not start with Digit – ShoulD not use $ (just Don’t) – ShoulD not start with _ – Case sensiNve – Can not be a keyworD • Legal: – foo, bar, a_variable, var123 • Legal but not consiDereD gooD: – var_with_$, _badness • Illegal: – 1var, while, break, this has whitespace Expressions • A sequence of symbols that can be evaluateD to proDuce a value. – Can be useD wherever a value is expecteD. • Types of expressions: – Literal values: 123 – Variable names: a_variable – Public class/object fielDs: Math.PI – Value as a result of a funcNon call: foo() – Expressions combineD by operators: 4+3*2 Operators • Unary: +, -, !, ++, -- • ArithmeNc: +, -, /, *, % • Relaonal: ==, !=, >, >=, <, <= • Boolean: &&, || • Ternary: ?: – expression ? if_true : if_false • Bitwise: ~, <<, >>, >>>, &, |, ^ • Be aware of preceDence – Can be controlleD by explicitly grouping with () I Spy... double height = 1.77;! • ... a type • boolean overWeight = false;! ... a variable • ... a boolean literal • ... an integer literal final int HIGH_BMI = 27;! • ... a real literal • ... a string literal String name =“joe”;! • ... a nameD constant • ... an assignment char firstChar= name.charAt(0);! • ... an expression • ... a cast int bmi= (int) weight/ • (height * height);! ... a methoD call • … a type mismatch int weight = “seventy”;! error Statements anD Blocks • Statements enD in ; – A complete unit of execuNon. – Types of statements: • Variable Declaraon • Expression statement – Not really useful unless the expression has a siDe effect. • Assignment • ConDiNonal • Loop • MethoD call • Blocks – Zero or more statements encloseD in curly braces { } – AlloweD anywhere a single statement is alloweD. • AnD vice versa ConDiNonal ExecuNon: if-else if-else if (expression) {! !block! } else if (expression) {! !block! } else {! !block! }! 14 if example if (score > 90) {! !System.out.println(“You got an A!”);! } else if (score > 80) {! !System.out.println(“You got a B.”);! } else if (score > 70) {! !System.out.println(“You got a C?”);! } else if (score > 60) {! !System.out.println(“You got a D :-(“);! } else {! !System.out.println(“You failed”);! }! ! ConDiNonal ExecuNon: switch switch (expression) {! • Works with basic case value:! value Data types !statements! • Works with strings !break;! as of Java 7 case value:! !statements! • ExecuNon starts at !break;! first matching case ...! value (or Default if default:! given). !statements! • Connues unl } ! break statement or enD of switch. Switch Example switch (c) {! !case 'a': ! !case 'e': ! !case 'i':! !case 'o': ! !case 'u': ! !!System.out.println("Vowel");! !!break;! !default: ! !!System.out.println("Consonant");! }! ! Loops: while while (expression) {! !block! }! ! do {! !block! } while (expression);! while example int sum = 0;! int n = 1;! while (n < 11) {! sum += n;! n++;! }! System.out.println(“The sum of 1 to 10 is: “ + sum);! Loops: for for (init; test; update) {! !block! }! for example int sum = 0;! for(int n=1; n<11; n++) {! sum += n;! }! System.out.println(“The sum of 1 to 10 is: “ + sum);! ! • Note that variable n is DeclareD as part of init expression in for loop. – This is a common programming iDiom if loop variable is only neeDeD for the loop. MethoD Calls • The terms “methoD”, “funcNon”, anD “proceDure” get useD almost interchangeably. – There are technical DisNncNons • Every methoD in Java is either a “class” methoD or an “instance” methoD. – Class methoDs are DeclareD with the keyworD “stac” – Can use Java in a non-OO manner by wriNng your program with only stac methoDs. • This is what A1 asks you to Do – Class methoDs have a slightly Different role when useD within a program that is writen in a OO manner Defining Class MethoDs public static type methodName (parameters) {! /* Method body */! }! ! • public is an access moDifier – Other possible values are “protecteD” anD “private” – More on access moDifiers later • type – type of value returneD by methoD – voiD inDicates no return value • parameters – comma separateD list of nameD parameters • MethoD “signature” is DefineD by its return type anD the orDer, number, anD types of its parameters Calling MethoDs • Calling a class methoD: ClassName.methodName(parameters)! • Calling an instance methoD: objectReference.methodName(parameters)! • Within the boDy of a class methoD or instance methoD, we can omit the class name or object reference if we are trying to call another class or instance methoD associateD with the same class or instance. methodName(parameters)! • Parameters are a comma separateD list of values (or expressions) – Must match in number anD type accorDing to methoD’s signature. TriangleArea example • Write a program that reads as input sequences of three siDe lengths of a potenNal triangle. – SiDe lengths specifieD as 3 real numbers – Input will enD with the worD “enD” • For each set of three siDe lengths: – Determine if a valiD triangle is possible • Triangle inequality that largest siDe is smaller than the sum of the two other siDes. – If valiD, categorize triangle • equilateral, isosceles, scalene – Report triangle type for each triangle – Arer enD of input report average size of triangles by type as well as area of smallest triangle .

View Full Text

Details

  • File Type
    pdf
  • Upload Time
    -
  • Content Languages
    English
  • Upload User
    Anonymous/Not logged-in
  • File Pages
    25 Page
  • File Size
    -

Download

Channel Download Status
Express Download Enable

Copyright

We respect the copyrights and intellectual property rights of all users. All uploaded documents are either original works of the uploader or authorized works of the rightful owners.

  • Not to be reproduced or distributed without explicit permission.
  • Not used for commercial purposes outside of approved use cases.
  • Not used to infringe on the rights of the original creators.
  • If you believe any content infringes your copyright, please contact us immediately.

Support

For help with questions, suggestions, or problems, please contact us