Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.



Download to read offline

Introduction to-programming

Download to read offline

Introduction to programming with Java - types and variables, conditional statements, loops, arrays

Related Books

Free with a 30 day trial from Scribd

See all

Introduction to-programming

  1. 1. Introduction to Java Programming
  2. 2. Contents <ul><li>The Structure of Java Programs </li></ul><ul><li>Keywords and Identifiers </li></ul><ul><li>Data Types </li></ul><ul><ul><li>Integral, Textual, Floating-Point </li></ul></ul><ul><ul><li>Enumerations </li></ul></ul><ul><li>Variables, Declarations, Assignments, Operators </li></ul>
  3. 3. Contents <ul><li>Expressions and Statements </li></ul><ul><ul><li>Logical Statements </li></ul></ul><ul><ul><li>Loop Statements </li></ul></ul><ul><li>Console Input and Output </li></ul><ul><li>Arrays and Array Manipulation </li></ul><ul><li>Using the Java API Documentation </li></ul>
  4. 4. Programming in Java
  5. 5. The Java API <ul><li>A set of runtime libraries </li></ul><ul><li>Available on any JVM </li></ul><ul><li>Provide platform-independent standard </li></ul><ul><ul><li>Classes and interfaces </li></ul></ul><ul><ul><li>Security </li></ul></ul><ul><li>Platform independence difficulties </li></ul><ul><li>Implementation is specific to the host platform </li></ul>
  6. 6. What is Java API Documentation? <ul><li>Java documentation is HTML based </li></ul><ul><ul><li>Also called &quot; Java Platform Standard Edition API Specification &quot; </li></ul></ul><ul><li>Complete documentation of all standard classes and methods </li></ul><ul><ul><li>Descriptions of all the functionality </li></ul></ul><ul><ul><li>Links to related articles </li></ul></ul><ul><li>Use local copy or the Web version from </li></ul>
  7. 7. Java API Documentation
  8. 8. A Java Program
  9. 9. The Java Programming Language <ul><li>Quite general-purpose </li></ul><ul><li>Boosts developer productivity </li></ul><ul><li>Combines proven techniques </li></ul><ul><li>Software technologies </li></ul><ul><ul><li>Object-orientation </li></ul></ul><ul><ul><li>Multi-threading </li></ul></ul><ul><ul><li>Structured error-handling </li></ul></ul><ul><ul><li>Garbage collection </li></ul></ul><ul><ul><li>Dynamic linking and extension </li></ul></ul>
  10. 10. Writing Java Programs <ul><li>Write custom source code </li></ul><ul><ul><li>In the Java programming language </li></ul></ul><ul><ul><li>Using the Java API </li></ul></ul><ul><li>Compile the source code </li></ul><ul><ul><li>Using the “ javac ” compiler command </li></ul></ul><ul><ul><li>Compiles to bytecodes </li></ul></ul><ul><li>Run the compiled code </li></ul><ul><ul><li>Using the “ java ” launcher command </li></ul></ul>
  11. 11. Java Program – Example public class HelloJava { public static void main(String[] args) { System.out.println(&quot;Hello, Java!&quot;); } } javac java –cp . HelloJava Hello, Java!
  12. 12. Typical Errors <ul><li>Compile-Time Errors </li></ul><ul><ul><li>javac: Command not found </li></ul></ul><ul><ul><li> Method printl(java.lang.String) not found in class </li></ul></ul><ul><ul><li> Public class HelloJava must be defined in a file called &quot;;. </li></ul></ul>
  13. 13. Typical Errors <ul><li>Runtime Errors </li></ul><ul><ul><li>Can’t find class HelloJava </li></ul></ul><ul><ul><li>Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: HelloJava/class </li></ul></ul>
  14. 14. Structure of Java Programs
  15. 15. The Source File Contents <ul><li>Java source code files can have t hree &quot;top-level&quot; elements: </li></ul><ul><ul><li>An optional package declaration </li></ul></ul><ul><ul><li>Any number of import statements </li></ul></ul><ul><ul><li>Class and interface declarations </li></ul></ul>package jeecourse.example; import*; public class SomeClass { // ... }
  16. 16. Classes and Packages <ul><li>Classes are the main program unit in Java </li></ul><ul><ul><li>Contain the source code of the program logic </li></ul></ul><ul><ul><li>Can define fields </li></ul></ul><ul><ul><li>Can contain methods (subprograms) </li></ul></ul><ul><li>Packages are containers for classes </li></ul><ul><ul><li>Can be nested hierarchically </li></ul></ul><ul><ul><li>Each package can contain multiple classes </li></ul></ul>
  17. 17. Important Java Packages <ul><li>Important packages within the Java class library are: </li></ul><ul><ul><li>java.lang </li></ul></ul><ul><ul><li>java.util </li></ul></ul><ul><ul><li> </li></ul></ul><ul><ul><li>java.text </li></ul></ul><ul><ul><li>java.awt </li></ul></ul><ul><ul><li> </li></ul></ul><ul><ul><li>java.applet </li></ul></ul>
  18. 18. Java Programs <ul><li>Java programs are sets of class definitions </li></ul><ul><li>The main() method is the entry point for standalone Java applications </li></ul><ul><li>The signature for main() is : </li></ul><ul><li>T he name args is purely arbitrary: </li></ul><ul><ul><li>A ny legal identifier may be used, provided the array is a single-dimension array of String objects </li></ul></ul>public static void main(String[] args)
  19. 19. Programs, Classes, and Packages – Example package jeecourse.example; import*; public class SomeClass { private static int mValue = 5; public static void printValue() { System.out.println(&quot;mValue = &quot; + mValue); } public static void main(String[] args) { System.out.println(&quot;Some Class&quot;); printValue(); } }
  20. 20. Keywords, Identifiers, Data Types
  21. 21. Keywords <ul><li>A keyword is a word whose meaning is defined by the programming language </li></ul><ul><li>Anyone who claims to be competent in a language must at the very least be familiar with that language’s keywords </li></ul><ul><li>Java’s keywords and other special-meaning words are listed in the next slide </li></ul>
  22. 22. Java Language Keywords abstract continue for new switch assert  default goto   package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum  instanceof return transient catch extends int short try char final interface static void class finally long strictfp  volatile const   float native super while
  23. 23. Reserved Words <ul><li>You may notice null , true , and false do not appear anywhere on the keywords list </li></ul><ul><li>true , false , and null are not keywords but they are reserved words </li></ul><ul><ul><li>You cannot use them as names in your programs either </li></ul></ul>
  24. 24. Identifiers <ul><li>Names given to a variable, method, field, class, interface, etc. </li></ul><ul><li>Can start with a letter, underscore(_), or dollar sign($) </li></ul><ul><li>Can contain letters, $, _, and digits </li></ul><ul><li>Case sensitive </li></ul><ul><li>Have no maximum length </li></ul><ul><li>Examples: </li></ul><ul><ul><li>userName, $app_name, __test, value, totalRevenue, location$ </li></ul></ul>
  25. 25. Primitive Data Types <ul><li>A primitive is a simple non-object data type that represents a single value </li></ul><ul><li>Java’s primitive data types are: </li></ul><ul><ul><li>boolean </li></ul></ul><ul><ul><li>char </li></ul></ul><ul><ul><li>byte , short , int , long </li></ul></ul><ul><ul><li>float , double </li></ul></ul>
  26. 26. Primitive Data Types <ul><li>Variables of type boolean may take only the values true or false </li></ul><ul><li>Their representation size might vary </li></ul>Type Effective Size (bits) byte 8 short 16 int 32 long 64 float 32 double 64 char 16
  27. 27. Boolean Type <ul><li>The boolean data type has two literals, true and false </li></ul><ul><li>For example, the statement: </li></ul><ul><ul><li>boolean truth = true; </li></ul></ul><ul><li>declares the variable truth as boolean type and assigns it a value of true </li></ul>
  28. 28. Textual Types: char <ul><li>Represents a 16-bit Unicode character </li></ul><ul><li>Must have its literal enclosed in single quotes(’ ’) </li></ul><ul><li>Uses the following notations: </li></ul><ul><ul><li>'a' – The letter a </li></ul></ul><ul><ul><li>' ' – A tab </li></ul></ul><ul><ul><li>' ' – A new line character </li></ul></ul><ul><ul><li>'u????' – A specific Unicode character, ????, is replaced with exactly four hexadecimal digits, e.g. 'u1A4F' </li></ul></ul>
  29. 29. Integral Types: byte , short , int , and long <ul><li>Uses three forms – decimal, octal, or hexadecimal, e. g. </li></ul><ul><ul><li>2 – The decimal value is two </li></ul></ul><ul><ul><li>077 – The leading zero indicates an octal value </li></ul></ul><ul><ul><li>0xBAAC – The leading 0x indicates a hexadecimal value </li></ul></ul><ul><li>The default integer values are int </li></ul><ul><li>Defines long by using the letter L or l : </li></ul>long value = 1234L;
  30. 30. Ranges of the Integral Primitive Types Type Size Minimum Maximum byte 8 bits -2 7 2 7 – 1 short 16 bits -2 15 2 15 – 1 int 32 bits -2 31 2 31 – 1 long 64 bits -2 63 2 63 – 1
  31. 31. Floating Point Types: float and double <ul><li>Default is double </li></ul><ul><li>Floating point literal includes either a decimal point or one of the following: </li></ul><ul><ul><li>E or e (add exponential value) </li></ul></ul><ul><ul><li>F or f (float) </li></ul></ul><ul><ul><li>D or d (double) </li></ul></ul><ul><li>Examples: </li></ul><ul><ul><li>3.14 – A simple floating-point value (a double) </li></ul></ul><ul><ul><li>6.02E23 – A large floating-point value </li></ul></ul><ul><ul><li>2.718F – A simple float size value </li></ul></ul><ul><ul><li>123.4E+306D – A large double value with redundant D </li></ul></ul>
  32. 32. Ranges of the Floating-Point Primitive Types Type Size Minimum Maximum float 32 bits +/- 1.40 -45 +/- 3.40 +38 double 64 bits +/- 4.94 -324 +/- 1.79 +308 char 16 bits 0 2 16 - 1
  33. 33. Non-numeric Floating-Point Values <ul><li>Float.NaN </li></ul><ul><li>Float.NEGATIVE_INFINITY </li></ul><ul><li>Float.POSITIVE_INFINITY </li></ul><ul><li>Double.NaN </li></ul><ul><li>Double.NEGATIVE_INFINITY </li></ul><ul><li>Double.POSITIVE_INFINITY </li></ul>
  34. 34. Textual Types: String <ul><li>Is not a primitive data type </li></ul><ul><ul><li>It is a class </li></ul></ul><ul><li>Has its literal enclosed in double quotes (&quot; &quot;) </li></ul><ul><li>Example: </li></ul><ul><li>Can be used as follows: </li></ul>String greeting = &quot;Good Morning !! &quot;; String errorMsg = &quot;Record Not Found!&quot;; &quot;The quick brown fox jumps over the lazy dog.&quot;
  35. 35. Values and Objects <ul><li>Primitive Data Types </li></ul><ul><ul><li>Are value types </li></ul></ul><ul><ul><li>Contain directly their values </li></ul></ul><ul><ul><li>Examples: int , float , char , boolean </li></ul></ul><ul><li>Objects </li></ul><ul><ul><li>Are reference types </li></ul></ul><ul><ul><li>Contain a pointer (memory address) of their values </li></ul></ul><ul><ul><li>Examples: String , Object , Date </li></ul></ul>
  36. 36. Values vs. Objects <ul><li>Consider the following code fragment: </li></ul><ul><li>Two variables refer to a single object: </li></ul>int x = 7; int y = x; String s = &quot;Hello&quot;; String t = s; 7 x 7 y 0x01234567 s 0x01234567 t &quot;Hello&quot; 0x01234567 Heap (dynamic memory)
  37. 37. Enumerations (enums) <ul><li>Enumerations are special types that </li></ul><ul><ul><li>Get values from a given set of constants </li></ul></ul><ul><ul><li>Are strongly typed </li></ul></ul><ul><ul><li>Compiled to classes that inherit java.lang.Enum </li></ul></ul>public enum Color { WHITE, RED, GREEN, BLUE, BLACK } ... Color c = Color.RED;
  38. 38. Enumerations (enums) <ul><li>Allow using if and switch : </li></ul>switch (color) { case WHITE: System.out.println(&quot;бяло&quot;); break; case RED: System.out.println(&quot;червено&quot;); break; ... } if (color == Color.RED) { ... }
  39. 39. Variables, Declarations, Assignments, Operators
  40. 40. Variables, Declarations, and Assignments <ul><li>Variables are names places in the memory that contain some value </li></ul><ul><ul><li>Variables have a type (int, float, String, ...) </li></ul></ul><ul><ul><li>Variables should be declared before use </li></ul></ul><ul><ul><li>Variables can be assigned </li></ul></ul><ul><li>Examples: </li></ul>int i; // declare variable int value = 5; // declare and assign variable i = 25; // assign a value to a variable that is already declared
  41. 41. Variables, Declarations, and Assignments – Examples public class Assignments { public static void main(String args []) { int x, y; // declare int variables float z = 3.414f; // declare and assign float double w = 3.1415; // declare and assign double boolean b = true; // declare and assign boolean char ch; // declare character variable String str; // declare String variable String s = &quot;bye&quot;; // declare and assign String ch = 'A'; // assign a value to char variable str = &quot;Hi out there!&quot;; // assign value to String x = 6; // assign value to int variable y = 1000; // assign values to int variable ... } }
  42. 42. Variables and Scope <ul><li>Local variables are: </li></ul><ul><ul><li>Variables that are defined inside a method and are called local , automatic , temporary, or stack variables </li></ul></ul><ul><ul><li>Created when the method is executed and destroyed when the method is exited </li></ul></ul><ul><ul><li>Variables that must be initialized before they are used or compile-time errors will occur </li></ul></ul>
  43. 43. Operators Category Operators Unary ++ -- + - ! ~ (type) Arithmetic * / % + - Shift << >> >>> Comparison < <= > >= instanceof == != Bitwise & ^ | Short-circuit && || Conditional ? : Assignment = op=
  44. 44. The Ordinal Comparisons Operators: <, <=, >, and >= <ul><li>The ordinal comparison operators are: </li></ul><ul><ul><li>Less than: < </li></ul></ul><ul><ul><li>Less than or equal to: <= </li></ul></ul><ul><ul><li>Greater than: > </li></ul></ul><ul><ul><li>Greater than or equal to: >= </li></ul></ul>
  45. 45. The Ordinal Comparisons Operators – Example <ul><li>int p = 9; </li></ul><ul><li>int q = 65; </li></ul><ul><li>int r = -12; </li></ul><ul><li>float f = 9.0F; </li></ul><ul><li>char c = ‘A’; </li></ul><ul><li>p < q  true </li></ul><ul><li>f < q  true </li></ul><ul><li>f <= c  true </li></ul><ul><li>c > r  true </li></ul><ul><li>c >= q  true </li></ul>
  46. 46. Short-Circuit Logical Operators <ul><li>The operators are && ( AND ) and || ( OR ) </li></ul><ul><li>These operators can be used as follows: </li></ul>MyDate d = null; if ((d != null) && ( > 31)) { // Do something } boolean goodDay = (d == null) || ((d != null) && ( >= 12));
  47. 47. String Concatenation with + <ul><li>The + operator: </li></ul><ul><ul><li>Performs String concatenation </li></ul></ul><ul><ul><li>Produces a new String as a result: </li></ul></ul><ul><li>First argument must be a String object </li></ul><ul><ul><li>Non-strings are converted to String objects automatically </li></ul></ul>String salutation = &quot;Dr. &quot;; String name = &quot;Pete &quot; + &quot;Seymour&quot;; System.out.println(salutation + name + 5);
  48. 48. The Unary Operators <ul><li>Unary operators take only a single operand and work just on that </li></ul><ul><li>Java provides seven unary operators: </li></ul><ul><ul><li>The increment and decrement operators: ++ and -- </li></ul></ul><ul><ul><li>The unary plus and minus operators: + and - </li></ul></ul><ul><ul><li>The bitwise inversion operator: ~ </li></ul></ul><ul><ul><li>The boolean complement operator: ! </li></ul></ul><ul><ul><li>The cast operator: () </li></ul></ul>
  49. 49. The Cast Operator: (type) <ul><li>Implicit type conversions are possible when no information can be lost </li></ul><ul><ul><li>E.g. converting int  long </li></ul></ul><ul><li>Casting is used for explicit conversion of the type of an expression </li></ul><ul><li>Casts can be applied to change the type of primitive values </li></ul><ul><ul><li>For example, forcing a double value into an int variable like this: </li></ul></ul>int circum = (int)(Math.PI * diameter);
  50. 50. The Multiplication and Division Operators: * and / <ul><li>The * and / operators perform multiplication and division on all primitive numeric types and char </li></ul><ul><li>Integer division will generate an ArithmeticException when attempting to divide by zero </li></ul>int a = 5; int value = a * 10;
  51. 51. The Bitwise Operators <ul><li>The bitwise operators: &, ^, and | provide bitwise AND, eXclusive-OR (XOR), and OR operations, respectively </li></ul><ul><li>They are applicable to integral types </li></ul>int first = 100; int second = 200; int xor = first ^ second; int and = first & second;
  52. 52. Operator Evaluation Order <ul><li>In Java, the order of evaluation of operands in an expression is fixed – left to right </li></ul><ul><li>Consider this code fragment: </li></ul><ul><li>In this case, it might be unclear which element of the array is modified: </li></ul><ul><ul><li>Which value of b is used to select the array element, 0 or 1 </li></ul></ul>int[] a = {4, 4}; int b = 1; a[b] = b = 0;
  53. 53. Expressions and Statements
  54. 54. Expressions <ul><li>Expression is a sequence of operators, variables and literals that is evaluated to some value </li></ul>int r = (150-20) / 2 + 5; // Expression for calculation of // the surface of the circle double surface = Math.PI * r * r; // Expression for calculation of // the perimeter of the circle double perimeter = 2 * Math.PI * r;
  55. 55. Statements <ul><li>Statements are the main programming constructs </li></ul><ul><li>Types of statements </li></ul><ul><ul><li>Simple statements </li></ul></ul><ul><ul><ul><li>The smallest programming instructions </li></ul></ul></ul><ul><ul><li>Block statements – { ... } </li></ul></ul><ul><ul><li>Conditional statements ( if , if-else , switch ) </li></ul></ul><ul><ul><li>Loop statements ( for , while , do/while ) </li></ul></ul>
  56. 56. Statements and Blocks <ul><li>A statement is a single line of code terminated by a semicolon(;) </li></ul><ul><li>A block is a collection of statements bounded by opening and closing braces: </li></ul><ul><li>You can nest block statements </li></ul>salary = days * daySalary; { x = x + 1; y = y + 1; }
  57. 57. Conditional Statements <ul><li>The if , if-else statements: </li></ul>if (boolean condition) { statement or block; } if (boolean condition) { statement or block; } else { statement or block; }
  58. 58. If Statement – Example public static void main(String[] args) { int radius = 5; double surface = Math.PI * radius * radius; if (surface > 100) { System.out.println(&quot;The circle is too big!&quot;); } else if (surface > 50) { System.out.println( &quot;The circle has acceptable size!&quot;); } else { System.out.println( &quot;The circle is too small!&quot;); } }
  59. 59. Conditional Statements <ul><li>The switch statement </li></ul>switch (expression) { case constant1: statements; break; case constant2: statements; break; default: statements; break; }
  60. 60. The switch Statement – Example int dayOfWeek = 3; switch (dayOfWeek) { case 1: System.out.println(&quot;Monday&quot;); break; case 2: System.out.println(&quot;Tuesday&quot;); break; ... default: System.out.println(&quot;Invalid day!&quot;); break; }
  61. 61. Looping Statements <ul><li>The for statement: </li></ul><ul><li>Example: </li></ul>for (init_expr; boolean testexpr; alter_expr) { statement or block; } for (int i = 0; i < 10; i++) { System.out.println(&quot;i=&quot; + i); } System.out.println(&quot; Finished !&quot;)
  62. 62. Looping Statements <ul><li>The enhanced for statement: </li></ul><ul><li>Example: </li></ul>for ( Type variable : some collection ) { statement or block; } public static void main(String[] args) { String[] towns = new String[] { &quot;Sofia&quot;, &quot;Plovdiv&quot;, &quot;Varna&quot; }; for (String town : towns) { System.out.println(town); } }
  63. 63. Looping Statements <ul><li>The while loop: </li></ul><ul><li>Examples: </li></ul>while (boolean condition) { statement or block; } int i=100; while (i>0) { System.out.println(&quot;i=&quot; + i); i--; } while (true) { // This is an infinite loop }
  64. 64. Looping Statements <ul><li>The do/while loop: </li></ul><ul><li>Example: </li></ul>do { statement or block; } while (boolean condition); public static void main(String[] args) { int counter=100; do { System.out.println(&quot;counter=&quot; + counter); counter = counter - 5; } while (counter>=0); }
  65. 65. Special Loop Flow Control <ul><li>Some special operators valid in loops: </li></ul><ul><ul><li>break [label]; </li></ul></ul><ul><ul><li>continue [label]; </li></ul></ul><ul><ul><li>label: statement; // Where statement should be a loop </li></ul></ul><ul><li>Example (breaking a loop): </li></ul>for (int counter=100; counter>=0; counter-=5) { System.out.println(&quot;counter=&quot; + counter); if (counter == 50) break; }
  66. 66. Special Loop Flow Control – Examples <ul><li>Example (continuing a loop): </li></ul>for (int counter=100; counter>=0; counter-=5) { if (counter == 50) { continue ; } System.out.println(&quot;counter=&quot; + counter); }
  67. 67. Special Loop Flow Control – Examples <ul><li>Example (breaking a loop with a label): </li></ul>outerLoop: for (int i=0; i<50; i++) { for (int counter=100; counter>=0; counter-=5) { System.out.println(&quot;counter=&quot; + counter); if ((i==2) && (counter == 50)) { break outerLoop; } } }
  68. 68. Comments <ul><li>Three permissible styles of comment in a Java technology program are: </li></ul>// comment on one line /* comment on one or more lines */ /** documenting comment */
  69. 69. Console Input and Output
  70. 70. Console Input/Output <ul><li>The input/output from the console is done through 3 standard streams </li></ul><ul><ul><li> – the standard input </li></ul></ul><ul><ul><li>System.out – the standard output </li></ul></ul><ul><ul><li>System.err – the standard error output </li></ul></ul><ul><li>To facilitate some operations additional classes should be involved </li></ul><ul><ul><li>Scanner </li></ul></ul><ul><ul><li>BufferedReader , InputStreamReader </li></ul></ul>
  71. 71. Printing to the Console <ul><li>System.out.print(...) </li></ul><ul><ul><li>Can take as input different types </li></ul></ul><ul><ul><ul><li>String , int , float , Object , ... </li></ul></ul></ul><ul><ul><li>Non-string types are converted to String </li></ul></ul><ul><li>System.out.println(...) </li></ul><ul><ul><li>Like print(...) but moves to the next line </li></ul></ul>System.out.print(3.14159); System.out.println(&quot;Welcome to Java&quot;); int i=5; System.out.println(&quot;i=&quot; + i);
  72. 72. Reading from the Console <ul><li>First construct a Scanner that is attached to the “standard input stream” </li></ul><ul><li>Then use various methods of the Scanner class to read input </li></ul><ul><ul><li>nextLine()  String </li></ul></ul><ul><ul><ul><li>Reads a line of input </li></ul></ul></ul><ul><ul><li>next()  String </li></ul></ul><ul><ul><ul><li>Reads a single word delimited by whitespace </li></ul></ul></ul>Scanner in = new Scanner(;
  73. 73. Reading from the Console <ul><li>Scanner – more methods </li></ul><ul><ul><li>nextInt()  int </li></ul></ul><ul><ul><ul><li>Reads an int value. Throws InputMismatchException on error </li></ul></ul></ul><ul><ul><li>nextLong()  long </li></ul></ul><ul><ul><li>nextFloat()  float </li></ul></ul><ul><ul><ul><li>Reads a float value. Throws InputMismatchException on error </li></ul></ul></ul><ul><ul><li>nextDouble()  double </li></ul></ul>
  74. 74. Scanner – Example import java.util.Scanner; public class ScannerDemo { public static void main(String[] args) { Scanner console = new Scanner(; // Get the first input System.out.print(&quot;What is your name? &quot;); String name = console.nextLine(); // Get the second input System.out.print(&quot;How old are you? &quot;); int age = console.nextInt(); // Display output on the console System.out.println(&quot;Hello, &quot; + name + &quot;. &quot; + &quot;Next year, you'll be &quot; + (age + 1)); } }
  75. 75. Formatting Output <ul><li>System.out.printf(<format>, <values>) </li></ul><ul><ul><li>Like the printf function in C language </li></ul></ul><ul><li>Some formatting patterns </li></ul><ul><ul><li>%s – Display as string %f – Display as float </li></ul></ul><ul><ul><li>%d – Display as number %t – Display as date </li></ul></ul><ul><li>* For more details see java.util.Formatter </li></ul>String name = &quot;Nakov&quot;; int age = 25; System.out.printf( &quot;My name is %s. I am %d years old.&quot;, name, age);
  76. 76. Arrays and Array Manipulation
  77. 77. Creating Arrays <ul><li>To create and use an array, follow three steps: </li></ul><ul><li>1. Declaration </li></ul><ul><li>2. Construction </li></ul><ul><li>3. Initialization </li></ul><ul><li>4. Access to Elements </li></ul>
  78. 78. Array Declaration <ul><li>Declaration tells the compiler the array’s name and what type its elements will be </li></ul><ul><li>For example: </li></ul><ul><li>The square brackets can come before or after the array variable name: </li></ul>int[] ints; Dimensions[] dims; float[][] twoDimensions; int ints[];
  79. 79. Array Construction <ul><li>The declaration does not specify the size of an array </li></ul><ul><ul><li>Size is specified at runtime, when the array is allocated via the new keyword </li></ul></ul><ul><ul><li>For example: </li></ul></ul><ul><li>Declaration and construction may be performed in a single line: </li></ul>int[] ints; // Declaration ints = new int[25]; // Construction int[] ints = new int[25];
  80. 80. Array Initialization <ul><li>When an array is constructed, its elements are automatically initialized to their default values </li></ul><ul><ul><li>These defaults are the same as for object member variables </li></ul></ul><ul><ul><li>Numerical elements are initialized to 0 </li></ul></ul><ul><ul><li>Non-numeric elements are initialized to 0-like values, as shown in the next slide </li></ul></ul>
  81. 81. Elements Initialization Element Type Initial Value byte 0 int 0 float 0.0f char ‘ u0000’ object reference null short 0 long 0L double 0.0d boolean false
  82. 82. Array Elements Initialization <ul><li>Initial values for the elements can be specified at the time of declaration and initialization: </li></ul><ul><li>The array size is inferred from the number of elements within the curly braces </li></ul>float[] diameters = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
  83. 83. Access to Elements <ul><li>Accessing array elements: </li></ul><ul><li>Elements access is range checked </li></ul><ul><li>Arrays has field length that contains their number of elements </li></ul>int[] arr = new int[10]; arr[3] = 5; // Writing element int value = arr[3]; // Reading element int[] arr = new int[10]; int value = arr[10]; // ArrayIndexOutOfBoundsException
  84. 84. Arrays – Example // Finding the smallest and largest // elements in an array int[] values = {3,2,4,5,6,12,4,5,7}; int min = values[0]; int max = values[0]; for (int i=1; i<values.length; i++) { if (values[i] < min) { min = values[i]; } else if (values[i] > max) { max = values[i]; } } System.out.printf(&quot;MIN=%d &quot;, min); System.out.printf(&quot;MAX=%d &quot;, max);
  85. 85. M ulti-dimension al A rrays <ul><li>Multidimensional arrays in Java are actually arrays of arrays </li></ul><ul><li>Defining matrix: </li></ul><ul><li>Accessing matrix elements: </li></ul><ul><li>Getting the number of rows/columns: </li></ul>int[][] matrix = new int[3][4]; matrix[1][3] = 42; int rows = matrix.length; int colsInFirstRow = matrix[0].length;
  86. 86. M ulti-dimension al A rrays <ul><li>Consider this declaration plus initialization: </li></ul><ul><li>It’s natural to assume that the myInts contains 12 ints and to imagine them as organized into rows and columns, as shown : </li></ul>WRONG ! int[][] myInts = new int[3][4];
  87. 87. M ulti-dimension al A rrays <ul><li>The right way to think about multi-dimension arrays </li></ul>CORRECT!
  88. 88. M ulti-dimension al A rrays <ul><li>The subordinate arrays in a multi-dimension array don’t have to all be the same length </li></ul><ul><li>Such an array may be created like this: </li></ul>int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} };
  89. 89. M ulti-dimension al A rrays – Example // Finding the sum of all positive // cells from the matrix int[][] matrix = {{2,4,-3}, {8,-1,6}}; int sum = 0; for (int row=0; row<matrix.length; row++) { for (int col=0; col<matrix[row].length; col++) { if (matrix[row][col] > 0) { sum += matrix[row][col]; } } } System.out.println(&quot;Sum = &quot; + sum);
  90. 90. Questions ? Introduction to Java Programming
  91. 91. Exercises <ul><li>Write an expression that checks if given integer is odd or even. </li></ul><ul><li>Write a boolean expression that for given integer checks if it can be divided (without remainder) by 7 and 5. </li></ul><ul><li>Write an expression that checks if a given integer has 7 for its third digit (right-to-left). </li></ul><ul><li>Write a boolean expression for finding if the bit 3 of a given integer is 1 or 0. </li></ul><ul><li>Write a program that for a given width and height of a rectangle, outputs the values of the its surface and perimeter. </li></ul>
  92. 92. Exercises <ul><li>Write a program that asks the user for a four-digit number abcd and: </li></ul><ul><ul><li>Calculates the sum of its digits </li></ul></ul><ul><ul><li>Prints its digits in reverse order: dcba </li></ul></ul><ul><ul><li>Puts the last digit in at the front: dabc </li></ul></ul><ul><ul><li>Changes the position of the second and third digits: acbd </li></ul></ul><ul><li>Write an expression that checks if a given number n ( n ≤ 100) is a prime number. </li></ul><ul><li>Write a boolean expression that returns true if the bit at position p in a given integer v is 1. Example: if v=5 and p=1, return false. </li></ul>
  93. 93. Exercises <ul><li>Write a program that reads 3 integer numbers from the console and prints their sum. </li></ul><ul><li>Write a program that reads the radius r of a circle and prints its perimeter and area. </li></ul><ul><li>A company has name, address, phone number, fax number, Web site and manager. The manager has first name, last name and a phone number. Write a program that reads the information about a company and its manager and prints it on the console. </li></ul>
  94. 94. Exercises <ul><li>Write a program that reads from the console two integer numbers and prints how many numbers exist between them, such that the reminder of the division by 5 is 0. </li></ul><ul><li>Write a program that gets two numbers from the console and prints the greater of them. Don’t use if statements. </li></ul><ul><li>Write a program that reads 5 numbers and prints the greatest of them. </li></ul><ul><li>Write a program that reads 5 numbers and prints their sum. </li></ul>
  95. 95. Exercises <ul><li>Write an if statement that examines two integer variables and exchanges their values if the first one is greater than the second one. </li></ul><ul><li>Write a program that shows the sign (+ or -) of the product of three real numbers without calculating it. Use sequence of if statements. </li></ul><ul><li>Write a program that finds the biggest of three integers using nested if statements. </li></ul><ul><li>Write a program that sorts 3 real values in descending order using nested if statements. </li></ul>
  96. 96. Exercises <ul><li>Write program that for a given digit (0-9) entered as input prints the name of that digit (in Bulgarian). Use a switch statement. </li></ul>
  • lesykaleanca

    Jan. 22, 2020
  • Ulfaeni

    Dec. 6, 2018
  • zarefa_nabil

    Mar. 31, 2018
  • Seid1983

    Apr. 25, 2017
  • TharakaDevinda

    Apr. 28, 2016
  • JabezVillanueva

    Jan. 28, 2016
  • FaizanHafeez3

    Oct. 25, 2015
  • christianjosephopiana

    Feb. 10, 2015
  • vinbalo32

    Apr. 4, 2014

Introduction to programming with Java - types and variables, conditional statements, loops, arrays


Total views


On Slideshare


From embeds


Number of embeds