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
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
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
is a case sensitive language Braces must occur on matching pairs Coding styles should be followed.
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.
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;
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)
Casting
SYNTAX Cast operation: (data-type) expression; float money = 158.05; int looseChange = 275; money = (float) looseChange;
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
Operator
Java Expression
if (x == 1) if (y != 5) while (x > y) while (x < y)
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;
Equivalent to
count = count + 1; count = count - 1;
++ --
Logical Operators
|| (logical OR)
Returns true if either of its conditions are true
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
?:
= += -= *= /=
Low
implements import
instanceof int
protected public
If if/else structures
if statement looks like: if (condition) { } Conditions are evaluated to either true or false
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
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)
Method Definitions
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
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
Returning control
If nothing returned: return;
Or until reaches right brace
Calling methods
Three ways
Method name and arguments
Can be used by methods of same class square( 2 );
Coercion of arguments
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
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
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
Block scope
Begins at identifier's declaration, ends at terminating brace Local variables and parameters of methods
When nested blocks, need unique identifier names
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; }
Arrays
Array
Group of consecutive memory locations
Array name Position number Format: arrayname[position number] First element at position 0
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
Passing arrays
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 } };