460 likes | 470 Views
This overview provides a comprehensive introduction to the Java programming language, covering topics such as comments, data types, variable declarations, expressions, flow of control statements, functions, and more.
E N D
Common Programming Language Features • Comments • Data Types • Variable Declarations • Expressions • Flow of Control Statements • Functions and Subroutines • Macros and Preprocessor Commands • I/O Statements • Libraries • Compiler Directives • External Tools (Compiler, debugger etc)
Comments in Java • The ability to comment is the most important feature in any programming language!!! • Comments should precede any block of code or any code that might be difficult to understand. A comment should describe the intent of what you are trying to do. • Write your comments BEFORE you write your code. Do not rely on the code itself to document what you are doing as the code may be incorrect • Comments may also be used to temporarily remove a block of code from your program • Special comments used to generate help files • Special comments used in NetBeans to keep track of unfinished tasks and problems /* This is a comment it can span many lines */ //Single line comments //* Javadoc comments */ //TODO
Hello World in Java class Hello { public static void main(String[] args){ System.out.println(“Welcome to Java”); } }
Why Java? Java enables users to develop and deploy applications on the Internet on multiple platforms: servers, desktop computers, hand-held and embedded devices such as dvd and blue-ray players, cell phones, RFID devices etc, regardless of the underlying processor or operating system. • Java is a general purpose programming language. • Java is the Internet programming language. • Write once, deploy everywhere 6
Characteristics of Java • Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic www.cs.armstrong.edu/liang/intro8e/JavaCharacteristics.pdf
JDK Versions • JDK 1.02 (1995) • JDK 1.1 (1996) • JDK 1.2 (1998) • JDK 1.3 (2000) • JDK 1.4 (2002) • JDK 1.5 (2004) a. k. a. JDK 5 or Java 5 • JDK 1.6 (2006) a. k. a. JDK 6 or Java 6 • JDK 1.7 (possibly 2010) a. k. a. JDK 7 or Java 7
JDK Editions • Java Standard Edition (J2SE) • J2SE can be used to develop client-side standalone applications or applets. • Java Enterprise Edition (J2EE) • J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. • Java Micro Edition (J2ME). • J2ME can be used to develop applications for mobile devices such as cell phones. The Course Text uses J2SE to introduce Java programming.
Compiling Java Source Code Unlike compiled programs written in languages such as C, C++ or Assembler, Java was designed to run object programs on any platform. With Java, you write the program once, and compile the source program into a special type of object code, known as bytecode. The bytecode can then run on any computer with a Java Virtual Machine, as shown below. Java Virtual Machine is a software that interprets Java bytecode.
Primitive Data Types • boolean, char, byte, int, short, long, float and double.
Ordinal Constants in Java • char : ‘A’ • int: -200, • 1000000L • (unsigned) 127 • 0x80FA (hex), • 007 (octal) • ‘\u0811’ (unicode) • range of values depends on word size of the machine. Usually 4 bytes for an int. “Ordinal” means “countable” – there is usually a next and previous value.
boolean data types boolean found=false; String password=“Swordfish”; found=(myInput.equals(“password”); if(found==true) System.out.println(“Yes we found it!”) elseSystem.out.println(“No we did not”);
Special Character Constants • ‘\n’ - newline • ‘\r’ - carriage return • ‘\t’ - tab • ‘\\’ - backslash • ‘\’’ - quoted apostrophe • ‘\”’ –quoted quote • ‘\0’ – null character • ‘\a’ – audible alert • ‘\b’ - backspace
Non-Ordinal Constants • float : 12.5E-12. -0.5 • double: 12.5E+200 always use doubles
Non-Primitive Data Types contain multiple values • arrays • classes (start with the idea of C’s structs) • Collections
Declaring Scalar Variables • short cake; • int i; • unsigned int value; • long face; • float icecream; • double mint; • boolean result;
Arrays int [ ] x = new int[20]; x[5] = 7; n=40; String [ ] names; names=new String[n]; //2 Dimensional Arrays Vehicle[ ][ ] parkingLot=new Vehicle[40][25];
Operators in Java • Assignment: = • Arithmetic : * / + - ++ -- % • Logical: && || ! • Relational: > < == <> • Bitwise: & | ^ << >> ~ • String: + • Grouping: () [] , • Triadic: (cond) ? value1 : value2
Operators in C • Operators can be binary or unary. • ?: is a special triadic operator. • Any binary operator can be combined with the assignmentoperator, ie:a*=3;is the same as a=a*3; • Assignment isn’t special – its an operator like any other a=b+(c=7);
Priority Operator Description 1 ()[ ]. Parentheses (grouping)Brackets (array subscript)Member selection Member selection via pointer 2 ++ --+ -! ~(type) Unary pre/post increment/ decrementUnary plus/minusUnary logical negation/bitwise complementUnary cast (change type)DereferenceAddress of size in bytes 3 * / % times/divide/mod 4 + - plus, minus 5 << >> bitwise left shift, bitwise right shift 6 < <=> >= less than, less than or equal to greater than, greater than or equal 2 7 = = != equal to, not equal to 8 & bitwise and 9 ^ bitwise xor 10 | bitwise or 11 && || logical and, logical or (short circuit operators 12 = += -= *= /= %= &= |= ^= <<== >>= Arithmetic Assignment Bitwise assignment 13 , comma: sequence operator Expressions: Operator Precedence
Expressions: Operator Precedence • When in doubt use brackets () • If you know the correct operator precedence, but aren’t so sure others will know it as well – use use brackets () • use brackets to make your meaning clear ( : - ) • did I mention you should use () ?
Expressions: Type Precedence • float + double double • float + int float • short * long long • char + int int • address + int address When 2 operands are of different types, the result is the larger or more complicated type When in doubt of the result, use the cast operator result = (float) (myDouble + myInt);
Expressions: Type Precedence Remember: x = 1/4; /* x 0 */ x = 1.0/7; /* x .25*/ C does very little type checking!!
Flow of Control: IF stmt if(condition) stmt; else stmt; if(x>10) System.out.print(“Too Big”); else System.out.print(“Value OK”);
Flow of Control: if stmt if(x>10 && x<20) { /* block of code */ } else { /* another block of code */ }
Secret Slide The triadic operator is a shorter form of if/then/else examples: if(x>10) y=2; else y=0; y= (x>10) ? 2 : 0 if(x>10) System.out.println(”X is big”); else System.out.println(”X is small”); System.out.println(x>10 ? “X is big” : “x is small”); if(a>b) return a; else return b; return (a>b) ? a : b;
Flow of Control: switch/case switch(ordinalValue) { case ‘A’: case ‘a’: puts(“A chosen”); break; case 2: puts(“# 2 choice”); break; default: puts(“None of the above”); }
while(condition) { int localValue; doStuff(); } Variables can be declared at the start of any block of code { } Flow of Control: while
while(true) { int localValue; doStuff(); } Forever loop: while
do { doStuff(); } while(condition); This kind of loop is always executed at least once. The test is at the end of the loop Flow of Control: do while
Flow of Control: for loops for(initialization; condition; increment) { doStuff(); ... } initialization
for(int i=0;i<10;i+=2) { for(init; cond; incr) { .... some code ... if(condition1) break; ... if(condition2) continue; } } break: exits the inner loop continue: jump to the end of the inner loop and loops around again The break and continue statements
for(int i=0;i<10;i++) {} for(;i;i--) {} for(;condition;) {} for(;;) {} Flow of Control: For Loops (cont’d)
Flow of Control: Labels and the dreaded Goto • You probably were not taught about the goto statement • If you were, you were told that it was bad • use break, continue, exit(n) instead • Use it only in emergencies ....
Flow of Control: An example of goto for ( ...) for(...) { if(errorCond) goto errorLabel; } errorLabel: fprintf(stderr,”Bad mojo – quitting program”);
I/O Java has no I/O commands. All I/O is performed using library functions
Output to the Console //Unformatted Output System.out.println(value1+val2+val3); //Formatted I/O String name="John Smith"; int age=20; System.out.printf(“Name: %-20s: Age: %4d\n” , name,age);
Frequently-Used Specifiers Specifier Output Example %ba boolean valuetrue or false %ca character'a' %da decimal integer 200 %fa floating-point number45.460000 %ea number in standard scientific notation4.556000e+01 %sa string"Java is cool"
String name;int age=20;//Wrap a Scanner around the input consoleScanner myScanner=new Scanner(System.in);//Input a stringSystem.out.print("Name: "); //Promptname=myScanner.nextLine();//Input an integerSystem.out.print("Age: "); //Promptage=myScanner.nextInt();System.out.printf("Name: %-20s: Age: %4d\n", name,age); Input from the Console
String name;int age=20;//Wrap a Scanner around the input consoleScanner myScanner=new Scanner(new File(“c:\\myData.txt”));//Input a whole line as a Stringname=myScanner.nextLine();//Input an integerage=myScanner.nextInt();System.out.printf("Name: %-20s: Age: %4d\n", name,age); Input from a file
Input from a web site on the Internet String name; int age; //This looks complicated – but only at first. All it is doing is creating a connection //to a remote file!Scanner myScanner=new Scanner( (new URL("http://munro.humber.ca/~king/abc.txt")) .openConnection().getInputStream()); //The rest is exactly the same name=myScanner.nextLine(); age=myScanner.nextInt(); System.out.printf("Name: %-20s: Age: %4d\n", name,age);
Getting Input from Input Dialog Boxes String input = JOptionPane.showInputDialog( "Enter an input");
(GUI) Confirmation Dialogs int option = JOptionPane.showConfirmDialog (null, "Continue");