1 / 90

Preparing a Java Program

Preparing a Java Program We are going to use JDK environment of Sun Microsystems. JDK environment is simple to use and free. You can JDK environment for your own computer from: the sun website http://java.sun.com/j2se/1.3 Editing : Create a file containing a Java program.

Mia_John
Download Presentation

Preparing a Java Program

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Preparing a Java Program • We are going to use JDK environment of Sun Microsystems. • JDK environment is simple to use and free. • You can JDK environment for your own computer from: the sun website http://java.sun.com/j2se/1.3 • Editing: • Create a file containing a Java program. • You may use any text editor. • This file will be .java extension (Ex: Test1.java ) • Compiling: • Use Java compiler to compile the Java program. ( javac Test1.java ) • Java compiler will create a file with .class extension. This file will contain the Java byte-codes of your Java program ( Test1.class ). You can run this file in different platforms. • The other compilers produce executable files. COP 3330 Object Oriented Programming

  2. Preparing a Java Program (cont.) • Executing: • Execute the byte-codes of your Java program by a Java interpreter. • We will see that there are two types of Java programs: application, applet • If our program is an application, we will execute it as follows: java Test1 (will interpret Test1.class file ) • If our program is an applet: * First we will create a .html file containing a link to our .class file. * Then we will run our applet using appletviewer: appletviewer Test1.html * We may run our applets under web-browsers too. COP 3330 Object Oriented Programming

  3. Simple IO System.out.print(“A simple sentence"); The other version of this method is the println method. The only difference between print and println is that println advances the cursor to the next line. Thus, the following three statements: System.out.print("Roses are red,"); System.out.println(" violets are blue,"); System.out.println("This poem is as good as new."); would produce the following output: Roses are red, violets are blue, This poem is as good as new. COP 3330 Object Oriented Programming

  4. Simple Operator Overloading • 3+2 (Integers) • 3.2+2.3 (Reals) • How does Java handle these expressions? • “Dog”+”House”=??? • 4+”Computers” = ??? COP 3330 Object Oriented Programming

  5. Simple Output System.out.println("Hello " + "World!"); Output: Hello World System.out.println("Answer = " + 7); Output: Answer = 7 System.out.println(3+4); Output: 7 System.out.println(3+4+"= 7"); Output: 7=7 COP 3330 Object Oriented Programming

  6. A Simple Console Application Program // Author: Ilyas Cicekli Date: October 9, 2001 // // A simple application program which prints “Hello, World” public class Test1 { public static void main(String args[]){ // print “Hello, World” System.out.println("Hello, World”); } // end of main } // end of class COP 3330 Object Oriented Programming

  7. A Simple Console Application Program (cont.) • Every Java program (every application program) defines a class. • We use class keyword to declare a class. • The name of a class is an identifier. Uppercase and lowercase letters are different. • The name of the class must be same as the the file holding that class (Test1.java) • Our class contains only one method. • Every console application program should contain main method. • It may contain other methods too. • The method main should be declared using public and static keywords. • Our main method contains only one executable statement • This is a method invocation statement (print statement) • Comments • // single line comments • /* ... */ multi line comments • We can use as much as white spaces between words to make easier to read programs. COP 3330 Object Oriented Programming

  8. A Simple Console Application Program (cont.) • We put this application program into the file Test1.java using a text editor. • To compile: javac Test1.java • creates Test1.class file (if there is no syntax errors) • To run: java Test1 • java interpreter will interpret the byte-codes in Test1.class file. • As a result, we will see Hello, World on the screen COP 3330 Object Oriented Programming

  9. Simple Java Program (cont.) • What do we have in our simple Java program? • Identifiers – Test1,args,... • Reserved Words – public, class, static, ... • Literals – “Hello, World” • Operators -- . • Delimeters -- { } ( ) [ ] ; • Comments -- // end of class • When these parts are combined according to the certain rules (the syntax of Java), a syntactically correct Java program is created. COP 3330 Object Oriented Programming

  10. object method Information provided to the method (parameters) Introduction to Objects • Initially, we can think of an object as a collection of services that we can tell it to perform for us • The services are defined by methods in a class that defines the object System.out.println (”Make the most of each day.");

  11. The println and print Methods • The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line

  12. Abstraction • An abstraction hides (or ignores) the right details at the right time • An object is abstract in that we don't really have to think about its internal details in order to use it • We don't have to know how the println method works in order to invoke it • A human being can only manage seven (plus or minus 2) pieces of information at one time • But if we group information into chunks (such as objects) we can manage many complicated pieces at once • Therefore, we can write complex software by organizing it carefully into classes and objects

  13. Identifiers • We make up words for class names, method names, and variables. • These words are called identifiers. • For example, • Test1, main, System, out, println are identifiers in our simple program. • We made up Test1 and main(!); and others are defined in Java API (Application Programming Interface). • An identifier can be composed of any combination of letters, digits, the under score character, and the dollar sign; but it cannot start with a digit. • We can use both upper case letters and lower case letters in identifiers. But Java is case sensitive. Identifiers Val, val and VAL are all different variables. • Some Legal Identifiers: x val count_flag Test1 $amount val1 stockItem • Some Illegal Identifiers: 1val x# x-1 x+ • Although we can choose any legal identifier to be used, but it is nice to follow certain style guidelines when make up an identifier. • Choose meaningful names (not too long, not too short, descriptive words) • First character of a class name should be an uppercase letter. • First character of a method name and a variable should be a lower case letter. COP 3330 Object Oriented Programming

  14. Three types of identifiers: • words that we make up ourselves. • words that are reserved for special purposes in the language • words that are not in the language, but were used by • other programmers to make the library. COP 3330 Object Oriented Programming

  15. Identifiers- different words used in a program • The rule: an identifier may be composed of any number of • letters, • digits • $ (dollar sign) • _ (underscore). • but the first character can not be a digit. • A letter: any English or foreign language alphabetic • symbol (both uppercase and lower case) Java is case sensitive! COP 3330 Object Oriented Programming

  16. data type variable name Variables • A variable is a name for a location in memory • A variable must be declared, specifying the variable's name and the type of information that will be held in it int total; int count, temp, result; Multiple variables can be created in one declaration

  17. Variables • A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; • When a variable is referenced in a program, its current value is used COP 3330 Object Oriented Programming

  18. Assignment • An assignment statement changes the value of a variable • The assignment operator is the = sign total = 55; • The expression on the right is evaluated and the result is stored in the variable on the left • The value that was in total is overwritten • You can only assign a value to a variable that is consistent with the variable's declared type

  19. Variables • A variable is an identifier that represents a memory location which holds a particular type of data. • The type of a variable indicates the size of the memory location which will be reserved for that variable, and how its content will be interpreted. • Variables must be declared before they can be referenced. • The syntax of a variable declaration: data-type variable-name ; • Examples: • int x; (32 bits and it will be interpreted as an integer number) • double y; (64 bits and it will be interpreted as a floating point number) • short z; (16 bits and it will be interpreted as an integer number) • String s; (big enough to hold a reference) • Contents of the allocated locations are not known (or we shouldn’t assume it). COP 3330 Object Oriented Programming

  20. Variable Declarations • Multiple variables can be declared with same declaration statement. data-type variable-name1,...,variable-namen ; int a, b, c; double x, y; • Variables can be initialized in declarations. int total=0, count=1; double price=15.25; • When a new value is placed in a memory location, this new value replaces the old value in that memory location. int x=1,y=2; x = 3; y = x; COP 3330 Object Oriented Programming

  21. Constants • A constant is an identifier that is similar to a variable except that it holds one value for its entire existence • The compiler will issue an error if you try to change a constant • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; • Constants: • give names to otherwise unclear literal values • facilitate changes to the code • prevent inadvertent errors COP 3330 Object Oriented Programming

  22. Constants • A constant is similar to a variable except that they keep the same value through their existence. • Constants cannot be used in the left side of an assignment statement. • They are specified using the reserved word final in declarations. • Examples: final double PI = 3.14159; final int NUMOFSTUDENTS = 58; • As a style, we choose upper case letter for identifiers representing constants. • Constants are better than literals because: • they make code more readable by giving a name to a value. • they facilitate easy updates in the programs because the value is only specified in one place. COP 3330 Object Oriented Programming

  23. Assignment Statement variable=expression; • The value of the expression is evaluated, and its result is stored in the memory location indicated by that variable overwriting the value stored in that location. • An expression is a sequence of operands (such as variables, literals, constants, method calls), and operators. It can be a single operand or a more complex expression. • The variable must be assignment compatible with the expression. COP 3330 Object Oriented Programming

  24. Java data types • Primitive data types • integers (byte, short, int, long) • floating point numbers (float, double) • boolean (true, false) • char (any symbol encoded by a 16-bit unicode) • Objects- everything else • An object is defined by a class. A class is the data type of the object. • You can define your own objects or • use predefined classes from library. COP 3330 Object Oriented Programming

  25. Data Types • Each value in memory is associated with a specific data type. • Data type of a value determines: • size of the value (how many bits) and how these bits are interpreted. • what kind of operations we can perform on that data. • A data type is defined by a set of values and the operators you can perform on them. • Data Types in Java: • Primitive Data Types • Object Data Types COP 3330 Object Oriented Programming

  26. Primitive Data • There are exactly eight primitive data types in Java • Four of them represent integers: • byte, short, int, long • Two of them represent floating point numbers: • float, double • One of them represents characters: • char • And one of them represents boolean values: • boolean COP 3330 Object Oriented Programming

  27. Primitive Data Types • There are eight primitive data types in Java programming language. byte short int long float double char -- characters boolean -- boolean values }integers }floating point numbers (real numbers0 COP 3330 Object Oriented Programming

  28. Typing and Naming What kind of things a program can manipulate? Some of them are simple, like numbers. Others may be complex. Those are called objects. What is a type? A type specifies what a thing can do (or what you can do with a thing). Names are ways to refer to things that already exist. Every name has a type, which tells you what you can expect from the thing that the name refers to. COP 3330 Object Oriented Programming

  29. Java numerical primitive types There are four separate integer primitive data types They differ by the amount of the memory used to store them. Internally, integers are represented using two’s complement representation (discussed later). COP 3330 Object Oriented Programming

  30. boolean true or false char ‘x’, ‘6’, ‘\’, ‘\’’, ‘\u006A’ 16 bit unicode Example: int a=1, b=0; boolean bool=a<b; // bool is false char letter=‘a’; COP 3330 Object Oriented Programming

  31. Literal Assigned type 6 int (default type) 6L long 6l long 1,000,000,000 int 2.5 (or 2.5e-2) double (default type) 2.5F float 2.5f float ‘x’ char ‘\n’ char (new line) ‘\u0039’ char represented by unicode 0039 true boolean “\tHello World!\n” String (not a primitive data type!) COP 3330 Object Oriented Programming

  32. Literals and identifiers • A literal is a thing itself. You can type it directly • in appropriate place of the program. • An identifier is a name that uniquely identifiers a thing. • Java is a strongly typed language. • Each thing (variable ) must be declared. • Appropriate storage space is allocated. • If no value is specified, the value is initialized to 0, 0.0, • ‘\u0000’ (null character) and falseby default. int myNumber; double realNumber; char firstLetterOfMyName; boolean isEmpty; COP 3330 Object Oriented Programming

  33. Assignment actually assigns value to a name myNumber=4; firstLetterOfMyName=‘N’; isEmpty=true; Combination of declaration and assignment is called definition boolean isHappy=true; double degree=0.0; String s = “This is a string.”; float x, y=4.1, z=2.2; COP 3330 Object Oriented Programming

  34. int y=4, z=2; x=y/z; Syntax error COP 3330 Object Oriented Programming

  35. Binary Numbers • Before we talk about primitive data types in Java programming language, let us review the binary numbers. • a sequence of 0s and 1s. • two bits: 00 01 10 11 (four different values) • three bits: 000 001 010 011 100 101 110 111 (eight different values) • 8 bits (1 byte): 00000000 ... 11111111 (256 different values) • n bits: 2n different values COP 3330 Object Oriented Programming

  36. Internal Data Representation of Integers • Two’s complement format is used to represent integer numbers. • Two’s complement format representation makes internal arithmetic processing easier. • In Two’s complement format: • positive numbers are represented as a straight forward binary number. • a negative value is represented by inverting all the bits in the corresponding positive number, then adding 1. (sign bit 0 for positive numbers, 1 for negative numbers) Ex: (byte) 00000110 (6)  11111001 + 1 = 11111010 (-6) invert all the digits – one’s complement then add one COP 3330 Object Oriented Programming

  37. Internal Data Representation – More Examples 31: 00011111  11100000 + 1 = 11100001 (-31) 0: 00000000 127: 01111111  10000000 + 1 = 10000001 (-127) 1: 00000001  11111110 + 1 = 11111111 (-1) 10000000 (which number?)  -128 128:10000000  01111111 + 1 = 10000000 (-128) Addition: 00000011 + 11111111 = 00000010 (2) 3 -1 COP 3330 Object Oriented Programming

  38. Overflow - Underflow • If a value grows so large that it cannot be stored in the space, this is called as OVERFLOW. • If a value grows so small that it cannot be stored in the space, this is called as UNDERFLOW. • If an overflow or an underflow occurs, we will get incorrect results (not error messages). Overflow: Underflow: byte x = 127; byte x = -128; x = (byte) (x+1); x = (byte) (x-1);  value of x is –128  value of x is 127 01111111 + 00000001 = 1000000010000000 + 11111111 = 01111111 COP 3330 Object Oriented Programming

  39. Floating Point Numbers (Real Numbers) • There are two separate floating point primitive data types. • They differ by the amount of the memory used to store them. • Java treats any floating point literal as double. • If we want to force a literal to be float: 1.2f 1.2F • double literals: 1.2 1.2d 1.2D COP 3330 Object Oriented Programming

  40. Internal Representation of Floating Point Numbers • Java uses the standard IEEE 754 floating point format to represent real numbers. float double sign exponent mantissa value = sign * mantissa * 2exponent COP 3330 Object Oriented Programming

  41. Boolean • A boolean value represents a true or false condition. • The reserved words true and false are only valid values for a boolean type. int i, j; boolean x, y; x = true; y = (i < j); COP 3330 Object Oriented Programming

  42. Boolean • A boolean value represents a true or false condition • A boolean can also be used to represent any two states, such as a light bulb being on or off • The reserved words true and false are the only valid values for a boolean type boolean done = false;

  43. Characters • A char value stores a single character from Unicode character set. • A character set is an ordered list of characters. Each character is represented by a sequence of bits. • The Unicode character set uses 16 bits per character (65636 unique characters) and contains international character sets from different languages, numbers, symbols. • ASCII character set is a subset of the Unicode character set. It uses only 8 bits (256 characters). In fact, the first 256 characters of the Unicode character set are ASCII characters. • 32 space • 48-57 0 to 9 • 65-90 A to Z • 97-122 a to z • Character literals: • ‘a’ ‘A’ ‘1’ ‘0’ ‘+’ • Note that ‘1’ and 1 are different literals (character and integer) COP 3330 Object Oriented Programming

  44. Characters • A char variable stores a single character from the Unicode character set • A character set is an ordered list of characters, and each character corresponds to a unique number • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n'

  45. uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, \, … carriage return, tab, ... Characters • The ASCII character set is older and smaller than Unicode, but is still quite popular • The ASCII characters are a subset of the Unicode character set, including:

  46. Reserved Words • Reserved words are identifiers that have a special meaning in a programming language. • For example, • public, void, class, static are reserved words in our simple programs. • In Java, all reserved words are lower case identifiers (Of course we can use just lower case letters for our own identifiers too) • We cannot use the reserved words as our own identifiers (i.e. we cannot use them as variables, class names, and method names). COP 3330 Object Oriented Programming

  47. Java reserved words • Data declaration: boolean, float, int, char • Loop keywords:for, while, continue • Conditional keywords: if, else, switch • Exceptional keywords: try, throw, catch • Structurekeywords: class, extends, implements • Modifier and access keywords: public, private, protected • Miscellaneous: true, null, super, this COP 3330 Object Oriented Programming

  48. /* HelloWorld application program */ public class HelloWorld // Class header { // Start class body public static void main(String argv[]) //main method { System.out.println(“HelloWorld!”); } // end of main } // end HelloWorld words that we make up ourselves COP 3330 Object Oriented Programming

  49. /* HelloWorld application program */ public class HelloWorld // Class header { // Start class body public static void main(String argv[]) //main method { System.out.println(“HelloWorld!”); } // end of main } // end HelloWorld words that are reserved for special purposes in the language are called reserved words COP 3330 Object Oriented Programming

  50. words that are not in the language, but were used by other programmers to make the library /* HelloWorld application program */ public class HelloWorld // Class header { // Start class body public static void main(String argv[]) //main method { System.out.println (“HelloWorld!”); } // end of main } // end HelloWorld COP 3330 Object Oriented Programming

More Related