CMPS4143 Contemporary Programming Languages Java Fundamentals Concentrate on writing applications… public class FirstSample { public static void main (String[] args) { System.out.println (“We will not use ‘Hello, World!;”); } } Java case sensitive public – access modifier (supports Security Principle) Keyword class – everything in Java a class (supports Regularity Principle) Rules for class names – start with letter, any combo of letters and digits; length unlimited (0-1-infinity principle). Can’t use a reserved word – security principle File name for source must be same name as public class with .java AND case is important! Javac – creates bytecodes in .class file. Run bytecode through interpreter Must have a main method and in Java Language Specification must be public. Textbook has a style – I LIKE that style! Every function is a method of some class – supports Regularity Principle static void – static member functions do not operate on objects of that class void indicates that method does not return a value (do not need an exit code to the OS like C++ - unless you use threads and you will use threads) every statement ends in ; so statements can span several lines – supports regularity principle System.out is an object and println is a method (. Invokes a method) …also a print method Methods can use 0, 1 or more parameters or arguments – supports regularity principle. Comments same as C++ Data Types Java strongly typed – supports security principle (C++ is weakly typed) See fig 3-1 8 primitive types: int, short, long, byte (use int unless…) In Java range of values does not depend on machine – supports portability (In C++ uses most efficient for each processor) float, double – use double unless … char – uses Unicode encoding scheme – 65,536 characters (2 bytes) escape sequences \t\n\r for white spaces boolean – false and true (cannot convert to int) supports Security principle Variables double salary; char answer; boolean done; int vacationDays; -every variable has a type -variable name must start with letter, followed by and number of letters and digits SUPPORTS 0-1-Infintity - can use Unicode letters/symbols - case sensitive - can’t use reserve words - FOLLOW CONVENTION Box box; or better Box aBox; Assgs/Inits int vacationDays; vacationDays = 14; Constants - used in one method - used in multiple methods int vacationDays = 14; SAME as C++ final double CM_PER_INCH = 2.54; public static final double CM_PER_INCH = 2.54; use of final – supports defense in depth and labeling principles different ways to declare – violates regularity principle use of public – methods of other classes can use it. Operators int n=5; int a= 2* n; x+=4; same as x = x+4; syntactic sugar violates consistency goal of portability of Java, but computations by different processors (and use of registers) yields different results. Initially, all machines required to truncate, and scientific community hated it…so now do not require it) If you require same results, use strictfp as a tag for the class. public static strictfp void main (String args[]) n++; n--; a=2 * ++m; increments m before mult. A=2*m++; after Relational and Boolean Ops ==, !=, < >, <=, >=, &&, !, || same as C++ compound expressions short circuit – principle? Math functions and constants double y = Math.sqrt(x); y = Math.pow(x,a); Math.PI and Math.E Math is a class, sqrt a method – it does not operate on an object, hence if you look at its declaration you’ll see it is a static method. Can also use Strict Math class instead (slower, but more predictable results) Conversions - strongly typed FIG 3-1 - can cast int i = (int)x; truncates - can round int I = (int)Math.round(x); Table for hierarchy or use ( )’s Strings - not built-in; but in a predefined class called String. Each quoted string is an instance of the string class: String greeting = “Hello”; Exception not using new to create instance Violates Regularity principle + concat (ONLY overloaded operator in Java) no overloading supports Othogonality String s = greeting.substring (0,4); int l = greeting.length( ); char last = greeting.charAt (greeting.length ( ) – 1); NO METHODS TO CHANGE a string – but can get around with reassg. String is a char* pointer basically. greeting = “Howdy”; memory leak? No automatic garbage collection – supports automation principle. Test strings = s.equals(t) s.equalsIgnoreCase(t); CANNOT use == String toUpperCase( ); CMPS4143 Contemporary Programming Languages Java Fundamentals cont. Reading Input Easy to output More complex to input from ‘standard input device’ Easy to supply a dialog box for keyboard input. Method is JoptionPane.showInputDialog (promptString) returns a string!!! Will also show OK and Cancel buttons Must use import javax.swing.*; Must end program with System.exit(0); because showing dialog box starts new thread Examples: String input = JoptionPane.showInputDialog (“What is your name?”) ; input = JoptionPane.showInputDialog (“Enter your age:”) ; int age = Integer.parseInt (input); input = JoptionPane.showInputDialog (“Enter your gpa:”) ; Double gpa = Double.parseDouble (input); Program 2 will use input from keyboard! Program 3 will have input from keyboard and file. Formatting output System.out.print (x) prints the maximum non-zero digits for that type. System.out.print (10000.0/3.0); 3333.3333333333335 Note: 10000/3 3333 Use NumberFormat class from java.text package NumberFormat formatter =NumberFormat.getNumberInstance (arg optional); getCurrencyInstance or getPercentInstance formatter.setMaximumFractionDigits(4); String sdoubleNum = formatter.format (doubleNum); System.out.print (sdoubleNum); Can also set min integer digits??? Control Flow Conditional statements and loops support structure principle No goto in Java supports structure principle Labeled break statement to jump out of nested loops violates structure principle Blocks define scope of variables - supports localized principle Blocks can be nested: BUT cannot redefine a variable inside a NESTED block UNLIKE C++ - violates regularity, supports security, because lots of programmers make errors in C++ EXCEPTION for loop’s LCV can be redefined – violates regularity Conditional statements if; if else if else; just like C++. NOTE: else paired with closest if. Loops – two forms for indeterminate loops: While and do-while just like C++ For loop – just like C++ for loops support automation principle CONVENTION in java that three parts of for loop are init, test, update the same counter variable (although like C++ you can show bad taste and do other things) SCOPE of LCV in for loop CAREFUL: using real numbers in for loops i+= 0.1 for update ROUNDOFF ERRORS switch similar to C++ cases support labeling principle case labels must be integers!!! Can’t do any ordinal types, ie chars forget a break, falls through violates security and defense in depth principle why do it: combine cases better way case 1, 2, 3: as in Pascal and Ada break in a loop labeled break better! read_data: while { break read_data; } continue transfer control to header of innermost loop CONVENTION: don’t use break or continue!!! BigNumbers BigInteger and BigDecimal from java.math package. BigInteger c = a.add(b);