java fundamentals 1. first program public class firstsample { public static void main (string[]...
TRANSCRIPT
Java Fundamentals
1
First Program
public class FirstSample{ public static void main (String[] args) { System.out.println (“We will not use ‘Hello, World!;”); }}
• Everything in Java is a class …(or a method)• 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 2
• 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)3
• 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++
4
Data Types
• Java strongly typed– supports security principle (C++ is weakly typed) – 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 5
Variables
• Every variable has a type
double salary;char answer;boolean done; int vacationDays;
• variable name must start with letter, followed by any number of letters and digits
– SUPPORTS 0-1-Infintity• can use Unicode letters/symbols• case sensitive• Some words keywords, some reserverd (can’t use reserve words, e.g. const,
goto)• FOLLOW CONVENTION Box box;
6
Assgs/Inits
• SAME as C++
int vacationDays;vacationDays = 14;
• or
int vacationDays = 14;
7
Constants
• used in one method
final double CM_PER_INCH = 2.54;• used in multiple methods
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.
8
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
9
Relational and Boolean Ops
• same as C++
==, !=, < >, <=, >=, &&, !, || • compound expressions short circuit
– principle?
10
Math functions and constants
double y = Math.sqrt(x); y = Math.pow(x,a);Math.PI and Math.E
• Math is a static 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 StrictMath class instead (slower, but more predictable
results)
11
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
12
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 to the rule to not use new 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);
13
Strings
• NO METHODS TO CHANGE a string – but can get around with reassignment
• String is a char* pointer basically.
• greeting = “Howdy”; – memory leak? No - automatic garbage collection – supports automation principle.
• Test strings CANNOT use == s.equals(t) s.equalsIgnoreCase(t); • String toUpperCase( );
• See handount on String methods.
14
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
15
Input 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.
16
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 getPercentInstanceformatter.setMaximumFractionDigits(4);String sdoubleNum = formatter.format (doubleNum);System.out.print (sdoubleNum);
• Can also SetMinimumFractionDigits17
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
18
Control Flow
• 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 is for loop• CAREFUL: using real numbers in for loops i+= 0.1 for update
ROUNDOFF ERRORS19
Loops
• break in a loop• labeled break better!
read_data: while { break read_data; }
• continue transfer control to header of innermost loop
• CONVENTION/ GOOD SWENG: don’t use break or continue!!!
20
Switch
21
• 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
BigNumbers
• BigInteger and BigDecimal from java.math package.
• BigInteger c = a.add(b);
22