Example: bachelor of science

Introduction to the Java Programming Language

Software Design ( java Tutorial)Software Design ( java Tutorial) SERGS oftware DesignIntroduction to the java Programming LanguageMaterial drawn from [JDK99,Sun96,Mitchell99,Mancoridis00]Sof tware Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Features Write Once, Run Anywhere. Portability is possible because of java virtual machine technology: Interpreted JIT Compilers Similar to C++, but cleaner : No pointers, typedef, preprocessor, structs, unions, multiple inheritance, goto, operator overloading, automatic coercions, Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Subset for this Course We will focus on a subset of the Language that will allow us to develop a distributed application using CORBA. Input and output will be character (terminal) based. For detailed treatment of java visit: Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Virtual Machine java programs run on a java Virtual Machine.

Software Design (Java Tutorial) © SERG Java Subset for this Course • We will focus on a subset of the language that will allow us to develop a distributed

Tags:

  Introduction, Programming, Language, Tutorials, Java, Introduction to the java programming language

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of Introduction to the Java Programming Language

1 Software Design ( java Tutorial)Software Design ( java Tutorial) SERGS oftware DesignIntroduction to the java Programming LanguageMaterial drawn from [JDK99,Sun96,Mitchell99,Mancoridis00]Sof tware Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Features Write Once, Run Anywhere. Portability is possible because of java virtual machine technology: Interpreted JIT Compilers Similar to C++, but cleaner : No pointers, typedef, preprocessor, structs, unions, multiple inheritance, goto, operator overloading, automatic coercions, Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Subset for this Course We will focus on a subset of the Language that will allow us to develop a distributed application using CORBA. Input and output will be character (terminal) based. For detailed treatment of java visit: Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Virtual Machine java programs run on a java Virtual Machine.

2 Features: Security Portability Superior dynamic resource management Resource location transparency Automatic garbage collectionSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGThe java EnvironmentJava Source File (*. java ) java Compiler (javac) java Bytecode File (*.class) java Virtual Machine ( java )Software Design ( java Tutorial)Software Design ( java Tutorial) SERGP rogram OrganizationSourceFiles (. java )JAVABYTECODECOMPILERC lassFiles (.class)RunningApplicationJAVA VIRTUAL MACHINER unningAppletWEB BROWSERS oftware Design ( java Tutorial)Software Design ( java Tutorial) SERGP rogram Organization Standards Each class is implemented in its own source file. Include one class per file: Name of the java file is the same as the class name. java applications must include a class with a mainmethod. , public static void main(String args[])Software Design ( java Tutorial)Software Design ( java Tutorial) SERGS tructure of a simple java Program Everything must be in a class.

3 java applications (not Applets) must have a main()routine in one of the classes with the signature: public static void main(String [] args)class HelloWorld{public static void main(String [] args){ ( Hello World! );}}Software Design ( java Tutorial)Software Design ( java Tutorial) SERGC ompiling and Running the Hello World Program Compile: javac Run: java HelloWorld Output: Hello World Software Design ( java Tutorial)Software Design ( java Tutorial) SERGC omments java support 2 commenting styles // Line Comments /* Block Comments */Software Design ( java Tutorial)Software Design ( java Tutorial) SERGData Types Basic types: byte, boolean, char, short, int, long, float, double. New types cannot be created in java . Must create a java class. java arrays are supported as classes. , int[] i = new int[9] size of an array Design ( java Tutorial)Software Design ( java Tutorial) SERGS calar Data Types In java Standard java data types: byte1 byte boolean1 byte char2 byte (Unicode) short2 byte int4 byte long8 byte float4 byte double8 byte<data type> variable_name;int x;Software Design ( java Tutorial)Software Design ( java Tutorial) SERGJava is Strongly Typed java is a strongly typed Language .

4 Strong typing reduces many common Programming errors. Seems inconvenient to C/C++ Design ( java Tutorial)Software Design ( java Tutorial) SERGJava is Strongly Typed (Cont d) Assignments must be made to compatible data types. To contrast, in C: No difference betweenint, char, and boolean Implicit type casts (automatic type promotion) between many Design ( java Tutorial)Software Design ( java Tutorial) SERGV ariables Variables may be tagged as constants (finalkeyword). Variables may be initialized at creation time finalvariables mustbe initialized at creation time Objects are variables in java and must be dynamically allocated with the newkeyword. ,a = new ClassA(); Objects are freed by assigning them to null, or when they go out of scope (automatic garbage collection). ,a = null;Software Design ( java Tutorial)Software Design ( java Tutorial) SERGV ariables (Cont d)int n = 1;char ch = A ;String s = Hello ; Long L = new Long(100000);boolean done = false;final double pi = ;Employee joe = new Employee(); char [] a = new char[3];Vector v = new Vector();Software Design ( java Tutorial)Software Design ( java Tutorial) SERGP ointers & References Variables java does not support pointers.

5 All variables are passed by value except objects. java classes either: Reference an object (new keyword) Alias an object (assign to another object)Software Design ( java Tutorial)Software Design ( java Tutorial) SERGE xpressions java supports many ways to construct expressions (in precedence order): ++,--Auto increment/decrement +,-Unary plus/minus *,/ Multiplication/division % Modulus +,-Addition/subtractionSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGE xamples of Expressionsint x,y,z;x = 0;x++;y = x + 10;y = y % 5;z = 9 / 5;Software Design ( java Tutorial)Software Design ( java Tutorial) SERGA ssignment Operators Assignment may be simple x = y Or fancy with the following operators: *=, /= %= +=, -= &= (bitwise AND) |= (bitwise OR) ^= (bitwise exclusive OR)Software Design ( java Tutorial)Software Design ( java Tutorial) SERGE xamples ofAssignment Operatorsint i = 5;i += 10;// i = 15i %= 12;// i = 3 Software Design ( java Tutorial)Software Design ( java Tutorial) SERGC onditional Logic Conditional logic in java is performed with the ifstatement.

6 Unlike C++ a logic expression does not evaluate to 0 (FALSE) and non-0 (TRUE), it evaluates to either trueor false true, falseare values of the booleandata type. Building compound conditional statements && (And), || (Or), ! (Not), <, >, ==, !=, <=, >=, Design ( java Tutorial)Software Design ( java Tutorial) SERGE xample of Conditional Logicint i = 8;if ((i >= 0) && (i < 10)) (i + is between 0 and 9 ); (i + is larger than 9 or less than 0 );Software Design ( java Tutorial)Software Design ( java Tutorial) SERGCode Blocks java , like many other languages, allows compound code blocks to be constructed from simple statements. Simply enclose the block of statements between braces. ,{Statement1;Statement2;Statement3;}Soft ware Design ( java Tutorial)Software Design ( java Tutorial) SERGL ooping Constructs java supports three looping constructs: while forSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGE xamples of Looping Constructsfor (int i = 0; i < 10; i++){ (i);}int i = 0;while(i < 10){ (i++); //prints i before}//applying i++int i = 0;do{ (i++);} while(i < 10)Software Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Exception Handling An exceptionis an object that defines an unusual or erroneous situation.

7 An exception is thrownby a program or a runtime environment and can be caughtand handled appropriately. java supports user-defined and predefined exceptions: ArithmeticException ArrayIndexOutOfBoundsException FileNotFoundException InstantiationExceptionSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Exception Handling (Cont d) Exception handling allows a programmer to divide a program into a normal execution flowand an exception execution flow. Separation is a good idea especially since 80% of execution is in 20% of the code (normal flow).Software Design ( java Tutorial)Software Design ( java Tutorial) SERGJava Exception Handling (Cont d) If an exception is not handled the program will terminate (abnormally) and produce a class DivideBy0 {public static void main (String[] args) { (10 / 0);}} : / by zeroat (DivdeBy0:3)Software Design ( java Tutorial)Software Design ( java Tutorial) SERGT ryand Catchstatements If an exception is thrown in statement-list1, control is transferred to the appropriate (with same exception class) catch handler.

8 After executing the statements in the catch clause, control transfers to the statement after the entire try {statement-list1} catch (exception-class1 variable1) {statement-list2} catch (exception-class2 variable2) {statement-list3} catch ..Software Design ( java Tutorial)Software Design ( java Tutorial) SERGE xception Propagation If an exception is not caught and handled where it occurs, it propagates to the calling Design ( java Tutorial)Software Design ( java Tutorial) SERG class Demo {static public void main (String[] args) {Exception_Scope demo = new Exception_Scope(); ( Program beginning ); ( ); ( Program ending );}}class Exception_Scope {public void L3 ( ) { ( Level3 beginning ); (10/0); ( Level3 ending );}public void L2 ( ) { ( Level2 beginning );L3( ); ( Level2 ending );}public void L1 ( ) { ( Level1 beginning );try { L2 ();} catch (ArithmeticException problem) { ( ( )); ( );} ( Level1 ending ).}}

9 }} OUTPUT:OUTPUT:Program beginningLevel1 beginningLevel2 beginningLevel3 beginning/ by : / by zeroat ( :18)at ( :24)at ( :31)at ( :7)Level1 endingProgram endingSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGT hrowing an Exceptionimport ;public class Demo {public static void main (String[] args) throws Doh {Doh problem = new Doh ( Doh! );throw problem;// ( Dead code );}}class Doh extends IOException {Doh (String message) {super(message);}} The exception is thrown but not :OUTPUT:Doh: Doh!at ( :4)Software Design ( java Tutorial)Software Design ( java Tutorial) SERGF inallyclause A trystatement may have a finallyclause. The finallyclause defines a section of code that is executed regardless of how the tryblock in {statement-list1} catch (exception-class1 variable1) {statement-list2} catch ..} finally {statement-list3}Software Design ( java Tutorial)Software Design ( java Tutorial) SERGI/O java supports a rich set of I/O libraries: Network File Screen (Terminal, Windows, Xterm) Screen Layout PrinterSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGI/O (Cont d) For this course we only need to write to or read from the terminal screen or file.

10 Use: () () May use + to concatenateint i, j;i = 1;j = 7; ( i = + i + j = + j);Software Design ( java Tutorial)Software Design ( java Tutorial) SERGI/O Example with Reading and Writing from or to the Screen import *;public class X {public static void main(String args[]){try{BufferedReader dis = new BufferedReader(new InputStreamReader( )); ("Enter x ");String s = ();double x= ( ()).doubleValue();// trim removes leading/trailing whitespace and ASCII control ("x = " + x);} catch (Exception e) { ("ERROR : " + e) ; ( );}}Software Design ( java Tutorial)Software Design ( java Tutorial) SERGI/O Example with Reading and Writing from or to the Fileimport *;import *;// Program that reads from a file with space delimited name-pairs and// writes to another file the same name-pairs delimited by a P{public static void main(String [] args){BufferedReader reader_d;int linecount = 0;Vector moduleNames = new Vector();try {reader_d = new BufferedReader(new FileReader(args[0]));// continued on next pageSoftware Design ( java Tutorial)Software Design ( java Tutorial) SERGI/O Example with Reading and Writing from or to the File (Cont d)//.}}}}


Related search queries