Basic Java Syntax
COMP 401, Spring 2013 Lecture 2 1/15/2013 Hello, World – take 2
• Same as before, but with Eclipse. – Eclipse Workspace – Crea ng new project – Crea ng a new package – Crea ng new class – Se ng up run me arguments in a “Run Configura on” Fundamental Characteris cs 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 automa cally allocated when objects are created. – Memory is automa cally 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 en rely by their value.
Reference types are structures in memory. • Address in memory uniquely iden fies 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” – Opera ons 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 [] a er 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 le er and can contain le ers, digits, $, or _ – Can not start with digit – Should not use $ (just don’t) – Should not start with _ – Case sensi ve – 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 func on call: foo() – Expressions combined by operators: 4+3*2 Operators
• Unary: +, -, !, ++, -- • Arithme c: +, -, /, *, % • Rela onal: ==, !=, >, >=, <, <= • 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 execu on. – Types of statements: • Variable declara on • Expression statement – Not really useful unless the expression has a side effect. • Assignment • Condi onal • Loop • Method call • Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. • And vice versa Condi onal Execu on: 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”);! }! ! Condi onal Execu on: switch switch (expression) {! • Works with basic case value:! value data types !statements! • Works with strings !break;! as of Java 7 case value:! !statements! • Execu on starts at !break;! first matching case ...! value (or default if default:! given). !statements! • Con nues un l } ! 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”, “func on”, and “procedure” get used almost interchangeably. – There are technical dis nc ons • Every method in Java is either a “class” method or an “instance” method. – Class methods are declared with the keyword “sta c” – Can use Java in a non-OO manner by wri ng your program with only sta c methods. • This is what A1 asks you to do – Class methods have a slightly different role when used within a program that is wri en 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 poten al 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 – A er end of input report average size of triangles by type as well as area of smallest triangle