2440 160 Java Programming

Document Sample
2440  160 Java Programming Powered By Docstoc
					2440: 160 Java Programming Chapter 1 INTRODUCTION TO JAVA
WHAT IS JAVA  Java is a programming language, with elements from C, C++, and other languages, and with libraries highly tuned (convenient) for the internet environment. With Java, anyone can publish a WWW page with code in it, which can be executed by anyone else accessing that page regardless of hardware. HISTORY OF JAVA  James Gosling of Sun wanted the benefits of object-oriented programming but C++ proved difficult for him.  Gosling implemented a language of his own called “Oak”, which was a software part of larger consumer hardware project.  Java became what it is today, with the introduction of the “internet” in the project‟s plans.  Java blasted into limelight 1995 with a web browser to proof the use of Java. Negotiations with Netscape started taking place and the “Java Day”was launched. PROPERTIES OF JAVA  Java is Object-Oriented - Java uses Objects to perform specific tasks.  Java is Portable - Java enables programs to behave identical on different platforms like: Mac, Windows 95/98, Solaris (UNIX). Java was designed with internet applications in mind.  Java is “architecture-neutral” - The library code that comes out of the compiler will run on any processor and operating system.  Java does not compile in machine code - Java programs are compiled to obtain object codes (byte codes) and these codes will run on any platform.  Java can be embedded on WWW pages - When a WWW page is accessed, the java program is sent over the net to the user, and executed on the user‟s computer. eg., Applets - a program in a web page. OBJECT-ORIENTED PROGRAMMING AND JAVA  Java is object-oriented and to be able to understand the Java programming language, you must understand OOP concepts.  Object-Oriented Programming - a perspective of classes and things (objects or nouns) Most expects agree that OOP is based on 4 key principles: abstraction, encapsulation, inheritance, and polymorphism.  Abstraction - hiding details that do not contribute to essential characteristics. eg., a car will be identified differently in many instances (a garage, home records, state records).  Encapsulation - Grouping of essential characteristics (data types, data, operations bundled together). Figure 1.1 illustrates this point
class Fruit { int grams; int caloriesPerGram; int totalCalories ( )


{ return grams * caloriesPerGram; } }

Figure 1.1 A sample program demonstrating Encapsulation  Inheritance - deriving types base on previously defined types (operations on the parent type apply to the derived type. Figure 1.2 illustrates this point
class Fruit { int grams; int cals_per_gram; int total_calories ( ) { /*…*/ } } class Plum extends Fruit { void squeeze ( ) { /*…*/ } }

Figure 1.2 Sample program to demonstrate Inheritance.  Some terminologies used in Inheritance include:  class - a data type.  extend - making a new class that inherits the contents of an existing class.  Superclass - a parent or “base” class.  Subclass - a child class that inherits, or extends, a superclass. Polymorphism - using the same procedure name or operator with different types of arguments. There are 2 types of polymorphism: overloading and overriding. These would be explained later in the in the notes.


public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World”); } }

Figure 1.3 A Simple Java program  The above program represents the simplest Java program. The statement that does the actual work is System.out.println(“Hello World”);


   

      

The text “Hello World” is a literal string of characters that is meant to appear exactly as entered. Any literal string in Java programming appears between quotation marks. The string “Hello World” appears within parenthesis because the string is an argument to a method. println( ) is the method that the argument is being passed to. Arguments consist of information that a method requires for performing its task. println( ) is a method in Java programming that prints a line of output on the screen, and positions the cursor on the next line, and stands ready to accept any additional input. print( ) also prints a line of output on the screen, but it positions the cursor on the same line as the output, after printing the message. Method names are usually referenced followed by their parenthesis in order to distinguish them from variable names. E.g., println( ). Within, System.out.println(“Hello World”);, out is an object that represents the screen and several methods like println( ) are available with the out object. System - a class defining the attributes of a collection of similar System objects like out, in. Java is case-sensitive; therefore System will not be the same as SYSTEM or system. The dots (.) in the statement System.out.println(“Hello World”); are used to separate the names of the class, object, and method. Everything used within a Java program must be part of a class. public class HelloWorld defines a class named HelloWorld. A class can be defined using any name or identifier as long as it satisfies the following criteria. 1. A class name must begin with a letter of the alphabet (Unicodes etc), an underscore, or a dollar sign. 2. A class name can contain only letters, digits, underscores, or dollar signs. 3. A class name cannot be a Java programming reserved word (Figure 2.2 below lists the Java reserved words).
abstract boolean break byte byvalue case cast catch char class const continue default do double else extends final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient try var void volatile while

Figure 1.4 Java Programming Reserved Words  In Java, standards are employed in the naming of classes to improve readability. This involves using uppercase letters to begin class names, and emphasizing each word put together as a class name with an uppercase letter. E.g., Employee, UnderGradStudent, InventoryItem, Year2000. It is recommended that established naming conventions be used in order for other programmers to interpret and follow a program. Some valid, but unconventional class names include, employee, Undergradstudent, Inventory_Item, YEAR2000.



   

The reserved word public in public class HelloWorld, is an access modifier that defines the circumstances under which a class can be accessed. public access is the most liberal type of access that allows other programs to access a class (also used to define methods, and data). Contents of all classes are enclosed in curly brackets ({ }), which can contain any number of data items and methods. In. Figure 2.1, the class HelloWorld contains only one method, main( ) within its curly brackets. main( ) also has its own curly brackets ({ }) and contains one statement - the println( ) statement. All Java applications must have a main( ) method because that is the first method to be executed by a Java compiler, upon execution of an application. In the method header, public static, void main (String[ ] args):  public - is the access modifier that allows public access to members of the HelloWorld class.  static - is also a modifier that indicates that every member created for the HelloWorld class will have an unchanging and identical main( ) method. Within the Java programming language, it also represents uniqueness - only one main( ) method for the HelloWorld class will ever be stored in the computer memory. Other classes might eventually have their own main( ) methods of course.  void - means the main( ) methods returns no value when it is called. It does not mean that the main( ) method is empty. main( ) produces output through other methods. It does not send any value to println( ) in Figure 2.1 but println( ) needs main( ) in order to produce output to screen.  (String[ ] args) - is the argument passed to the main( ) method. String[ ] represents a Java class that can be used to represent a string of characters or array of string objects. args is the identifier used to hold any strings passed to the main( ) methods. main( ) can do anything with those arguments and although it doesn‟t do anything with args in Figure 2.1, it must be placed in the main( ) method anyway. The identifier does not have to be named args (could be any legal identifier) but it has been traditionally used in Java programming.

COMMENTS  “//” go to the end of line. Must be used at the beginning of every line.  “/*” ends at the next “*/”.  “/**” indicates text to be picked up by javadoc - an automatic documentation generator. IDENTIFIERS  Identifiers are names provided by the programmer in a program and they can be of any length in the Java programming language.  The criteria used in naming identifiers are discussed in the naming of class identifiers earlier in the notes.  Java uses the 16-bit Unicode character set.  Unicode is the solution chosen for the support of Asian languages.  Unicode supports 65,536 different characters used in several languages worldwide.


Lab Program #1 (HelloWorld.java) 1. Using any text editor, type the following code. 2. Compile and run to see the output.
public class HelloWorld { public static void main (String[] args) { System.out.println("Hello World"); } }

Figure 1.5 HelloWorld.java program VARIABLES AND CONSTANTS  Contant - data that cannot be changed after a program is compiled. E.g., 45 is a constant in the statement, System.out.println(45);  Variables - named memory locations that a program can use to store values. E.g., System.out.println(ovenTemperature); Depending on the what value is stored in ovenTemperature, different values might display when the program is executed multiple times, during each run of the program.  Java provides for 8 primitive data types namely: boolean, byte, char, double, float, int, long, short. These primitive data types serve as building blocks for more complex data types called reference types (objects).  Variables are named using the same rules as legal class identifiers.  Variables must be declared before use, variables declarations include:  A data type that identifies the type of data that the variable will store.  An identifier that is the variable‟s name.  An optional assigned value.  An ending semicolon. NOTE: Variables usually begin with lowercase letters to distinguish them from class identifiers, although they can also begin with uppercase letters. E.g., myAge = 25;. “=” is the assignment operator that assigns the value 25 to myAge. An assignment made when a variable is declared is an initialization and when the assignment is made later is it an assignment. E.g. int myAge = 25; // an initialization (declaring and assigning a value) int myAge; // declaration myAge = 25; // assignment NUMERIC DATA TYPES (int, byte, short, long, float, double)  Variables of type int are used to store integers or whole numbers. byte and short are used for small integer values in order to save space. long is used for integer values that might be very big. To change an int to a long, you simply add l or L at the end of the value. E.g.,  Variables of type float are used for decimal point values. A float data type can hold values up to 6 or 7 significant digits of accuracy. A double data type can hold 14 to 15 significant digits of accuracy. Significant digits mean the mathematical accuracy of a value. E.g., a float will display the value .324616777 as .324617 and value of 324616777 will be displayed



 

by float as 3.24617e+008 (approx. 3.2 x 10 to the 8th power - 324617000). The e stands for exponents. A Literal or Literal Constant - value that is taken literally at each use. E.g. 25 is a literal of the statement int i = 25. By default, an integer literal constant like 932 is an int data type value. To use a constant higher than an int value, you can append the letter l or L at end of the value. Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type value. E.g., 5.0 is considered a double and not a float. You can make a number a float or double by simply appending the letters f, F, d, D, respectfully. Figure 1.6 below shows the numeric data types and their limits.
Minimum Value -12 -32768 -2147483648 -9223372036854775808 -3.4e38 (-3.4 * 1038) -1.7e308 (-1.7 * 10308) Maximum Value 127 32767 2147483647 9223372036854775807 3.4e38 (3.4 * 1038) 1.7e308 (1.7 * 10308) Size in Bytes 1 2 4 8 4 8 Size in bits 8 16 32 64 32 64

Type byte short int long float double

Figure 1.6 Numeric data types and their limits Lab Program #2 (DemoVariables.java)
public class DemoVariables { public static void main (String[] args) { int oneInt = 315; short oneShort = 23; System.out.println("The int is: " + oneInt); System.out.println("The short is: " + oneShort); } }

Figure 1.7 DemoVariables.java program ARITHMETIC STATEMENTS  The five standard arithmetic operators used in arithmetic statements are described in Figure 1.8.  NOTE: All the operators, except modulus (%) are used by both int and float data type values.
Operator + * / % Description Addition Subtraction Multiplication Division Modulus (remainder) Example 45 + 2 = 47 45 - 2 = 43 45 * 2 = 90 45 / 2 = 22 (22.5 for float) 45%2 = 1 (45/2 = 22 remainder 1)

Figure 1.8 Arithmetic Operators


Lab Program #3 (ArithmeticStatements.java)
public class ArithmeticStatements { public static void main (String[] args) { int value1 = 43, value2 = 10, sum, difference, product, quotient, modulus; sum = value1 + value2; difference = value1 - value2; product = value1 * value2; quotient = value1 / value2; modulus = value1 % value2; System.out.println("The Sum is: " + sum); System.out.println("The Difference is: " + difference); System.out.println("The Product is: " + product); System.out.println("The Quotient is: " + quotient); System.out.println("The Modulus is: " + modulus); } }

Figure 1.9 ArithmeticStatements.java program SHORTCUT OPERATORS  Shortcut operators originally came from C, inherited by C++ and adopted by Java. Shortcut operators make expressions short, however, it makes them complex and difficult to read sometimes. Figure 1.10, shows some shortcut operators.  The last shortcut operators are often used in loop statements - the structures that control how many times an operation or a sequence of operations is performed in succession. Operator Example Equivalent += i += 5 i=i+5 -= i -= 5 i=i-5 *= i *= 5 i=i*5 /= i /= 5 i=i/5 %= i %= 5 i=i%5 ++ x++ or ++x x = x + 1(increments) -x--or --x x = x - 1(decrements) Figure 1.10 Shortcut Operators and their Equivalents NUMERIC TYPE CONVERSION  When arithmetic is performed on variables or constants of the same type, the result of the arithmetic retains the same type. E.g., when two integers are added, the result is an integer, and when two doubles are added, the result is a double.  Often, there might be instances when mathematical operators may be performed on unlike types. E.g. int hoursWorked = 37; double payRate = 6.73; grossPay = hoursWorked * payRate;  When this happens, Java chooses a unifying type for the result. Java then implicitly (or automatically) converts nonconforming operands to the unifying type.  The unifying type is the type of the involved operand that appears first in the following list:



1. double 2. float 3. long 4. int 5. short 6. byte So for the example above, grossPay is the result of multiplication of an int and a double, so grossPay itself must be double. Similarly, an addition of a short and an int result in an int.

Lab Program #5 (UnifyType.java)
public class UnifyType { public static void main (String[] args) { double grossPay; int hoursWorked = 40; double payRate = 60.50; grossPay = hoursWorked * payRate; System.out.println("The Gross Pay is: " + grossPay); } }

Figure 1.11 UnifyType.java program   The unifying type imposed by Java could explicitly (or purposely) be overridden by performing a type cast. Type casting involves placing the desired result type in parenthesis followed by the variable or constant to be cast. E.g., int hoursWorked = 37; double payRate = 6.73; grossPay = hoursWorked * (int) payRate; Instead of producing a double type result, grossPay will be an int type. NOTE: It is very easy to lose data when performing a cast. E.g., int hoursWorked = 37; double payRate = 600; (byte) grossPay = hoursWorked * payRate; The result will be distorted since the largest byte value is 127.

 


Lab Program #6 (TypeCast.java)
public class UnifyType { public static void main (String[] args) { double grossPay; int hoursWorked = 40; double payRate = 60.50; grossPay = hoursWorked * (int)payRate; System.out.println("The Gross Pay is: " + grossPay); } }

Figure 2.10 TypeCast.java program


CHARACTER DATA TYPE (char)  The character data type, char, is used to hold or represent any single character.  A character value is placed within single quotation marks because the computer stores characters and integers differently.  E.g. char letterValue = ‘A’; // legal char numberValue = ‘4’; // legal char numberValue = 4; // illegal int letterValue = ‘A’ ; // illegal  A variable of type char can only store one character.  To store a string of characters, such as a person‟s name the String data structure must be used. Unlike single characters, which use single quotation marks, string constants are written between double quotation marks. E.g., String name = “Java Programming”. Strings will be discussed more detailed under the topic “Arrays and Strings”.  Any character (such a backspace) can be stored in a char variable. To store these characters, the escape sequence must be used.  The escape sequence always begins with a backslash. Figure 1.12 shows the Escape Sequences.  Java characters use Unicode (16-bit encoding scheme) which are expressed in four hexadecimal numbers that run from „\u000‟ to „\uFFFF‟. For instance the unicode, „\u0007‟ is a bell that produces a noise if you send it to output.  The examples below are equivalent: char letter = ‘A’; char letter = ‘\u0041’;  But obviously, the second example (using Unicodes) is very difficult and confusing to use. Escape Sequence
\b \t \n \f \r \” \‟ \\

Backspace Tab New line or linefeed Form feed Carriage return Double quotation mark Single quotation mark Backslash

\u0008 \u0009 \u000a \u000d

Figure 1.12 Common Escape sequences and some Unicode Equivalents. THE BOOLEAN DATA TYPE  The boolean data type comes from Boolean algebra. The domain of the boolean type consists of two values: true and false.  E.g., boolean isItPayday = true; boolean areYouBroke = false;  Values can also be assigned based on the result of comparisons to boolean variables. Java supports six (6) comparison operators listed in Figure 1.13.  A comparison operator compares two items; an expression containing a comparison operator has a boolean value.  NOTE: (==) is a comparison operator while (=) is for assignment.


< <= > >= == !=

Less than Less than or equal to Greater than Greater than or equal to Equal to Not equal to

1<2 1 <= 2 1>2 1 >= 2 1 == 1 1 != 2

true true false false True true

Figure 1.13 Comparison Operators   Boolean Operators (Figure 1.14) operate on Boolean values to result in a new Boolean value. Boolean Operators will be treated in-depth on the topic “Input, Selection, and Repetition”. Name not and or exclusive or Description logical negation logical conjunction logical disjunction logical exclusive (one of the other and not both)

Operator ! && || ^

Figure 1.14 Boolean Operators Lab Program #4 (BooleanVariables.java)
public class BooleanVariables { public static void main (String[] args) { boolean areYouBroke = true, isItPayDay = false; System.out.println("The value for areYouBroke is: " + areYouBroke); System.out.println("The value for isItPayDay is: " + isItPayDay); } }

Figure 1.15 DemoVariables.java program


Jun Wang Jun Wang Dr
About Some of Those documents come from internet for research purpose,if you have the copyrights of one of them,tell me by mail vixychina@gmail.com.Thank you!