Computer Science BSc Java programming Presentation 2 Dr

Computer Science BSc: Java programming Presentation 2 Dr. Gábor Pauler, Associate Professor, PTETTK, Room F 104, 6 th Ifjusag str. Pecs, Hungary Skype: gjpauler E-mail: pauler@t-online. hu Facebook and Open FTP sites of the course: https: //www. facebook. com/groups/574936103087671/ ftp: //gamma. ttk. pte. hu/pub/pauler/Java/

Content of the Presentation 3. Java syntax 3. 1. Sample project 3. 2. Comments 3. 3. Annotations 3. 4. Declarations 3. 4. 1. Uppercase-lowercase standards 3. 4. 2. Positioning variable/object declarations 3. 4. 3. Deallocation of resources 3. 5. Variable types 3. 5. 1. Passing values 3. 5. 2. Object type 3. 5. 3. Integer types 3. 5. 4. Floating point types 3. 5. 5. Date types 3. 5. 6. Logical types 3. 5. 7. Text types 3. 5. 8. Arrays 3. 5. 9. Lists 3. 6. Arithmetics 3. 6. 1. Type conversions 3. 6. 2. Text operators 3. 6. 3. Arithmetic operators 3. 6. 4. Logical operators 3. 6. 5. Operator precedency 3. 6. 6. Using simple math functions 3. 6. 7. Using complex math functions 3. 6. 8. Random class: random numbers 3. 7. Output tools 3. 7. 1. Numbers, text writeout on console 3. 8. Input tools 3. 8. 1. User input from console into variable 3. 9. Algorithm control 3. 9. 1. Conditional branching 3. 9. 2. Cycles 3. 9. 3. Exception handling

3. Java Syntax: 3. 4. Declarations 1 3. 1. Sample project: See Introduction project 3. 2. Comments: /*Text*/ - within line comments //Text – full line or end-of-line comment (Can be put at the end of lines at declaration of a method with very long parameter list, to explain meaning of individual parameters! Eg. : ) Double volume. Of. Cone(Double radius, Double height) {…} //Radius of base //Height of cone GUI|FRM: Code. Panel|FRM: Buttons|BTN: / / - converts forth and back marked text into comment or program code 3. 3. Annotations: Meta-controllers written into the code, eg. : @Deprecated others. Method – this marks a method obsolete, we keep it only in our code because somebody else still needs it. 3. 4. Declarations 3. 4. 1. Upper-lowercase rules: int my. Variable = 3; - My own variables and primitive types are lowercase (primitive types are already obsolete, do not use them!) Integer my. Variable = 3; - Modern type classes are uppercase (they can do much more than corresponding primitive type!) my. Instance = new My. Class(); - System- or my own classes are uppercase, their instances are lowercase, reserved words are lowercase blue System. out. println() - Declaring/calling methods of system- or my own classes is lowercase 3. 4. 2. Where to declare variables/objects? For most important ones it is recommended to declare at the beginning of a program block, but auxiliary stuff can be declared mid- block also.

3. Java Syntax: 3. 5. Variable types 3. 4. 3. Deallocating reserved resources Except using very large memory variables, this activity is done fully automatically by Garbage. Collector class in the background, which cleans class instances/variables from RAM not used for very long time 3. 5. Types of variables Java is a strongly-typed language: only variable type Object is non-typed, and can accept all types of data Therefore it is more difficult to learn than weakly typed PHP or Python, type conversions are terrible, needing more coding, eg. It does not auto-convert even integer types into each other But it helps to avoid the most evil, hard-detectable coding errors occouring at copying and reusing some part of the code elsewhere in modified format, and forgetting to make all proposed chages => strongly typed environment will give alarm for these errors. Type classes: they are modern and having many useful conversion methods, they are named uppercase: Integer Primitive types: they have limited functionality, they are already obsolete, do not use them. They are named lowercase: int 3. 5. 1. Passing values what. Gets = what. Gives; - Passing values goes from right to left want. To. Be. Empty = null; - null means there is no instance of a class, or we remove existing instance of a class. 3. 5. 2. Object type: Object (Pointer, 4 bytes) – it can accept any type of content, but just stores it and WILL NOT AUTOCONVERT it (eg. Making floating point number from integer). It is mainly used in the practice to accept data coming from database table fields, because they can have many types.

3. Java Syntax: 3. 5. Variable types: 3. 5. 3. Integer types 3. 5. 3. The most important integer types: Integer 2 bytes -32 K. . +32 K. int. Value(my. Integer. Toint) – MET converts it from class type to primitive type, if mixing up with some other class can be a problem Long 4 bytes -2. 4 Md. . +2. 4 Md – because of strong typedness Integer – Long is not autoconverted. Result of making division on integer will be the integer part of the result 3. 5. 4. The most important floating point types Double 8 bytes 15 valuable digits – storing fractional numbers 3. 5. 5. The most important date type Epoch. Time 8 bytes – Number of seconds passed since Jan 1, 1970, 00: 00 Its date handling fuctions are in Date class 3. 5. 6. Logical types Boolean my. Logic. Variable = true; - can be true, false, null my. Logic. Variable = Boolean. TRUE; - calls method of a type class 3. 5. 7. The most important text type String my. Text =„Blahblah"; – max. 65535 chars, Netbeans can handle Unicode character table, but MS Java compiler unfordunately not! my. Text. equals(„Blahblah") – MET comparison for String type class instances, the ==, DOES NOT WORK HERE! But if String class typed variable has to be compared with null missing value, then: my. Text == null

3. Java Syntax: 3. 5. Variable types: 3. 5. 8. Arrays 3. 5. 8. Array(Tömb): it stores multiple values of any variable type or class, reachable by index starting from 0, they can be multi dimensional, inserting new element is possible only in 1 dimension, after the last element String[] my. Arr = {}; - declare 1 dimension, without size, starting values String[] my. Arr = {"Val 1", "Val 2"}; - declare 1 dimension, with values my. Text = my. Arr[0]; my. Arr[0] = my. Text; - reading/writing value from/to 0 th array element, index of array always starts from 0!!! String[][] my 2 Dim. Arr = new String[5][10]; - declare 2 dimensions, with size, empty String[][] my. Sports. Stars = new String[5][]; - declare 2 dimensions, one with size (eg. 5 Sports), other dimension’s size may be decided later (eg. I want to store varying number of Stars by 5 Sports) my. Sports. Stars[0] = new String[10]; - declaring second dimension with size (eg. 10 Stars) into given element of first dimension (eg. Sport 0: soccer) my. Arr = add. Element(my. Arr, "Val 3”); - add compatible type element at the end of one dimensional array my. Arr. length – PRP size of array in elements, counting starts from 1!!! my. Text. char. At(i) – MET reach ith character of a string 3. 5. 9. List(Lista): it stores multiple values of any variable type or class, reachable by index starting from 0 or by sequentially, can be only 1 dimensional, insert of new element is possible to any of its position. 3. 5. 9. 1. Array. List(Tömb. Lista): list of variables/objects optimized for random access: Elements can be modified faster than in chained list But its sequential reading is slower than chained list It van contain any variable type or class

3. Java Syntax: 3. 5. Variable types: 3. 5. 9. Lists: 3. 5. 9. 1. Array. List import java. util. Array. List; - Import it at package header Array. List<String> my. List = new Array. List(); - Declare list my. List. add(„Text"); - MET adding new element at end, if you insert a class instance it is inserted by reference, not by value! my. Lista. add(i, "Szoveg"); - MET insert ith element by reference, old one is pushed further to i+1 th! my. Text = my. List. get(i); - MET read ith element, index starts with 0!!! my. List. set(i, „Text"); - MET write ith element, index starts with 0!!! System. out. println(my. List); - MET writing content of all list elements to console my. List. Clear; - MET remove all elements, list stays there empty my. List. remove(i. int. Value()); - MET remove ith element. Here convert index back to primitive type preventing it to mix up with Integer class typed list element!!! my. List. equals(other. List) – MET compare with other list my. Size = my. List. Size; - PRP get size of list, counting starts with 1!!! 3. 5. 9. 2. Linked. List(Láncolt lista): list of variables/objects optimized for sequential access: Fast sequential reading, Slower modification/delete than arraylist import java. util. Linked. List; - Import it at package header Linked. List<String> my. List = new Linked. List(); - Declare List my. Lista = new Linked. List(); - If it is declared without type, elements will be Object Handling is similar to Array. List

Content of the Presentation 3. Java syntax 3. 1. Sample project 3. 2. Comments 3. 3. Annotations 3. 4. Declarations 3. 4. 1. Uppercase-lowercase standards 3. 4. 2. Positioning variable/object declarations 3. 4. 3. Deallocation of resources 3. 5. Variable types 3. 5. 1. Passing values 3. 5. 2. Object type 3. 5. 3. Integer types 3. 5. 4. Floating point types 3. 5. 5. Date types 3. 5. 6. Logical types 3. 5. 7. Text types 3. 5. 8. Arrays 3. 5. 9. Lists 3. 6. Arithmetics 3. 6. 1. Type conversions 3. 6. 2. Text operators 3. 6. 3. Arithmetic operators 3. 6. 4. Logical operators 3. 6. 5. Operator precedency 3. 6. 6. Using simple math functions 3. 6. 7. Using complex math functions 3. 6. 8. Random class: random numbers 3. 7. Output tools 3. 7. 1. Numbers, text writeout on console 3. 8. Input tools 3. 8. 1. User input from console into variable 3. 9. Algorithm control 3. 9. 1. Conditional branching 3. 9. 2. Cycles 3. 9. 3. Exception handling

3. Java Syntax: 3. 6. Arithmetics: 3. 6. 1. Type conversions 3. 6. Arithmetics 3. 6. 1. Type conversions(Típuskonverziók) As Java is a strongly typed language, it never converts anything automatically, even between very similar type classes This makes coding more slow and hard to learn than in non-strongly typed languages (eg. Python, PHP, Java. Script) But time invested in that pays off well in business/problem environments with many difficult math computations (danger of floating point over/uderflow(Lebegőpontos túl/alul csordulás)), many Measure unit(Mértékegység) conversions Also it reduces probability of hard to detect errors at copying and reusing chunks of code and forgetting make changes => they will probably jump up because of strong typedness 3. 6. 1. 1. At Non-relative(Nem-rokon) type classes, we have parse methods: my. Int. Number = String. parse. Int(my. Text); - MET it works only if text can be compiled into number! my. Int. Number = Double. parse. Int(my. Fraction); - MET be aware of that it is not rounding, but keeping integer part! (eg. 3. 8 will be 3 not 4) my. Fraction = Integer. parse. Double(my. Int. Number); - MET it is not automatic! my. Int. Number = my. Long. Int. short. Value(); - MET it is not automat. ! my. Text = my. Int. Number. to. String(); - MET it is not automatic! 3. 6. 1. 2. At Relative(Rokon) type classes we use Type casting(Típuskényszer): Double my. Fraction = 3. 14; my. Int. Number = (Integer)my. Fraction; - type casting into integer my. Text = my. Int. Number + " "; - be aware of this annoying exception!!!

3. Java Syntax: 3. 6. Arithmetics: 3. 6. 1. Type conversions 3. 6. 1. 3. Date conversions 3. 6. 1. 3. 1. Giving simple date constant, date from numbers (obsolete) public static final Date my. Date. Given = new Date(120, 0, 1); - here year 0 is 1900, month 0 is Januar, first day is 1! 3. 6. 1. 3. 2. Get numbers from parts of date: my. Minutes = my. Date. get. Minutes(); - MET extracts minutes 3. 6. 1. 3. 3. Converting string into date, which complies rules of a language: First it defines a formatting mask (eg. US date with English lang. ) public static final Date. Format my. Date. Format = new Simple. Date. Format("MMMMM d, yyyy", Locale. ENGLISH); String text. Date = „July 6, 2019”; //Input text date Date my. Date = null; //Compulsory to initialize date type! try { //Try to convert text into date my. Date = my. Date. Format. parse(text. Date); //MET convert } catch (Exception e) { //Handle errors, compulsory! System. out. println(e. to. String+”Bad date txt: ”+text. Date); } 3. 6. 1. 3. 4. Converting date into string, which complies rules of a language: public static final Date. Format my. Date. Format = new Simple. Date. Format("MMMMM d, yyyy", Locale. ENGLISH); text. Date = my. Date. Format. format(my. Date); // MET Gets back „July 6, 2019”

3. Java Syntax: 3. 6. Arithmetics: 3. 6. 2. Text operators all. Text = my. Text + other. Text; - Concatenation of strings 3. 6. 3. Arithmetic operators (not shown here which are the same in all other languages) if a == b {…}; - Comparing values is double equals!!! Simple equals works here as passing values being true if succesful, totally misleading!!! if a === b {…}; - Comparing values and variable types is triple equals if a != b {…}; - Nonequalty test a += 1; a++; - Incrementing variable value a -= 1; a--; - Decrementing variable value a / b; - At fractions it is division, at integers it is division with modulus a % b; - Modulus value at dividing integers if a. equals(b) {…} – Comparison of 2 instances of a class: At type classes: It compares values: Strings can be compared correctly only this way, do not use there ==, except == null can be used! At complex classes: It compares wether a and b are the very same instances of the same complex class If all property values of 2 different instances of the same complex class are equal, it DOES NOT SHOW EQUALTY, because auto-generated unique identifier of the 2 instances will be different!!! This is totally stupid, therefore you have to code all complex class instance comparisons by hand!!! 3. 6. 4. Logic operators if !my. Bool. Val {…} – Logic NOT if (my. Bool. Val 1 & & my. Bool. Val 2) {…} – Logic AND, can be used among multiple operands also my. Int. Val 3 = my. Int. Val 1 & my. Int. Val 2; - Bitwise AND if (my. Bool. Val 1 || my. Bool. Val 2) {…} – Logic OR, can be used among multiple operands also my. Int. Val 3 = my. Int. Val 1 | my. Int. Val 2; - Bitwise OR

3. Java Syntax: 3. 6. Arithmetics: 3. 6. 5. Operator precedence 3. 6. 5. Operator precedency Multiplications and divisions are done first: *, / Then addition and subtraction: +, Then math relations: ===, !=, <=, >=, <>, <, > Then logic operators with their internal precedence: ! && || 3. 6. 6. Simple math functions They are in the Math class, which does not have to be impported manually, eg. : my. Result = Math. sqrt( my. Input ); - MET square root 3. 6. 7. Complex math functions They are in separate classes, which should be imported, and instance created, eg. : 3. 6. 8. Random class: generating random numbers. Eg. code for generating integer random numbers in some range: //At package header… import java. util. Random; // Import Random class //At the beginning of Main static method… Random my. Random = new Random(); // Creating instance //At inside my method… my. Int. Rand. Num = my. Random. next. Int(3); //Random number 0. . 2 my. Int. Rand. Num++; //Pushing to interval 1. . 3

Content of the Presentation 3. Java syntax 3. 1. Sample project 3. 2. Comments 3. 3. Annotations 3. 4. Declarations 3. 4. 1. Uppercase-lowercase standards 3. 4. 2. Positioning variable/object declarations 3. 4. 3. Deallocation of resources 3. 5. Variable types 3. 5. 1. Passing values 3. 5. 2. Object type 3. 5. 3. Integer types 3. 5. 4. Floating point types 3. 5. 5. Date types 3. 5. 6. Logical types 3. 5. 7. Text types 3. 5. 8. Arrays 3. 5. 9. Lists 3. 6. Arithmetics 3. 6. 1. Type conversions 3. 6. 2. Text operators 3. 6. 3. Arithmetic operators 3. 6. 4. Logical operators 3. 6. 5. Operator precedency 3. 6. 6. Using simple math functions 3. 6. 7. Using complex math functions 3. 6. 8. Random class: random numbers 3. 7. Output tools 3. 7. 1. Numbers, text writeout on console 3. 8. Input tools 3. 8. 1. User input from console into variable 3. 9. Algorithm control 3. 9. 1. Conditional branching 3. 9. 2. Cycles 3. 9. 3. Exception handling

3. Java Syntax: 3. 7. Output tools: 3. 7. 1. Console 3. 7. Output tools 3. 7. 1. Writing text and numbers into console It will NOT DO any type conversion during writing. If you want write out content of a numeric variable, concatenate some strings to it also to enforce type casting! System. out. println(my. Int. Val + my. Text + „Blahblah"); Writes separated line System. out. print(„Blahblah"); - Writes in one line consecutively System. out. print("n"); - Writes Enter character to end line System. out. print("t"); - Writes Tab character to equally space columns to write out nicely aligned table columns on console 3. 8. Input tools 3. 8. 1. Entering value to given type class variable from console //At package header… import java. util. Scanner; // Import Scanner class //At the beginning of Main static method… Scanner my. Input = new Scanner(System. in); // Create new instance //At my method… my. Int. Val = my. Input. next. Int(); //MET reads the next word (separated by spaces/enters) from text input stream on console, tries to compile into an integer

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 1. Conditions 3. 9. Algoritm control(Vezérlési szerkezetek) 3. 9. 1. Selections(Elágazások) 3. 9. 1. 1. Simple if if ( a == b ) { //Condition //If branch } 3. 9. 1. 2. Two-branch if if ( a == b ) { //Condition //If branch } else { //Else branch } 3. 9. 1. 3. Multi-branch if if ( a == b ) { //Condition //If branch } else if ( a == c ) { //Alternative condition, examined only when earlier coditions fail! //Alternative branch } else { //Else branch }

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 1. Conditions 3. 9. 1. 4. Switch(Elágazás) If you do not put break at the end of branches, it tries to search for next fitting branch also! switch (my. Numeric. Variable) { case my. Value 1: //First branch break; case my. Value 2: //Second branch break; default: //Optional branch: if nothing else matches } 3. 9. 2. Cycles(Ciklusok) 3. 9. 2. 1. Fixed iterations(Fix pörgésszámú), Pre-testing(Elöltesztelő): for At the header, it has 3 clausules, 2 nd, 3 rd are optional, making it while: Type class declaration and Initial value(Kezdőérték) of Cycle variable(Cilusváltozó): can be Integer, Long, Double, String, Boolean. Best Practice: they are traditionally named i, j, k, l Limit of cycle variable. Best Practice: use i < limit, as array/list indices are counted from 0 but their size is from 1! Break: jumps out from the whole cycle to its end Continue: jumps out from current iteration to beginning of next Increment(Növekmény) of cycle variable: can be <0 or >1 also

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 2. Cycles can be nested into each other in more levels. They are usually used to handle multi-dimensional arrays or lists nested in lists. break my. Label; - it can jump out from cycle not only to its top level cycle, but top-top level also, if that is labeled with my. Label: at the beginning of its starting row You cannot give more cycle variables for one cycle (like it can be done in C#) to avoid need of nesting cycles. Best Practice: use break to leave cycle if you want to find 1 st thing only! for (Integer i = 0; i<10; i+=1) { //Cycle header(Fejléc) System. out. println(i+”. ”); //Cycle core(Ciklusmag) if ( i == 5 ) { //Jumpout condition(Kiugrási feltétel) break; //Jump out from whole cycle continue; //Jump out from current iteration only } } 3. 9. 2. 2. Non-fixed iterations(Nem fix pörgésszámú), Pre-testing(Elöltesztelő) No cycle variable is included, if you need, you have to define manually Best Practice: put manual increment of cycle variable at the end of core! Integer i = 0; //Manual declaration and initial value while (i < 10) { //Cycle header with condition System. out. println(i); //Cycle core if ( i == 5 ) { //Pre-finish jump out condition break; //Jump out from whole cycle continue; //Jump out from current iteration only } i++; //Manual incrementation }

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 2. Cycles 3. 9. 2. 3. Non-fixed iterations(Nem fix pörgésszámú), Back-testing(Hátultesztelő) Integer i = 0; //Declaration and initialization do { //Unconditional core start, it runs at least once! System. out. println(i); //Cycle core if ( i == 5 ) { //Jomp out condition break; //Jump out from whole cycle continue; //Jump out from current iteration only } i++; //Incrementing after cycle core } while ( i < 10 ); //Post-testing 3. 9. 2. 4. Two-clausule for cycle to step sequentially on elements of Array, List It can READ ONLY, cannot write in Array, List!! Index of Array, List is hidden, you have to create manually break, continue work here also Integer i = 0; //Declare and initialize manual index for(String my. Text. Cyc. Var : my. Text. List) { //Cycle variable (the actual element) here can be String, Object also! System. out. println(my. Text. Cyc. Var); //Cycle core i++; //Incrementing manual index } 3. 9. 2. 5. Simple cycle with MET for. Each of Numbers: Numbers. for. Each((cyc. Var) -> System. out. println(cyc. Var));

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 3. Exceptions 1 3. 9. 3. Exception handling(Kivételkezelés) It defines a block in code – the try block – where: try { Any kind of runtime errors can occour, but the system WILL NOT terminate running the code immediately, just creates an instance of an Exception class, collecting all possible info about the error. Alternatively, if we detect some error runtime ourselves, it is Best Practice: we can create our own exception with a given type, and error text to signal to the whole system that there is an error. (Here DON’T just simply write out a text error message to console, because the system and front end will not see that!) throw new Runtime. Exception("My error text here"); } If exception is created, execution jumps to a separate catch block of the code, where: catch (Exception e) { An instance from the exception created, by Best Practice: with name e You can examine its properties: error message: e. to. String(), which casses|methods were called before: e. get. Stack. Trace(), then: If you can resolve the error in local code, solve it (very infrequent) If user should be notified locally, write them out it to console: System. out. println(e. get. Stack. Trace() + e. to. String() + " ERROR: " + my. Err. Value); If you can’t solve the error, create a new exception again adding your local information to it. This way all the system and even frontend can analyze and react on that later: throw new Runtime. Exception(e. get. Stack. Trace() + e. to. String() + " ERROR: " + my. Err. Value); }

3. Java Syntax: 3. 9. Algorithm control: 3. 9. 3. Exceptions 2 Optionally you can define a finally block of the code, which runs regardless that an exception was created and caught: finally { //We usually put releasing big resources here } Best Practice: If your algorithm in general does not use very big resorces (eg. matching postal addressess), but handling a possible error itself has high resource consumption (eg. correcting mistyped street types from a dictionary in a given language), you can declare class instances at the header line of try, which are only valid in try-catch blocks, so whenever they are finished, these resources will be removed, and you do not have to take care about releasing them manually: try (Object my. Object = new Object()) { } Catch (Exception e) { }

References w 3 Schools complete Java syntax reference: https: //www. w 3 schools. com/java_syntax. asp Stack overflow q&A, forums: https: //stackoverflow. com/questions

List of Symbols General Symbols: DEF: definition, PRC: process, ALT: alternatives, CYC: cycle, : inference, : contradicts, / : dis/advantage, URL: webaddress DIR: directory, PCK: package, CLS: class, PRP: property MET: method EVN: event EXC: exception Symbols of Graphic User Interface: Aaa|Bbb|-Menu|Submenu, SCR: Screen, FRM: Frame, ID: Unique identifier, BTN: Button, TXB: Textbox, DDN: Dropdown, TAB: Multi. Tabs, CHK: Checkbox RAD: Radio button, TBL: Table COL: Table. Column, LIN: Table. Row, KEY: Keyboard, WRN: Popup warning ERR: Error message Logic Symbols: a&&b: a and b, a&b: binary and, a||b: a or b, a|b: binary or !a: not a Math Symbols: a = b passing value a == b value equals a === b value and type equals a. equals(b) class instance equals != value not equals a / b division or integer division a % b modulus of integer division a + b addition or concatenation Database Symbols: : Entity, ▬◄: 1: many relation ►▬: Many: 1 relation ---▬: independent/dependent side PK: Primary key FK: Foreign key UML Class Diagram Symbols: +PRP: public property, -PRP: private property, #PRP: protected property, ~PCK: package, /CLS: descendant class, Owner◄─Nested: nesting connection Ancestor∆┘Descendant: inheritance conn. Whole♦┘Oblig. Part: obligatory part
- Slides: 22