Java (SE) Programming Course

May 31, 2016 | Author: Shin Mañale Ocampo | Category: Types, Instruction manuals
Share Embed Donate


Short Description

The Java Standard Edition for Beginners...

Description

Java (SE) Programming Course

Course Objective 

Introduce you to all the key concepts of the Java language, language, as well as a full coverage coverage of the Java Syntax

 You  You will be exposed to examples examples of building programs that incorporates Java as it’s primary  building blocks.



History  Java was conceived conceived by James Gosling, Gosl ing, Patrick Naughton, Chris Chri s Warth, Warth, Ed Frank, and Mike Mi ke Sheridan at Sun Microsystems, Microsys tems, Inc in 1991. It took 18 months months to develop develop the first first working working version. Then language was initially called “Oak but renamed “Java” in 1995. Somewhat surprisingly, surprisingly, the original impetus for  Java was not the internet! Instead, Instead, the primary  primar y  motivation was the need for a platformindependent (that is architecture-neutral) language language that could could be used to create software

To be embedded in various consumer electronic devices, such as microwave ovens and remote control.  About the time that th thee details of java were being  worked  worked out, a second factor was emerging that  would play a crucial crucial role in the future of Java. This  was, of course, the World Wide Web. Had the Web not taken shape at about the same time that Java  was being implemented. implemented. Java might have have remained a useful but but obscure language for programming consumer electronics. electronics. Ho Howev wever er,, with with the the emergence emergence of the World World Wide Web, Web, Java was propelled to the forefront of 

Of computer computer language design, because because the Web, Web, too, demanded portable programs. The Java Programming Language?  Java is a general-purpose, concurrent, class-based, object-oriented language. It is designed to be simple enough that many programmers can achieve fluency  in the language. Java is related to C and C++ C ++ but is organized rather differently, differently,  with a number of aspects of C and C++ omitted and a few ideas from other languages included. Java is intended to be a production language, not a research language, and so, as C. A. R. Hoare suggested in his classic paper on language design, the design of Java has avoided including new and untested features. 

 Java is strongly typed. This specification clearly distinguishes between the compile-time errors that can and must be detected at compile time, and those that occur at run time. Compile time normally consists of translating Java programs into a machine-independent byte-code representation. Run-time activities include loading and linking of the classes needed to execute a program, optional machine code generation and dynamic optimization of the





 Java is a relatively high-level language, in that details of the machine representation are not available available through the language. It includes automatic storage management, typically using a garbage g arbage collector, collector, to avoid the safety problems of explicit deallocation (as in C's free or C++'s delete). High-performance High-perfo rmance garbage-collected garbage-collected implementations of Java can have bounded pauses paus es to support systems programming and realtime applications. Java does not include inc lude any unsafe constructs, such as array accesses without index checking, since such unsafe constructs  would cause a program to behave in an unspecified way.  Java is normally compiled compiled to a bytecoded instruction instructio n set and binary  bi nary  format defined in The Java Virtual Machine Specification

 Why Choose Java?  You should choose Java because it is: Simple Secure Portable Object-oriented Robust Multithreaded  Architecture-neutral Interpreted High performance Distributed Dynamic           









 Java Reserved Words

abstract

assert

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

transient

try

void

volatile

while

Escape characters Backslash ( \ ) Indicates special characters be output  

Escape sequence \n

\t \r

\\ \"

Fig. 2.5

Description Newline. Position the screen cursor at the beginning of the next line. Horizontal tab. Move the screen cursor to the next tab stop. sto p. Carriage return. Position the screen cursor at the beginning of  the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line. Backslash. Used to print a backslash character. character. Double quote. Used to print a double quote charcter

Some common escape sequences.



Data Types Every variable must have a data type. A variable's variab le's data type determines the values that th at the variable can contain contain and the th e operations that can be performed on it. For example, in the MaxVariablesDemo program, the declaration int largestInteger declares that largestInteger has an integer data type (int). Integers can contain only integral values (both positive posit ive and negative). negative). You You can perform arithmetic arit hmetic operations, such suc h as addition, on integer variables. variable s. The Java programming language langua ge has two categories categories of data da ta types: primitive and reference. A variable of primitive pri mitive type contains a single value of the the appropriate size and format forma t for its type: type : a number, number, a character, character, or a boolean boolea n value. For example, an integer value is 32 bits of data in a format known as two's complement complement,, the value of a char is 16 bits bi ts of  data formatted forma tted as a Unicode character, character, and so on.



Primitive types 



 Java is strongly typed 



“building blocks” for more complicated types  All variables varia bles in a Java program must have a type

 Java primitive types 

portable portab le across computer computer platforms that tha t support Java

Typ e boolean

Siz ize e in b its

char

16

byte

8

short

16

int

32

long

64

float

32

Va lue s true or false

Sta nd a rd

[ Note: The representation of a boolean is specific to the Java Virtual Machine on each computer platform.] '\u0000' to '\uFFFF' (ISO Unicode character set) (0 to 65535)  – 128 128 to +127 ( – 27 to 27  –  1)  – 32,768 32,768 to +32,767 ( – 215 to 215  –  1) 2,147,483,648 to +2,147,483,647 +2,147,483,647  – 2,147,483,648 31 31 ( – 2 to 2  –  1) 9,223,372,036,854,775,808 t o  – 9,223,372,036,854,775,808 +9,223,372,036,854,775,807 63 63 ( – 2 to 2  –  1)  Negative range: (IEEE 754 floating point) 3.4028234663852886E+38 to  – 3.4028234663852886E+38 1.40129846432481707e – 45 45  – 1.40129846432481707e Positive range:

1.40129846432481707e – 45 45 to 3.4028234663852886E+38

double

64

 Negative range:

 – 1.7976931348623157E+308 1.7976931348623157E+308 to to 4.94065645841246544e – 324 324  – 4.94065645841246544e Positive range:

4.94065645841246544e – 324 324 to 1.7976931348623157E+308

Fig. 4.16 The Java p rimitive typ es. es.

(IEEE 754 floating point)

* MaxVariablesDemo.java is an application that compiles and runs

* under J2SE 5.0. It requires no other files. public class MaxVariablesDemo { public static void main(String args[]) {  // integers byte largestByte = Byte.MAX_VALUE; short largestShort = Short.MAX_VALUE; int largestInteger = Integer.MAX_VALUE; long largestLong = Long.MAX_VALUE;  // real numbers float largestFloat = Float.MAX_VALUE; double largestDouble = Double.MAX_VALUE;  // other primitive types char aChar = 'S'; boolean aBoolean = true;

 // display them all System.out.println("The largest byte value is " + largestByte); System.out.println("The System.out.println("The largest short value is " + largestShort); largestShort); System.out.println("The System.out.println("The largest integer value is " + largestInteger); System.out.println("The System.out.println("The largest long value is " + largestLong); largestLong); System.out.println("The System.out.println("The largest float value is " + largestFloat); largestFloat); System.out.println("The System.out.println("The largest double value is " + largestDouble); largestDouble); if (Character.isUpperCase(aChar)) { System.out.println("The System.out.println("The character " + aChar + " is upper case."); } else { System.out.println("The character " + aChar + " is lower case."); } System.out.println("The System.out.println("The value of aBoolean is " + aBoolean); } }

•Reference types Arrays, classes, and interfaces are reference  types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable (see the following figure). A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.

• Operators An operator performs a function on one, two, or three operands. An operator that requires one operand is called a unary operator . For example, ++ is a unary operator that increments the value of its operand by 1.

An operator that requires two operands is a binary operator . For example, = is a binary operator that assigns the value from its right-hand operand to its left-hand operand. And finally, a ternary operator is one that requires three operands. The Java programming language has one ternary operator, ?:, which is a short-hand ifelse statement. • Arithmetic Operators The Java programming language supports various arithmetic operators for all floating-point floating-point and integer numbers. These operators are + (addition), (subtraction), (subtraction), * (multiplication), (multiplication), / (division), and % (modulo). The following table summarizes the binary arithmetic operations in the Java programming language.

O p e ra to r(s) * / + -

Fig. 2.17

O p e ra ra t io io n ( s) O rd rd e r o f e v a lu lu a t io io n (p (p re c e d e n c e ) Multiplication Division Remainder Addition Subtraction

Evaluated first. If there are several of this type of operator, they are evaluated from left to right. Evaluated next. If there are several of this type of operator, they are evaluated from left to right.

Prec ed enc e of a rithm etic o p er era a to rs.

Operator precedence Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3 Follows PEMDAS Parentheses, Exponents, Multiplication, Division, Addition, Addition, Subtraction

Here's an example program, ArithmeticDemo , that defines two integers and two double-precision double-precision floating-point floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface: public class ArithmeticDemo { public static void main(String[] args) {  //a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" System.out.println(" i = " + i); System.out.println(" System.out.println(" j = " + j); System.out.println(" System.out.println(" x = " + x); System.out.println(" y = " + y);

 //adding numbers System.out.println("Adding..."); System.out.println(" System.out.println(" i + j = " + (i ( i + j)); j)); System.out.println(" System.out.println(" x + y = " + ( x + y)); y));  //subtracting  //subtracting numbers System.out.println("Subtra System.out.println("Subtracting..."); cting..."); System.out.println(" System.out.println(" i - j = " + ( i - j)); j)); System.out.println(" System.out.println(" x - y = " + ( x - y)); y));  //multiplying  //multiplying numbers System.out.println("Multip System.out.println("Multiplying..."); lying..."); System.out.println(" System.out.println(" i * j = " + (i ( i * j)); j)); System.out.println(" System.out.println(" x * y = " + ( x * y)); y));  //dividing numbers System.out.println("Dividing..."); System.out.println(" System.out.println(" i / j = " + ( i / j)); j)); System.out.println(" System.out.println(" x / y = " + ( x / y)); y));

 //computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" System.out.println(" i % j = " + (i ( i % j)); j)); System.out.println(" x % y = " + ( x % y)); y));  //mixing types System.out.println("Mixing types..."); System.out.println(" System.out.println(" j + y = " + ( j + y)); y)); System.out.println(" System.out.println(" i * x = " + ( i * x)); x)); } } The output from this program is: Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37

Dividing... i/j=0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types...  j + y = 49.22 i * x = 1016.58

Note that when an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. The following table summarizes the data type returned by the arithmetic operators, based on the data type of the operands. The necessary conversions take place before the operation is performed.

Shortcut Arithmetic Arithmetic Operators

Operator

Use

Description

++

op++

Increments op by 1; evaluates to the value of op before it was incremented

++

++op

Increments op by 1; evaluates to the value of op after it was incremented

--

op--

Decrements op by 1; evaluates to the value of op before it was decremented

--

--op

Decrements op by 1; evaluates to the value of op after it was decremented

The following program, called SortDemo , uses ++ twice and -- once. public class SortDemo { public static void main(String[] args) { int[ ] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; arrayOfInts.length; --i >= 0; 0; ) { for (int j = 0; j < i; i ; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) i++) { System.out.print(arrayOfInts[i] System.out.print(arrayOfInts[i] + " "); } System.out.println(); } } This program puts ten integer values into an array — a fixed-length structure that can hold multiple values of the same type — then sorts them. The boldface line of code declares an array referred to by arrayOfInts, creates the ar ray, ray, and puts ten integer values into it. The program uses arrayOfInts.length to get the number of e lements in the array. array. Individual elements are accessed with this notation: arrayOfInts[index], where index is an integer indicating the position of the element within the array. array. Note that indices begin at 0. You’ll get more details and examples for arrays in the section Arrays . The output from this program is a list of numbers sorted from lowest to highest: 3 8 12 32 87 127 589 622 1076 2000

Relational and Conditional Operators A relational operator compares two values and determines the relationship between them. For example, != returns true if its two operands are unequal. The next table summarizes the relational operators: Sta nda rd a lg eb ra ic Java eq uali uality ty eq ua lity or or rrelat elat iona l relational op erator operator  Equality operators = 

 Relational operators > <  

Example of Ja Ja va condition

Mea ni ning ng o f Java c ond iti tion on

== !=

x == y x != y

x is equal to y x is not equal to y

> < >= y < y >= y j)); j)); //false System.out.println(" System.out.println(" j > i = " + ( j > i)); i)); //true System.out.println(" System.out.println(" k > j = " + (k ( k > j)); j)); //false;  //they are equal  //greater than or equal to System.out.println("Greater System.out.println("Greater than or equal to..."); System.out.println(" System.out.println(" i >= j = " + ( i >= j)); j)); //false System.out.println(" System.out.println(" j >= i = " + ( j >= i)); i)); //true System.out.println(" System.out.println(" k >= j = " + ( k >= j)); j)); //true

 //less than System.out.println("Les System.out.println("Less s than..."); System.out.println(" System.out.println(" i < j = " + ( i < j)); j)); //true System.out.println(" System.out.println(" j < i = " + ( j < i)); i)); //false System.out.println(" System.out.println(" k < j = " + ( k < j)); j)); //false  //less than or equal to System.out.println("Less System.out.println("Less than or equal to..."); System.out.println(" System.out.println(" i 5) numberOfEnemies = 10; else numberOfEnemies = 5;  A shorter way to do this is to use the ternary operator, which is ?. A ternary operator has the following foll owing parts: The condition to test, surrounded by parentheses, as in (skillLevel > 5)  A question mark (?) The value to use if the condition is true  A colon (:) The value to use if the condition is false    

To use the ternary operator to set the value of numberOfEnemies number OfEnemies based on skillLevel, skill Level, you could use the following statement: numberOfEnemies = ( skillLevel > 5) ? 10 : 5;



Exercises 1 (Nested if Statement) 

the

Create a module nestedIf.java.

This module functionality f unctionality would be to evaluate age value and print appropriate information listed below. below. If Age < 18 print "You're "You're young - enjoy it! If not print "You're "You're not under 18" If Age >= 18 and Age < 50 print "You're "You're in the prime of your life“ if not print "You're "You're not in the prime of your life\n"; If Age >= 50 print " print "You "You can retire retire soon - hurrah! “ if not print "print "You cannot retire soon :( “.



Exercises 2 (Nested If Statement) 

the

Create a module nestedIf2.java.

This module functionality f unctionality would be to evaluate age value and print appropriate information listed below. below. 









 Age < 10 print " print "You're "You're under 10“  Age < 20 print "You're "You're under 20“  Age < 30 print "You're "You're under 30“  Age < 40 print pri nt "You're "You're under 40“  Age more than 40 print "You're "You're over 40"



Exercises 3 (Nested If Statement) 

the

Create a module nestedIf3.java.

This module functionality f unctionality would be to evaluate name value and print appropriate information listed below. below. 









Name is Jim print prin t " print prin t "You'r "You'ree name is Jim“ Jim“ Name is Bob print prin t "You're name is Bob“ Name is Sally print "You're name is Sally“ Name is Linda print "You're name is Linda“ Else print “I don’t don’t know you’re you’re name"



Exercises 4 (Switch Statement) 

Create a module switch1.java.

This module functionality f unctionality would be to evaluate a numeric value and print the appropriate information listed below. below. 











iValue = 1 set value = “Ace“ iValue = 10 set value = “Ten“ iValue iV alue = 11 set value = “Jack“ iValue iV alue = 12 set value = “Queen“ “Queen“ iValue iV alue = 13 set value = “King“  After evaluation print “ iV iValue alue = “ value valu e variable.



Exercises 5 (Switch Statement) 

Create a module switch2.java.

This module functionality f unctionality would be to evaluate grade value and print the appropriate information listed below. below. 







Grade = ‘A’ print “You got an A. Great job” Grade = ‘B’ print “Y “ You got a B. Good work!” Grade = ‘C’ ‘C ’ print “You got a C. You'll never get into a good good college!” Grade = ‘F’ print "You "You got an F. F. You'll You'll do well in Congress!"

The full text of ClockTalk.java. import java.util.*; public class ClockTalk { /** * Creates a new instance of ClockTalk. */ public ClockTalk() { } /** * @param args the command line arguments */ public static void main(String[] args) { // get current time and date GregorianCalendar now = new GregorianCalendar(); int hour hou r = now.get(Calend now.get(Calendar ar.HOUR); .HOUR); int minute = now.get(Calenda now.get(Calendarr.MINUTE); int month = now.get(Calendar.MONTH) + 1; int day = now.get(Calendar.DATE); int year = now.get(Calend now.get(Calendar ar.YEAR); .YEAR);

// display greeting if (hour < 12) System.out.println("Good morning.\n"); else if (hour < 17) System.out.println("Good afternoon.\n"); else System.out.println("Good evening.\n"); // begin beg in time message by showing the minutes System.out.print("It's"); if (minute != 0) { System.out.print(" " + minute + " "); System.out.print( (minute != 1) ? "minutes" : "minute"); System.out.print(" past"); } // display the hour System.out.print(" "); System.out.print( (hour > 12) ? (hour - 12) : hour ); System.out.print(" o'clock on ");

// display the name of the month switch (month) { case (1): System.out.print("January"); break; case (2): System.out.print("February"); break; case (3): System.out.print("March"); break; case (4): System.out.print("April"); break; case (5): System.out.print("May"); break; case (6): System.out.print("June"); break; case (7): System.out.print("July"); break; case (8): System.out.print("August"); break;

case (9): break; case (10): System.out.print("October"); break; case (11): System.out.print("November"); break; case (12): System.out.print("December"); } // display the date and year System.out.println(" " + day+", " + year + "."); } }

Repetition Statement 

Repeat action while condition condition remains remain s true

merge

decision

[product 1000] Corresponding Java statement: product = 2 * product;

Fig 4.5 while repetition statement activity diagram.

Repeating an Action with Loops One of the more annoying punishments for schoolchildren is to make them write something over and over again on paper or, for a capital offense, on the chalkboard. In one of his frequent trips to the board, cartoon problem child Bart Simpson had to write "I will not trade pants with others" dozens of times. This kind of punishment might work on children, but it definitely would fail on a computer. computer. They can repeat repea t a task with ease.

for Loops The most complex of the loop statements is for. The for loop is often used in cases  where you you want to repeat a section of a program for a fixed fi xed amount of times. It also can be used if the number of times the loop should be repeated is variable. The following is an example of a for loop: for (int number = 0; number < 1000; number++) { if (number % 12 == 0) System.out.println("#: " + number); }



 while Like the for loop, the while loop lo op has a loop condition that controls the execution of the th e loop statement. Unlike the for loop, the while loop has no initialization or step expressions. The syntax for the while statement follows:  while (LoopCondition) Statement If the Boolean LoopCondition Lo opCondition evaluates to true, the Statement is executed and the th e process starts over. over. It is important to understand that there is no step expression, expression, as in a for loop. This means that the LoopCondition LoopConditi on must somehow be affected by code in the Statement or the loop will infinitely repeat, which is a bad thing. This is bad because an infinite loop lo op causes a program to never exit, which hogs processor time and can ultimately hang the system.  Another important thing to notice about the while loop is that its LoopCondition LoopConditi on occurs occurs before the body of the loop Statement. This means that if the LoopCondition LoopConditio n initially evaluates to false, the Statement never  will be b e executed. This might seem trivial, but it is in fact the only thing that differentiates the while loop from the do-while loop.

To better understand how the while loop works, take a look at Listing 13.15, which shows how a counting program works using a while loop. The WhileCount class. class WhileCount { public static void void main (String args[ ]) { String strLine = ""; int numToCount; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter a number to count to between 0 and 10:"); try { strLine =in.readLine(); } catch (Exception e) { System.out.println("Error: " + e.toString()); } numToCount numToCount = Integer.parseInt(strLine); Integer.parseInt(strLine); if ((numToCount > 0) && (numToCount < 11)) { int i = 1;  while (i 100) break; }  while (true); } } 



Exercises (Loop) 

Create a module nestedLoop1.java.

Here's the output: I: 1, J: 1, K: 1 I: 1, J: 1, K: 2 I: 1, J: 2, K: 1 I: 1, J: 2, K: 2 I: 2, J: 1, K: 1 I: 2, J: 1, K: 2 I: 2, J: 2, K: 1 I: 2, J: 2, K: 2



Exercises (Loop) 

Create a module nestedLoop2.java.

Here's the output: I: 1, J: 1, K: 1 I: 1, J: 2, K: 1 I: 2, J: 1, K: 1 I: 2, J: 2, K: 1

public class nestedFor { public static void main(String[] args) { for (int i = 1; i < 3; i++) { for (int j = 1; j < 3; j++) { for (int k = 1; k < 3; k++) { System.out.println( System.out.println( "I: "+ i +", J:"+ j +", K: "+k+"\n"); } } } } }

public class nestedFor2 { public nestedFor2() { } public static void main(String[] args) { for (int i = 1; i < 3; i++) { for (int j = 1; j < 3; j++) { for (int k = 1; k < 3; k++) { System.out.println("I: System.out.println("I: "+i+ ",J: "+j+",K: "+k+"\n"); break; } } } } }

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF