Your SlideShare is downloading. ×
0
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Introduction to-programming
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Introduction to-programming

7,203

Published on

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

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

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
7,203
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
473
Comments
0
Likes
2
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## The Java API is set of runtime libraries that give you a standard way to access the system resources of a host computer. When you write a Java program, you assume the class files of the Java API will be available at any Java virtual machine that may ever have the privilege of running your program (because the Java virtual machine and the class files for the Java API are the required components of any implementation of the Java Platform). When you run a Java program, the virtual machine loads the Java API class files that are referred to by your program's class files. The combination of all loaded class files (from your program and from the Java API) and any loaded dynamic libraries (containing native methods) constitute the full program executed by the Java virtual machine. The class files of the Java API are inherently specific to the host platform. To access the native resources of the host, the Java API calls native methods. The class files of the Java API invoke native methods so your Java program doesn't have to. In this manner, the Java API's class files provide a Java program with a standard, platform-independent interface to the underlying host. Creating platform- independent API is inherently difficult , given that system functionality varies greatly from one platform to another. In addition to facilitating platform independence, the Java API contributes to Java's security model. The methods of the Java API, before they perform any action that could potentially be harmful (such as writing to the local disk), check for permission. In Java releases prior to 1.2, the methods of the Java API checked permission by querying the security manager . The security manager is a special object that defines a custom security policy for the application . A security manager could, for example, forbid access to the local disk.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## As a whole, Java technology leans heavily in the direction of networks, but the Java programming language is quite general-purpose . Java is, first and foremost, an object-oriented language. One promise of object-orientation is that it promotes the re-use of code, resulting in better productivity for developers. In Java, there is no way to directly access memory by arbitrarily casting pointers to a different type or by using pointer arithmetic, as there is in C++. Java requires that you strictly obey rules of type when working with objects. Because Java enforces strict type rules at run- time, you are not able to directly manipulate memory in ways that can accidentally corrupt it. As a result, you can't ever create certain kinds of bugs in Java programs that regularly harass C++ programmers and hamper their productivity. Another way Java prevents you from inadvertently corrupting memory is through automatic garbage collection . Java has a new operator, just like C++, that you use to allocate memory on the heap for a new object. But unlike C++, Java has no corresponding delete operator, which C++ programmers use to free the memory for an object that is no longer needed by the program. In Java, you merely stop referencing an object, and at some later time, the garbage collector will reclaim the memory occupied by the object. You can be more productive in Java primarily because you don't have to chase down memory corruption bugs. But also, you can be more productive because when you no longer have to worry about explicitly freeing memory, program design becomes easier. A third way Java protects the integrity of memory at run-time is array bounds checking . In Java, arrays are full-fledged objects, and array bounds are checked each time an array is used. If you create an array of ten items in Java and try to write to the eleventh, Java will throw an exception. Java won't let you corrupt memory by writing beyond the end of an array. One final example of how Java ensures program robustness is by checking object references , each time they are used, to make sure they are not null. In C++, using a null pointer usually results in a program crash. In Java, using a null reference results in an exception being thrown. The productivity boost you can get just by using the Java language results in quicker development cycles and lower development costs . You can realize further cost savings if you take advantage of the potential platform independence of Java programs. Even if you are not concerned about a network, you may still want to deliver a program on multiple platforms. Java can make support for multiple platforms easier, and therefore, cheaper.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## The executables “javac” and “java” are platform-specific and are part of the Java Development Kit (JDK), which must be installed on the target host machine. Each of the executables take large number of arguments that customize the compilation and execution process (set custom classpath etc.)
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 To create an application, you write a class definition that includes a main() method. To execute an application, type java at the command line, followed by the name of the class containing the main() method to be executed. The main() method must be public so that the JVM can call it. It is static so that it can be executed without the necessity of constructing an instance of the application class. The return type must be void . The argument to main() is a single-dimension array of Strings, containing any arguments that the user might have entered on the command line. For example, consider the following command line: # java Mapper France Belgium With this command line, the args[] array has two elements: France in args[0], and Belgium in args[1].
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Unused keywords There are two keywords that are reserved in Java but which are not used. If you try to use one of these reserved keywords, the Java compiler will produce the following: KeywordTest.java:4: ‘goto’ not supported.                goto MyLabel; 1 error const Do not use to declare a constant; use public static final . goto Not implemented in the Java language.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 According to the Java Language Specification these are technically literal values and not keywords. A literal is much the same as a number or any other value. If we try to create an identifier with one of these literal values we will receive errors. class LiteralTest {      public static void main (String [] args) {           int true = 100; // this will cause error      } } Compiling this code gives us the following error: c:Java ProjectsLiteralTest>javac LiteralTest.java LiteralTest.java:3: Invalid expression statement.                   int true = 100; .. In other words, trying to assign a value to true is much like saying: int 200 = 100;
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 All numeric primitive types are signed. The char type is integral but unsigned. The range of a variable of type char is from 0 through 216 − 1. Java characters are in Unicode, which is a 16-bit encoding capable of representing a wide range of international characters. If the most significant 9 bits of a char are all 0, then the encoding is the same as 7-bit ASCII.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 These types conform to the IEEE 754 specification. Many mathematical operations can yield results that have no expression in numbers (infinity, for example). To describe such non-numeric situations, both double and float can take on values that are bit patterns that do not represent numbers. Rather, these patterns represent non-numeric values. The patterns are defined in the Float and Double classes and may be referenced as shown in the next slide.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 NaN stands for Not a Number The following code fragment shows the use of these constants: double d = -10.0 / 0.0; if (d == Double.NEGATIVE_INFINITY) { System.out.println("d just exploded: " + d); } In this code fragment, the test on line 2 passes, so line 3 is executed. Non-numeric values cannot be compared – the following is TRUE: ( Float.NaN != Float.NaN )
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 The Java operators are listed in precedence order, with the highest precedence at the top of the table. Each group has been given a name for reference purposes; that name is shown in the left column of the table. Arithmetic and comparison operators are each split further into two sub groupings because they have different levels of precedence. We’ll discuss these groupings later.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 These are applicable to all numeric types and to char and produce a boolean result.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Notice that arithmetic promotions are applied when these operators are used. This is entirely according to the normal rules discussed in Module 4. For example, although it would be an error to attempt to assign, say, the float value 9.0F to the char variable c , it is perfectly acceptable to compare the two. To achieve the result, Java promotes the smaller type to the larger type; hence the char value ‘A’ (represented by the Unicode value 65) is promoted to a float 65.0F. The comparison is then performed on the resulting float values. Although the ordinal comparisons operate satisfactorily on dissimilar numeric types, including char , they are not applicable to any non-numeric types. They cannot take boolean or any classtype operands.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 If the cast, which is represented by the (int) part, were not present, the compiler would reject the assignment; a double value, such as is returned by the arithmetic here, cannot be represented accurately by an int variable. Casts can also be applied to object references. This often happens when you use containers, such as the Vector object. If you put, for example, String objects into a Vector, then when you extract them, the return type of the elementAt() method is simply Object. Module 4, “Converting and Casting,” covers casting, the rules governing which casts are legal and which are not, and the nature of the runtime checks that are performed on cast operations.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 An evaluation from left to right requires that the leftmost expression, a[b], be evaluated first, so it is a reference to the element a[1]. Next, b is evaluated, which is simply a reference to the variable called b. The constant expression 0 is evaluated next, which clearly does not involve any work. Now that the operands have been evaluated, the operations take place. This is done in the order specified by precedence and associativity. For assignments, associativity is right to left, so the value 0 is first assigned to the variable called b; then the value 0 is assigned into the last element of the array a.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 A Java array is an ordered collection of primitives, object references, or other arrays. Java arrays are homogeneous: except as allowed by polymorphism, all elements of an array must be of the same type. That is, when you create an array, you specify the element type, and the resulting array can contain only elements that are instances of that class or subclasses of that class.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 The first example declares an array of a primitive type. Example 2 declares an array of object references (Dimension is a class in the java.awt package). Example 3 declares a two-dimensional array—that is, an array of arrays of floats. The square brackets can come before or after the array variable name - This is also true, and perhaps most useful, in method declarations. A method that takes an array of doubles could be declared as myMethod(double dubs[]) or as myMethod(double[] dubs); a method that returns an array of doubles may be declared as either double[] anotherMethod() or as double anotherMethod()[]. In this last case, the first form is probably more readable.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Since array size is not used until runtime, it is legal to specify size with a variable rather than a literal: int size = 1152 * 900; int [] raster; raster = new int[size];
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Arrays are actually objects, even to the extent that you can execute methods on them (mostly the methods of the Object class), although you cannot subclass the array class. So this initialization is exactly the same as for other objects, and as a consequence you will see the initialization table again in the next section.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Of course, an array can also be initialized by explicitly assigning a value to each element, starting at array index 0: long [] squares; squares = new long[6000]; for ( int i = 0; i < squares.length; i++) { squares[i] = i * i; } Keep in mind, that the next code is also legal, although it will show only 3 elements: float [] diameters = {1.1f, 2.2f, 3.3f, }; for ( int i = 0; i < diameters.length; i++) { System.out.println("Element [" + i + "] = " + diameters[i]); }
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Actually, the f igure is misleading. myInts is actually an array with three elements. Each element is a reference to an array containing 4 ints, as shown in the next slide .
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 Actually, the f igure is misleading. myInts is actually an array with three elements. Each element is a reference to an array containing 4 ints, as shown in the next slide .
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## ## (c) 2006 National Academy for Software Development - http://academy.devbg.org* * 07/16/96 When you realize that the outermost array is a single-dimension array containing references, you understand that you can replace any of the references with a reference to a different subordinate array, provided the new subordinate array is of the right type. For example, you can do the following: int [][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} }; int [] replacement = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; myInts[1] = replacement;
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 10/09/1007/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • Transcript

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

    ×