Anda di halaman 1dari 16

Introduction to Java Programming Computer Programming computer science discipline dealing with the creation and maintenance of computer

programs is just one activity in the more complex field of software engineering

Programming Language a standardized communication technique for expressing instructions to a computer. Like human languages, each language has its own syntax and grammar enables a programmer to precisely specify what data a computer will act upon, how these data will be stored transmitted, and precisely what actions to take under various circumstances set of rules, symbols, and special words used to construct programs or instructions that are translated into machine language that can be understood by computers

Java Background ! little "it #istory developed in early $%%&s by 'ames (osling et. al. as the programming language component of the (reen )roject at *un +icrosystems originally named ,ak and intended for programming networked -smart. consumer electronics launched in $%%/ as a -programming language for the 0nternet.1 quickly gained popularity with the success of the 2orld 2ide 2eb currently used by around / million software developers and powers more than 3./ billion devices worldwide, from computers to mobile phones

4esign (oals simple5 derived from 6 677, but easier to learn

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 robust5 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 compiler5 :ransform 'ava programs into 'ava byte code Java interpreter5 ;ead programs written in 'ava byte code and execute them Java virtual machine5 ;untime system that provides various services to running programs Java programming environment5 *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... pu lic class #ello2orld > the main method defines the #starting point# of the execution of this program... pu lic 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 ThisIsAnExampleOfClassName thisIsAnExampleOfMethodName 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 #e ugging +ost of the time, after a programmer has written the program, the program isnKt $&&L 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 de ugging. :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

misspelling a certain command, for example, is a compiletime error. o ;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 byte, short, int, long two of them represent floating point numbers5 o 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 37n3

Fxample declarations5
char top8rade 1 393,

char terminator 1 3,3, 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 <nicode character set uses sixteen bits per character, allowing for N/,/ON unique characters 0t is an international character set, containing symbols and characters from many world languages :he 9S;<< character set is older and smaller than <nicode, but is still quite popular ?in 6 programsB :he !*600 characters are a subset of the <nicode character set, including5

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

(aria les

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,

(aria le 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 for example, J<+G*:!:F* means more than the literal /& o second, they facilitate program maintenance 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 o 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 <nformation provided to the method 'Harameters(

&"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 !tring Concatenation -

"hreeI "woI

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 AJ concatenatedK + E ?A E AJ(,

prints as5 ?A and AJ concatenatedK ?AAJ 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 AJ addedK + E '?A E AJ((,

"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 blue.B1 )rints as5


Moses are red, Violets are blue,

:o put a specified <nicode character into a string using its code value, use the escape sequence5 Vuhhhh where hhhh are the hexadecimal digits for the <nicode value Fxample5 6reate a string with a temperature value and the degree symbol5
double temp 1 BD.G, System.out.println'*Nody temperature is + E temp E * 7u==b=O.+(,

)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 7 -peration !ddition 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.&% 3 WS& 3.% 3 S $.T/ 3.$ 3.% S &.W3T$OW%O$& 3LWS3 3.% L 3 S &.R%%%%%%%%% 3.% L 3.$ S &.W%%%%%%%R

*ubtraction

+ultiplication

4ivision

+odulus ?;emainderB

Jote5 2hen evaluating the mod operator with negative integer operands, the answer always takes the sign of the dividend. 0llustration5 ->A Q J 1 -A >A Q-J 1 A ->A Q-J 1 -A

>A Q J 1 A :erms5
2HRM9STS U may refer to the numbers or alphabetical symbols that we use in our expression ' formula ( :S9MV 2HRM9"2MS U operators that only have one operand. 'exampleK -J( N<S9MV 2HRM9"2MS 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 ZS [ [S SS DS

(reater than (reater than or equal to Less than Less than or equal to Fqual to Jot equal to

Logical -perators Logical operators have "oolean operands that yield a "oolean result.
-perator 11 #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

22

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 'gradeX15J(W#Hassed#K#Oailed#, System.out.println'status(, 0 0

)rints as
Oailed

Anda mungkin juga menyukai