Anda di halaman 1dari 47

Java Basics

History of C++
First there was C. C initially became widely known as the development language of UNIX OS. C++ evolved as an extension to C. It mainly provides the capabilities of Object-Oriented Programming to C world. C++ is a hybrid language. Both C-like style and object-oriented style can be developed using it.

History of Java

Java first was developed in 1991 by James Gosling at Sun Microsystems to be used with interactive TV technology which had failed to find a market. When The World-Wide Web became popular in 1995 , Java came to life again. Java is now considered as the native language of the Internet. Java is a C/C++ based language. Java is a Full object-oriented language

So, what is Java?


According to Sun's definition: Java is a "simple, object-oriented, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language."

multitasking infers the mechanism to run many processes simultaneously with user interaction.

in contrast,multithreading is a mechanism of running various threads under single process within its own space.

Java Environment
Draft .java file .class File Byte code on RAM Verified Byte code Editor Compiler Class Loader Byte code Verifier .java file .class File Byte code on RAM Verified Byte code

Interpreter

Executed machine code

Compiling/Running Java Programs

To compile your program, use command: c:\> javac MyProgramName.java

To run your program, use command: c:\> java MyProgramName

Program skeleton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

//the skeleton of a java application package packagename; import packagename.ClassName; public class ProgramName { // Define program variables here. . . . // Define program methods here. . . . //Define the main method here.

Notes
Java

public static main(String args[])


{ // Main method body }//end of the main method.

is a case sensitive language Braces must occur on matching pairs Coding styles should be followed.

} //End of class HelloWorld

Comment Styles

Comments are used to clear the logic of the code and to increase the readability if it. Comments are ignored by the compiler. Java uses three types of comments:
Single-line comment(//). Example: //single-line comment here Multiple-line comment(/**/). Example: /* line 1 here line 2 here */ Documentation comment(/***/). It is multiple-line and used with javadoc utility to create application documentation.

Playing With Strings

A string is a group of characters We use class String to define a string. Example: String name; Strings are bounded by double quotations. Example: String name = Jane; We can concatenate two or more strings using the operator + Strings can contain escape characters like \n, \t, \\, \.

Variables Definition

Variables are used to represent the data that a program deals with As the name might imply, the data that a variable holds can change. We have to define a variable before using it Here is an example of defining a variable: int numberOfChar; String nameOfPerson;

Identifiers
An identifier may contain combinations of the letters of the alphabet (both uppercase A-Z and lowercase a-z), an underscore character _, a dollar sign $, and decimal digits 0-9. Assignment Statement: identifier = literal; identifier = identifier; identifier = expression;

What's a Java Literal?


A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values. Example of literals: Integer literals: 33 0 -9 Floating-point literals: .3 0.3 3.14 Character literals: '(' 'R 'r '{ Boolean literals:(predefined values) true false String literals: "language" "0.2" "r" ""

the following statements are legal. tax = 135.86; where 135.86 is a numeric literal tax = incomeTax; where incomeTax is another identifier tax = 0.175*cost; where 0.175*cost is an expression the following statements are illegal. 135.86 = tax; this implies the syntax literal =identifier (wrong) tax = incomeTax statement delimiter ; missing (wrong) 0.175*cost = tax; this implies expression = identifier (wrong)

Variable Declaration: data-type identifier; data-type identifier-list;


int parkingTime; float balance; float costOfGas;

int weightLimit, parkingTime; float balance, costOfGas, valueOfShares;

Variable Initialization : data-type identifier = literal;


char parkingSymbol= 'P'; int weightLimit = 10; float balance = 1225.11f; Constant Declaration: final data-type identifier = literal; final float SALES_TAX = 0.05f; final double PI = 3.14159;

Casting
SYNTAX Cast operation: (data-type) expression; float money = 158.05; int looseChange = 275; money = (float) looseChange;

Primitives Data types


Type boolean char byte short int long float double Size in bits 8 16 8 16 32 64 32 64 Values
true or false \u0000 - \uFFFF -128 - 127 -32,768 32,767 -2,147,483,648 - +2,147,483,647

-9,223,372,036,854,775,808 +9,223,372,036,854,775,807 -3.40292347E+38 - -+3.40292347E+38


-1.79769313486231570E+308 to +1.79769313486231570E+308

Arithmetic Operations
Operation
Addition

Operator

Java Expression

Subtraction
Multiplication

Division
Modulus

+ * / %

a + 8

b - 7
p * 10

c / 9
b % 6

Arithmetic
Unary Operators + unary plus - unary minus Binary Multiplicative Operators * multiplication / division % remainder

Binary Additive Operators + addition - subtraction

Decision making operations


Operation
Equal to Not equal to Greater than Less than

Operator

Java Expression
if (x == 1) if (y != 5) while (x > y) while (x < y)

Greater than or equal


Less than or equal

== != > < >= <=

if (X >= y)
if ( y <= z)

Assignment Operators
Operator = += -= *= /= %= Expression c = 5; a += 10 ; a -= b; c *= 13; a /= b; b %= c ; Equivalent to c = 5 a = a + 10; a = a b; c = c * 13; a = a/b; b = b% c;

Increment /decrement operation


Operator expression
count++; ++count; --count; count--;

Equivalent to
count = count + 1; count = count - 1;

++ --

Logical Operators

Logical operators allow more complex conditions && (logical AND)


Returns true if both conditions are true

|| (logical OR)
Returns true if either of its conditions are true

! (logical NOT, logical negation)


Reverses the truth/falsity of its condition Unary operator, has one operand

Short circuit evaluation


Evaluate left operand, decide whether to evaluate right operand If left operand of && is false, will not evaluate right operand

Precedence
Operator
( ) ++ * + < == & ^ | && || <= != / > >= -%

Associativity
From left to right From right to left From left to right From left to right From left to right From left to right From left to right From left to right From left to right From left to right From left to right

High

?:
= += -= *= /=

From right to left


From right to left

Low

Java Key words


Keywords are words reserved for Java and cannot be used as identifiers or variable names
Ja va Keyw o rd s
abstract catch do final long private static throw void const boolean char double finally native super throws volatile goto break class else float new switch transient while byte continue extends for null return synchronized true case default false if interface package short this try

implements import

instanceof int

protected public

Keywords that are reserved but not used by Java

If if/else structures

if statement looks like: if (condition) { } Conditions are evaluated to either true or false

If/else statement looks like:

if (condition) { //do something. } else { //do something else. }

The switch Structure

switch statements
Useful to test a variable for different values switch ( value ){ case '1': actions case '2': actions default: actions } break; causes exit from structure

While Structure

while repetition structure


Repeat an action while some condition remains true while loop repeated until condition becomes false Body may be a single or compound statement If the condition is initially false then the body will never be executed Example: int product = 2; while ( product <= 1000 ) product = 2 * product;

The for Structure


for "does it all" : initialization, condition, increment General format


for ( initialization; loopContinuationTest; increment ) statement

If multiple statements needed, enclose in braces Control variable only exists in body of for structure If loopContinuationTest is initially false, body not executed

public void hitungNilaiV(int n) { double nilaiV; for(int P=1000;P<10000;P=P+1000){ for(float r=0;r<1;r=r+0.1f){ for(int k=0;k<n;k++){ nilaiV=hitungSatuV(P,r,k);
System.out.println("Untuk nilai P="+P+", r="+r+", n="+k+" --> V = "+nilaiV);

} } }

Methods

Methods
Modularize a program All variables declared inside methods are local variables
Known only in method defined

Parameters
Communicate information between methods Local variables

Benefits
Divide and conquer
Manageable program development

Software reusability
Existing methods are building blocks for new programs Abstraction - hide internal details (library methods)

Avoids code repetition

Method Definitions

Method definition format


return-value-type method-name( parameter-list ) { declarations and statements }

Method-name: any valid identifier Return-value-type: data type of the result (default int)
void - method returns nothing Can return at most one value

Parameter-list: comma separated list, declares parameters.

Methods and Parameters


SYNTAX Method Signature: modifier(s) return-type methodName(formal-parameterlist); modifier(s)usually indicates the visibility of the method, i.e., where it can be activated from. If you will notice that the modifier defined for those methods is public; this implies that the methods are visible (accessible) anywhere the class is visible. public, private dan protected

return-typethe return type specifies the data type of the value that is returned by the method. This can be a primitive data type or a class. If no data is returned by the method, then the keyword void is used for the return type.
methodNamean identifier that defines the name of the method. formal-parameter-listdeclares the data variables that are passed to and used by the method. If no data is passed to the method, then the parentheses remain empty.

return Statement

When method call encountered


Control transferred from point of invocation to method

Returning control
If nothing returned: return;
Or until reaches right brace

If value returned: return expression;


Returns the value of expression

Example user-defined method:


public int square( int y ) { return y * y }

Calling methods

Three ways
Method name and arguments
Can be used by methods of same class square( 2 );

Dot operator - used with references to objects


g.drawLine( x1, y1, x2, y2 );

Dot operator - used with static methods of classes


Integer.parseInt( myString );

Coercion of arguments

Forces arguments to appropriate type for method


Example:
Math methods only take double Math.sqrt( 4 ) evaluates correctly

Integer promoted to double before passed to Math.sqrt

Promotion rules
Specify how types can be converted without losing data If data will be lost (i.e. double to int), explicit cast must be used If y is a double,
square( (int) y );

Duration of Identifiers

Duration (lifetime) of identifiers


When exists in memory Automatic duration
Local variables in a method

Called automatic or local variables

Exist in block they are declared When block becomes inactive, they are destroyed

Static duration
Created when defined Exist until program ends Does not mean can be referenced/used anywhere

See Scope Rules

Scope Rules (1)

Scope
Where identifier can be referenced Local variable declared in block can only be used in that block

Class scope
Begins at opening brace, ends at closing brace of class Methods and instance variables
Can be accessed by any method in class

Scope Rules (2)

Block scope
Begins at identifier's declaration, ends at terminating brace Local variables and parameters of methods
When nested blocks, need unique identifier names

If local variable has same name as instance variable


Instance variable "hidden"

Method scope
For labels (used with break and continue) Only visible in method it is used

Method Overloading

Method overloading
Methods with same name and different parameters Overloaded methods should perform similar tasks
Method to square ints and method to square doubles
public int square( int x ) { return x * x; } public float square( double x ) { return x * x; }

Program calls method by signature


Signature determined by method name and parameter types Overloaded methods must have different parameters

Return type cannot distinguish method

Arrays

Array
Group of consecutive memory locations

Same name and type Static(Remain same size)

To refer to an element, specify

Array name Position number Format: arrayname[position number] First element at position 0

Every array knows its own length


c.length

Declaring/Allocating Arrays

Declaring arrays
Specify type, use new operator
Allocate number of elements Place brackets after name in declaration

Two steps:
int c[]; //declaration c = new int[ 12 ]; //allocation

One step:
int c[] = new int[ 12 ];

Primitive elements are initialized to zero or false while Non-primitive references are initialized to null

References and Reference Parameters

Passing arguments to methods


Call-by-value: pass copy of argument Call-by-reference: pass original argument
Improves performance, weakens security

In Java, you cannot choose how to pass arguments


Primitive data types passed call-by-value References to objects passed call-by-reference
Original object can be changed in method

Arrays in Java treated as objects


Passed call-by-reference

Passing arrays

Passing Arrays to Functions

Specify array name without brackets


int myArray[ 24 ]; myFunction( myArray );

Arrays passed call-by-reference


Modifies original memory locations

Header for method modifyArray might be void modifyArray( int b[] )

Passing array elements


Passed by call-by-value Pass subscripted name (i.e., myArray[3]) to method

Multiple-Subscripted Arrays

Represent tables
Arranged by m rows and n columns (m by n array) Can have more than two subscripts

Array of arrays
Fixed rows and columns
arrayType arrayName[][] = new arrayType[ numRows ][numColumns ]; int b[][] = new int[ 3 ][ 3 ];

Initializer lists
arrayType arrayName[][] = { {row1 sub-list}, {row2 sub-list}, ... }; int b[][] = { { 1, 2 }, { 3, 4 } };

Anda mungkin juga menyukai