Introduction Introducti on to Java Programmi Programming ng Computer Programming -
computer scien computer science ce disci disciplin pline e dealing dealing with the crea creation tion and main maintenanc tenance e of computer programs
-
is just one acti activity vity in the more comp complex lex fiel field d of softw software are engin engineeri eering ng
Programming Language -
a standard standardized ized comm communicat unication ion techn technique ique for expr expressin essing g instruc instructions tions to a computer. Like human languages, each language has its own syntax and grammar
-
enables a progr enables programme ammerr to prec precisely isely spec specify ify what what data data a compu computer ter wil willl act upon, how these data will be storedtransmitted, and precisely what actions to take under various circumstances
-
set of of rules, rules, symbo symbols, ls, and and special special wor words ds used used to constr construct uct progr programs ams or instructions that are translated into machine language that can be understood by computers
Java Background Background ! little "it #istory -
developed in early developed early $%% $%%&s &s by 'ames (osli (osling ng et. et. al. al. as the progr programmi amming ng language component of the (reen )roject at *un +icrosystems
-
originall origin ally y named named ak and and intend intended ed for prog program rammi ming ng networ networked ked smart consumer electronics
-
launched launch ed in $%% $%%/ / as a prog program rammi ming ng langua language ge for for the 0nte 0nterne rnet1 t1 quickly gained popularity with the success of the 2orld 2ide 2eb
-
currently currentl y used used by by around around / milli million on software software devel developer opers s and powe powers rs more than 3./ billion devices worldwide, from computers to mobile phones
4esign (oals
simple55 derived from 6677, but easier to learn simple
secure5 built-in support for compile-time and run-time security
distributed5 built to run over networks
object-oriented5 built with features from the start
robust 5 featured memory management, exception handling, etc.
portable5 write once, run anywhere88
interpreted5 bytecodes executed by the Java Virtual Machine
multithreaded, dynamic, high-performance, architecture-neutral Bytecodes are the machine language understood by the Java virtual machine
Java Platform - Java Virtual Machine or JVM5 a virtual machine, usually implemented as a program, which interprets the bytecodes produced by the 'ava compiler1 the '9+ converts the bytecodes instructions to equivalent machine language code of the underlying hardware1 compiled 'ava programs can be executed on any device that has a '9+ Java Programming Environment -
'ava programming language specification o
*yntax of 'ava programs
o
4efines different constructs and their semantics
- Java byte code5 0ntermediate representation for 'ava programs - Java compiler 5 :ransform 'ava programs into 'ava byte code -
Java interpreter 5 ;ead programs written in 'ava byte code and execute them Java virtual machine5 ;untime system that provides various services to running programs Java programming environment 5 *et of libraries that provide services such as (<0, data structures,etc.
-
Java enabled browsers5 "rowsers that include a '9+ 7 ability to load programs from remote hosts
How are Java Programs Written? ! "his program displays the message #$ello, %orld on the standard output device 'usually the screen(..."his code must be saved in a file named $ello%orld.java... ! this is the declaration of the $ello%orld class... pulic class #ello2orld > the main method defines the #starting point# of the execution of this program... pulic static void main?*tring@A argsB > this statement displays the program)s output... *ystem.out.println?C#ello, 2orldDCB1 E end of method main... E end of class $ello%orld...
Fundamental Concepts -
'ava programs are made up of one or more classes.
-
! 'ava class is defined through a class declaration, which, aside from assigning a name for the class, also serves to define the structure and behavior associated with the class.
-
"y convention, 'ava class names start with an uppercase letter. 'ava programs are case-sensitive.
-
! 'ava source code file usually contains one class declaration, but two or more classes can be declared in one source code file. :he file is named after the class it declares, and uses a .java filename extension.
-
=or a class to be executable, it must be declared public, and must provide a public static method called main, with an array argument of type String.
-
0f a file contains more than one class declaration, only one of the classes can be declared public, and the file must be named after the sole public class.
-
:he 'ava compiler ? javacB is used to compile a 'ava source code file into a class file in bytecode format. :he resulting class file has the same name as the source code file, but with a .class filename extension.
-
:he 'ava 9irtual +achine ?javaB is used to execute the class file.
Java Comments -
6omments are notes written to a code for documentation purposes. :hose texts are not part of the program and do not affect the flow of the program. o
:wo types of comment *ingle Line 6omment Fxample5 "his is an example of a single line comment
+ultiline 6omment Fxample5 ! "his is an example of a multiline comment enclosed by two delimiters that starts with a ! and ends with a ! !
Java !tatements and Blocks -
! statement is one or more lines of code terminated by a semicolon. !n example of a single statement is, System.out.println'*$ello world+(
-
! block is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit. "lock statements can be nested indefinitely. !ny amount of white space is allowed. !n example of block is, public static void main 'String args( / System.out.println'*$ello+( System.out.println'*%orld+( 0
Java Identifiers
-
0dentifiers are tokens that represent names of variables, methods, classes, etc. Fxamples of identifiers are5 #ello, main, *ystem, out.
-
'ava identifiers are case-sensitive. :his means that the identifier5 Hello is not the same as "ello. 0dentifiers must begin with either a letter, an underscore G, or a dollar sign H. Letters may be lower or upper case. *ubsequent characters may use numbers & to %.
-
0dentifiers cannot use 'ava Ieywords like class, public, void, etc.
6oding (uidelines
=or names of classes, capitalize the first letter of the class name. =or names of methods and variables, the first letter of the word should start with a small letter. =or example5 T hisIs AnE xampleOf ClassName t hisIs AnE xampleOf MethodName
0n case of multi-word identifiers, use capital letters to indicate the start of the word except the first word. =or example, char!rray, fileJumber, 6lassJame. !void using underscores at the start of the identifier such as Gread or Gwrite.
Coding and #eugging -
+ost of the time, after a programmer has written the program, the program isnKt $&& working right away. :he programmer has to add some fixes to the program in case of errors ?also called bugsB that occurs in the program. :his process is called deugging.
-
:wo :ypes of )rogram Frrors o
6ompile-:ime Frror
ccur if there is a syntax error in the code. :he compiler will detect the error and the program wonKt even compile. !t this point, the programmer is unable to form an executable that a user can run until errors are fixed. =orgetting a semi-colon at the end of a statement or
o
misspelling a certain command, for example, is a compiletime error. ;untime Frror
6ompilers arenKt perfect and so canKt catch all errors at compile time. :his is especially true for logic errors such as infinite loops. :his type of error is called runtime error. =or example, the actual syntax of the code looks okay. "ut when you follow the codeKs logic, the same piece of code keeps executing over and over again infinitely so that it loops.
Java $e%words -
Ieywords are predefined identifiers reserved by java for specific purposes. Mou cannot use keywords as names of variables, classes, methods, etc.
Primitive #ata &%pes in Java -
four of them represent integers5 o
-
two of them represent floating point numbers5 o
-
byte, short, int, long
float, double
one of them represents characters5 o
char
-
and one of them represents boolean values5 o
boolean
'umeric Primitive #ata -
:he difference between the various numeric primitive types is their size, and therefore the values they can store5
Boolean Primitive #ata -
a boolean value represents a true or false condition
-
the reserved words true and false are the only valid values for a boolean type example5 boolean done 1 false
-
boolean variable can represent any two states such as a light bulb being on or off example5 boolean is2n 1 true
C"aracters -
a char variable stores a single character
-
character literals are delimited by single quotes5 3a3 343
353
363
3,3
Fxample declarations5 char top8rade 1 393
37n3
char terminator 1 33, separator 1 3 3
-
! character set is an ordered list of characters, with each character corresponding to a unique number
-
! char variable in 'ava can store any character from the :nicode character set
-
:he
-
0t is an international character set, containing symbols and characters from many world languages
-
:he 9S;<< character set is older and smaller than
-
:he !*600 characters are a subset of the
C"aracter !trings -
! string of characters can be represented as a string literal by putting double quotes around the text5 Fxamples5 C:his is a string literal.C C$3O +ain *treetC CPC
-
Jote the distinction between a primitive character QPK, which holds only one character, and a *tring object, which can hold a sequence of one or more characters
-
Fvery character string is an object in 'ava, defined by the *tring class
(ariales
-
a variable is a name for a location in memory
-
a variable must be declared by specifying the variable8s name and the type of information that it will hold
-
multiple variables can be created in one example5 int count, temp, result
(ariale Initiali)ation -
assigning a value to a variable for the first time
-
a variable can be given an initial value in the declaration with an equals sign example5 int sum 1 = int base 1 >?, max 1 @AB
-
when a variable is referenced in a program, its current value is used example5 int Ceys 1 DD System.out.println'*9 piano has +E Ceys E * Ceys+(
-
prints as5 ! piano has RR keys
*ssignment -
an assignment statement changes the value of a variable
-
the equals sign is also the assignment operator
-
the expression on the right is evaluated and the result is stored as the value of the variable on the left
-
the value previously stored in total is overwritten
-
you can only assign a value to a variable that is consistent with the variable8s declared type
Constants -
a constant is an identifier that is similar to a variable except that it holds the same value during its entire existence
-
as the name implies, it is constant, not variable
-
in 'ava, we use the reserved word final in the declaration of a constant example5 final int minFheight 1 GB
-
any subsequent assignment statement with minFheight on the left of the S operator will be flagged as an error
6onstants are useful for three important reasons o
first, they give meaning to otherwise unclear literal values
o
second, they facilitate program maintenance
o
for example, J<+G*:!:F* means more than the literal /&
if a constant is used in multiple places and you need to change its value later, its value needs to be updated in only one place
third, they formally show that a value should not change, avoiding inadvertent errors by other programmers
&"e println +et"od -
the System.out object represents a destination ?the monitor screenB to which we can send output System.out.println '#%hatever you are, be a good one.#( 2bject Method name
&"e print +et"od -
the System.out object provides another method
-
the print method is similar to the println method, except that it does not start the next line
-
therefore any parameter passed in a call to the print method will appear on the same line System.out.print '*"hreeI +( System.out.print '*"woI +(
prints as5
"hreeI "woI
!tring Concatenation -
the string concatenation operator ?7B is used to append one string to the end of another #Heanut butter # E #and jelly#
-
it can also be used to append a number to a string
-
a string literal cannot be broken across two lines in a program so we must use concatenation
System.out.println'*%e present the following facts for your + E *extracurricular edification+(
-
the 7 operator is also used for arithmetic addition
-
the function that it performs depends on the type of the information on which it operates
-
if both operands are strings, or if one is a string and one is a number, it performs string concatenation
-
if both operands are numeric, it adds them
-
the 7 operator is evaluated left to right, but parentheses can be used to force the order System.out.println'*?A and A concatenatedK + E ?A E A(
prints as5 ?A and A concatenatedK ?AA -
the 7 operator is evaluated left to right, but parentheses can be used to force the order 9ddition is done first
System.out.println'*?A and A addedK + E '?A E A((
"hen concatenation is done
prints as5 3T and T/ added5 N%
Escape !e,uences -
2hat if we want to include the quote character itselfU
-
:he following line would confuse the compiler because it would interpret the two pairs of quotes as two strings and the text between the strings as a syntax error5 System.out.println '#< said #$ello# to you.#(
-
!n escape seLuen ce is a series of characters that represents a special character
-
Fscape sequences begin with a backslash character ?VB System.out.println '#< said 7#$ello7# to you.#(
-
*ome 'ava Fscape *equences
*ystem.out.println?;oses are red,VnVt9iolets are blueB1 )rints as5 oses are red, Violets are blue,
-
:o put a specified
)rints as5 Nody temperature is BD.G PO.
-perators 0n 'ava, there are different types of operators. :here are arithmetic operators, relational operators, logical operators and conditional operators. :hese operators follow a certain kind of precedence so that the compiler will know which of the operator to evaluate first in case multiple operators are used in one statement. *rit"metic -perators -perator
-peration
7
!ddition
-
*ubtraction
Y
+ultiplication
4ivision
+odulus ?;emainderB
E.ample 37T SN 3 7 3.T S T.T /.3 7 W.O S $O./ T/ X %& S - T/ 3.% X 3./ S &.O%%%%%%%% 3.% X 3 S &.R%%%%%%%%% 3 Y W S $T 3.% Y 3 S / .R 3.% Y 3.$ S N.&% 3WS& 3.% 3 S $.T/ 3.$ 3.% S &.W3T$OW%O$& 3WS3 3.% 3 S &.R%%%%%%%%% 3.% 3.$ S &.W%%%%%%%R
Jote5 2hen evaluating the mod operator with negative integer operands, the answer always takes the sign of the dividend. 0llustration5 ->A Q 1 -A >A Q- 1 A ->A Q- 1 -A
>A Q 1 A :erms5 2HR9TS U may refer to the numbers or alphabetical symbols that we use in our expression ' formula ( :9 2HR9"2S U operators that only have one operand. 'exampleK -( N<9 2HR9"2S U operators that have two operands
Increment/#ecrement -perators -
!side from basic arithmetic operators, 'ava also includes a unary increment operator and unary decrement operator. o
0ncrement perator ?77B - increases the value of a variable by $ Fxample5 int count 1 > count 1 count E @ the above statement may be written as the one shown below. countEE
o
4ecrement perator ?--B - decreases the value of a variable by $ Fxample5 int count 1 > count 1 count - @ the above statement may be written as the one shown below. count--
0elational -perators -
;elational operators compare two values and determine the relationship between those values.
-
:he outputs of evaluation are the boolean values true or false.
-perator
#escription
Z
(reater than
ZS
(reater than or equal to
[
Less than
[S
Less than or equal to
SS
Fqual to
DS
Jot equal to
Logical -perators -
Logical operators have "oolean operands that yield a "oolean result. -perator 11
22
3
#escription Logical !J4 - ;eturns :rue if all of its boolean operands are :rue, =alse if otherwise. Logical ; - ;eturns :rue if at least one of its "oolean operands are :rue, otherwise =alse Logical J: - ;everses the value of its operand.
Illustration :rue \\ :rue S :rue :rue \\ =alse S =alse =alse \\ =alse S =alse :rue]]:rue S :rue :rue]]=alse S :rue =alse]]=alse S =alse D:rue S =alse D=alse S :rue
Conditional -perators -
:he conditional operator ?UB is a ternary operator. :his means that it takes three arguments that together form a conditional expression. :he structure of an expression using a conditional operator is, exp@Wexp?Kexp>
-
2herein exp@ is a "oolean expression whose result must either be :rue or =alse
-
0f exp@ is true, exp? is the value returned. 0f it is false, then exp> is returned. Fxample5 public class ;onditional2perator / public static void main'String args( / String status 1 ## int grade 1 GB
status 1 'gradeX15(W#Hassed#K#Oailed# System.out.println'status( 0 0
)rints as Oailed