Java
Java Basics
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 Editor .java file
.java file Compiler .class File
.class File Class Loader Byte code on RAM
Byte code on RAM Byte code Verifier Verified Byte code
Executed machine
Verified Byte code Interpreter 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 //the skeleton of a java application
2 package packagename;
3 import packagename.ClassName;
4 public class ProgramName
5 {
Notes
6 // Define program variables here.
Java is a case
7 . . .
8 // Define program methods here. sensitive language
9 . . . Braces must occur
10 //Define the main method here.
11 public static main(String args[])
on matching pairs
12 { Coding styles
13 // Main method body
should be followed.
14 }//end of the main method.
15 } //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 Size in bits Values
boolean 8 true or false
char 16 \u0000 - \uFFFF
byte 8 -128 - 127
short 16 -32,768 – 32,767
int 32 -2,147,483,648 - +2,147,483,647
long 64 -9,223,372,036,854,775,808 -
+9,223,372,036,854,775,807
float 32 -3.40292347E+38 - -+3.40292347E+38
double 64 -1.79769313486231570E+308 to -
+1.79769313486231570E+308
Arithmetic Operations
Operation Operator Java Expression
Addition a + 8
+
Subtraction b - 7
-
Multiplication p * 10
*
Division c / 9
/
Modulus b % 6
%
Arithmetic
Unary Operators
+ unary plus
- unary minus
Binary Multiplicative Operators
* multiplication
/ division
% remainder
Binary Additive Operators
+ addition
- subtraction
Decision making operations
Operation Operator Java Expression
Equal to == if (x == 1) …
Not equal to != if (y != 5) …
Greater than > while (x > y) …
Less than < while (x < y) …
Greater than or equal >= if (X >= y) …
Less than or equal <= if ( y <= z) …
Assignment Operators
Operator Expression Equivalent to
= c = 5; c = 5
+= a += 10 ; a = a + 10;
-= a -= b; a = a –b;
*= c *= 13; c = c * 13;
/= a /= b; a = a/b;
%= b %= c ; b = b% c;
Increment /decrement
operation
Operator expression Equivalent to
++ count++; count = count + 1;
++count;
-- --count; count = count - 1;
count--;
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 High
++ -- 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
?: 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
J ava Keywords
abstract boolean break byte case
catch char class continue default
do double else extends false
final finally float for if
implements import instanceof int interface
long native new null package
private protected public return short
static super switch synchronized this
throw throws transient true try
void volatile while
Keywords that are reserved but not used by Java
const goto
If – if/else structures
if statement looks like: If/else statement looks
if (condition) like:
{ … if (condition)
} {
Conditions are //do something.
}
evaluated to either true
else
or false
{
//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-parameter-
list);
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-type—the 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.
methodName—an identifier that defines the name of the
method.
formal-parameter-list—declares 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 to
Functions
Passing arrays
Passing arrays
– 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 } };