Fundamentals of the Java Programming Language
TABLE OF CONTENTS
JDK INSTALLATION
OVERVIEW
INSTALLATION INSTRUCTIONS
CONFIGURATION
MODULE 1 - EXPLAINING JAVA TECHNOLOGY
Brief History of Java
What is Java?
List the three Java technology product groups
Java Development Kit
How does JVM work?
Features of Java
MODULE 2 - ANALYZING JAVA TECHNOLOGY PROGRAM
Java Source File Structure
Java Keywords
Identifiers
Literals
MODULE 3 - DECLARING, INITIALIZING, AND USING VARIABLES
Define the syntax for a variable
Java programming language data types
Primitive Data Type
Reference Data Type
Declare, initialize, and use variables
Primitive Type Declaration
Reference Data Type
Scope of the Variables
MODULE 4 OPERATORS AND ASSIGNMENTS
Arithmetic operators
Object operators
Integer Operators
Floating Point Operators
Boolean Operators
Conditional Boolean Operators
Assignment operators
String operator
Evaluation order Operator Precedence
Expressions
Casting
MODULE 5 FLOW CONTROLS AND ARRAYS
Selection
Iteration
Jump
Array Declaration, Construction, Initialization, Manipulation
By SRK
Page 1 of 35
Fundamentals of the Java Programming Language
Programs to install during Module 1:
1. Java Development Kit (JDK)
JDK Installation
Overview
JDK includes tools useful for developing and testing programs written in the Java programming
language and running on the Java platform.
Installation Instructions
1. In your local drive go to D:\WebServices\CoreJava folder.
2. Launch the installer([Link]). A series of installation windows will be
displayed and you have the option to customize your installation. Customizing your installation
includes choosing the directory where you want to install.
3. Change the default installation directory for the JDK to D:\WebServices\CoreJava \ jdk1.7.0_60
\. Accept the default components.
4. Change the default directory for the JRE to the directory D:\WebServices\CoreJava\
jdk1.7.0_60 \. Accept the default components.
Configuration
After successful installation, add the additional environment variable JAVA_HOME on the list of
system variables. Make sure to indicate the path directory where JDK was installed.
1.
Right-click My Computer from the desktop and select Properties.
By SRK
Page 2 of 35
Fundamentals of the Java Programming Language
1. Select the Advanced tab and click the Environment Variables button.
3.
Click the New button on System Variables. Specify variable name (JAVA_HOME) and variable
value which is the directory of your JDK (Ex. D:\WebServices\CoreJava \ jdk1.7.0_60).
By SRK
Page 3 of 35
Fundamentals of the Java Programming Language
Brief History of Java
In 1990, Sun Microsystems began an internal project known as the Green Project to work on a
new technology.
In 1992, the Green Project was spun off and its interest directed toward building highly
interactive devices for the cable TV industry. This failed to materialize.
In 1994, the focus of the original team was re-targeted, this time to the use of Internet technology.
A small web browser called HotJava was written. Oak was renamed to Java after learning that
Oak had already been trademarked.
In 1995, Java was first publicly released.
James Gosling is generally credited as the inventor of the Java programming language
He was the first designer of Java and implemented its original compiler and virtual machine
JDK(Java Development Kit) 1.0, code named Oak and released on January 23, 1996.
JDK 1.1, released on February 19, 1997.
JDK 1.2, code named Playground and released on December 8, 1998.
JDK 1.3, code named Kestrel and released on May 8, 2000.
JDK 1.4, code named Merlin and released on February 6, 2002 (first release under JCP).
JDK 1.5, code named Tiger and released on September 30, 2004.
JDK 1.6, code named Mustang and released on December 11, 2006.
JDK 1.7, code named Dolphin and released on July 28, 2011, the most widely used version.
JDK 1.8, was released on 18 March 2014. The code name culture is dropped with Java 8 and so
no official code name going forward from Java 8., the latest version.
What is Java?
A multi-platform, network-centric, object-oriented programming language
Multi-platform
It can run on almost any computer platform
Network-centric
Designed with network in mind the network is the computer
Designed for building applications for the Internet
Object-oriented
It incorporates object-oriented programming model
List the three Java technology product groups
A Java Platform is the set of APIs, class libraries, and other programs used in developing Java programs
for specific applications
There are 3 Java Platform Editions
By SRK
Page 4 of 35
Fundamentals of the Java Programming Language
1. Java 2 Platform, Standard Edition (J2SE)
Core Java Platform targeting applications running on workstations
2. Java 2 Platform, Enterprise Edition (J2EE)
Component-based approach to developing distributed, multi-tier enterprise applications
3. Java 2 Platform, Micro Edition (J2ME)
Targeted at small, stand-alone or connectable consumer and embedded devices
Java Development Kit (JDK)
Java Development Kit (JDK)
Is a set of Java tools for developing Java programs
Consists of Java API, Java Compiler, and JVM
Java Application Programming Interface (API)
Is prewritten code, organized into packages of similar topics
Java Virtual Machine (JVM)
Is an execution engine that runs compiled Java byte code
JDK
JRE
[Link]
Java API
Java Virtual Machine
Hardware - Based Platform
How does JVM work?
A Java program is written
By SRK
Page 5 of 35
Fundamentals of the Java Programming Language
The program is compiled
A class file is produced containing bytecodes
The bytecodes are interpreted by the JVM
The JVM translates bytecodes into native machine code
Source Code
public class HelloWorld {
public static void main(String args[ ]) {
[Link](Hello World!);
}
}
Compiler
Class File
Bytecodes
Java Virtual Machine
Native Machine Code
Features of Java
Write Once, Run Anywhere
Java is portable and platform independent
Network-centric
Can work with resources across a network and multi-tier architectures
Object-oriented
A Java program models a set of objects interacting with each other
Robust
By SRK
Page 6 of 35
Fundamentals of the Java Programming Language
Strong type checking
Exception handling mechanism
Automatic memory management
Multithreaded
A Java application can run several different processes called threads simultaneously
Security
Can download remote code over a network and run it in a secure environment
Security levels and restrictions are highly configurable
Java Source File Structure
Declaration order
1. Package declaration
Used to organize a collection of
related classes.
2. Import statement
Used to reference classes and
declared in other packages.
3. Class declaration
A Java source file can have
several classes but only one
public class is allowed.
Comments
1. Single Line Comment
// insert comments here
2. Block Comment
/*
* insert comments here
*/
3. Documentation Comment
/**
* insert documentation
*/
White spaces
Tabs
and spaces are ignored by
By
SRK
the compiler. Used to improve
readability of code.
/*
* Created on Dec 10, 2014
* First Java Program
*/
package [Link];
import [Link].*;
/**
* @author skummitha
*/
public class JavaMain
{
public static void main(String[]
args) {
// print a message
[Link]("Welcome to
Java!");
}
}
class Extra {
/*
* class body
*/
}
Page 7 of 35
Fundamentals of the Java Programming Language
Class
Every java program
includes at least one class
definition. The class is the
fundamental component of all
Java programs.
A class definition contains
all the variables and methods
that make the program work.
This is contained in the class
body indicated by the opening
and closing braces.
Braces
Braces are used
for grouping statements or
block of codes.
The left brace ( { )
indicates the beginning of a
class body, which contains any
variables and methods the
class needs.
The left brace also
indicates the beginning of a
method body.
For every left
brace that opens a class or
method you need a
corresponding right brace ( } )
to close the class or method.
By SRK
/*
* Created on Dec 10, 2014
* First Java Program
*/
package [Link];
import [Link].*;
/**
* @author Skummitha
*/
public class JavaMain
{
public static void main(String[]
args) {
// print a message
[Link]("Welcome to
Java!");
}
}
class Extra {
/*
* class body
*/
}
Page 8 of 35
Fundamentals of the Java Programming Language
Class
Every java program
includes at least one class
definition. The class is the
fundamental component of all
Java programs.
A class definition contains
all the variables and methods
that make the program work.
This is contained in the class
body indicated by the opening
and closing braces.
Braces
Braces are used
for grouping statements or
block of codes.
The left brace ( { )
indicates the beginning of a
class body, which contains any
variables and methods the
class needs.
The left brace also
indicates the beginning of a
method body.
For every left
brace that opens a class or
method you need a
corresponding right brace ( } )
to close the class or method.
/*
* Created on Dec 10, 2014
* First Java Program
*/
package [Link];
import [Link].*;
/**
* @author Skummitha
*/
public class JavaMain
{
public static void main(String[]
args) {
// print a message
[Link]("Welcome to
Java!");
}
}
class Extra {
/*
* class body
*/
}
main() method
String args[]
This line begins the main()
method.
By
SRK This is the line at which
the program will begin executing.
Declares a parameter named args,
which is an array of String.
It 9 of 35
Page
represents command-line
arguments
Fundamentals of the Java Programming Language
Terminating Character
Semicolon (;) is the terminating
character for any java statement.
Java Key Words
abstract
default
if
package
synchronized
assert
do
implements
private
this
boolean
double
import
protected
throw
break
else
instanceof
public
throws
byte
extends
int
return
transient
case
false
interface
short
true
catch
final
long
static
try
char
finally
native
strictfp
void
class
float
new
super
volatile
continue
for
null
switch
while
const
By SRK
35
goto
Page 10 of
Fundamentals of the Java Programming Language
Identifiers
An identifier is the name given by a
programmer to a variable, statement label,
method, class, and interface
An identifier must begin with a letter, $ or _
Subsequent characters must be letters,
numbers, $ or _
Incorrect
3strikes
Write&Print
switch
An identifier must not be a Java keyword
Correct
strikes3
Write_Print
Switch
printMe is not the same as PrintMe
Identifiers are case-sensitive
Literals
A literal is a representation of a value of a particular type
Type
By SRK
35
Examples & Values
boolean
true / false
character
a \uFFFF' \777
Integer
123 123L O123 Ox123
floating-point
123.5 123.5D 123.5F 123.5e+6
object
escape sequences
test null
\n \t \b \f \r \ \ \\
Page 11 of
Fundamentals of the Java Programming Language
MODULE 3 - DECLARING, INITIALIZING, AND USING VARIABLES
Variables and Data types
A variable is a named storage location used to represent data that can be changed while the
program is running
A data type determines the values that a variable can contain and the operations that can be
performed on it
Categories of data types:
1. Primitive data types
2. Reference data types
Primitive Data types
Primitive data types represent atomic values and are built-in to Java
Java has 8 primitive data types
Type
boolean
Bits
Lowest Value
Highest Value
(n/a) false
true
char
16
'\u0000' [0]
'\uffff' [216-1]
byte
-128 [-27]
+127 [27-1]
short
16
-32,768 [-215]
+32,767 [215-1]
int
32
-2,147,483,648 [-231]
+2,147,483,647 [231-1]
long
64
-9,223,372,036,854,775,808 [-263] +9,223,372,036,854,775,807 [263-1]
float
32
1.40129846432481707e-45
3.40282346638528860e+38
double
64
4.94065645841246544e-324
1.79769313486231570e+308
Reference Data types
Reference data types represent objects
A reference serves as a handle to the object, it is a way to get to the object
Java has 2 reference data types
By SRK
35
1. Class
2. Interface
Page 12 of
Fundamentals of the Java Programming Language
Variable Declaration and Initialization
Declaring a variable with primitive data type
int
age =
21;
Declaring a variable with reference data type
Date
String
now = new Date();
name = Jason;
Primitive Type Declaration
MEMORY
Declaration
Allot space to memory
int
age;
age
type
Identifier name
17
Initialization / Assignment
age
Identifier name
17;
Value
Stack
By SRK
35
Page 13 of
Fundamentals of the Java Programming Language
Reference Type Declaration
Allot space to memory
Car
type
myCar;
myCar
memory address location
Identifier
name
myCar
reference
The heap
= new Car(Bubble Bee);
Values
Bumble Bee
Identifier
name
Car object
Scope of the variable
public class HelloWorld
{
//accessible throughout the class
String name;
Member Variables
public void otherMethod()
{
float salary = 15000.00f;
//cant access age variable from here
}
Declared inside the class but outside of
all methods. Accessible by all methods
of the class.
Local Variables
public static void main(String args[ ])
{
//cant access salary variable from here
int age=17;
//cant access ctr variable from here
for (int ctr=0; ctr<5; ctr++) {
//age variable accessible here
}
Available only within the method whereThe heap
they were declared. Method
parameters have local scope.
}
}
By SRK
35
Page 14 of
Fundamentals of the Java Programming Language
MODULE 4 OPERATORS AND ASSIGNMENTS
Operators and Assignments
Arithmetic operators
Object operators
Integer Operators
Floating Point Operators
Unary operators
Binary operators
Relational operators
Boolean Operators
Unary operators
Binary operators
Bitwise operators
Shift operators
Relational operators
Logical operator
Conditional Boolean Operators
Conditional operator
Assignment operators
String operator
Evaluation order Operator Precedence
Expressions
Primitive Casting
Arithmetic Operators
Arithmetic operators are used for basic mathematical operations
+ Add
By SRK
35
Subtract
Multiply
Divide
% Modulo, remainder
Page 15 of
Fundamentals of the Java Programming Language
Sample code:
Sample Output :
Object Operators
Testing Object Equality
It is a source of great confusion to novice programmers that Java has two ways of thinking about the
equality of objects. When used with object references, the == operator returns true only if both
references are to the same object. This is illustrated in the following code fragment in which we create
and compare some Integer object references:
1. Integer x1 = new Integer( 5 );
2. Integer x2 = x1;
3. Integer x3 = new Integer( 5 );
4. if( x1 == x2 ) [Link]("x1 eq x2" );
5. if( x2 == x3 ) [Link]("x2 eq x3" );
Executing this code will print only "x1 eq x2" because both variables refer to the same object. To test for
equality of content, you have to use a method that can compare the content of the objects
The equals Method
In the Java standard library classes, the method that compares content is always named equals and
takes an Object reference as input. For example, the equals() method of the Integer class works like this:
1. public boolean equals(Object obj)
2. {
3.
if( obj == null ) return false;
4.
if( ! ( obj instanceof Integer ) ) return false;
5.
return [Link] == ((Integer) obj).intValue();
6. }
Note that the equals() method does not even look at the value of the other object until it has been
determined that the other object reference is not null and that it refers to an Integer object.
The equals() method in the Object class returns true only if
this == obj
Therefore, in the absence of an overriding equals method, the == operator and equals methods inherited
from Object are equivalent.
By SRK
35
Page 16 of
Fundamentals of the Java Programming Language
Remember that the equals() method compares content only if the two objects are of the identical type.
For example, an equals test by an Integer object on a Long object always returns false, regardless of the
numeric values. Also note that the signature of the equals() method expects an Object reference as
input. The compiler reports an error if you try to call equals with a primitive value.
Integer Operators
Unary Operators
Unary operators use only one operand
++ Increment by 1, can be prefix or postfix
--
Decrement by 1, can be prefix or postfix
Positive sign
Negative sign
class IncDec{
public static void main(String args[]){
int x = 10, y = 20;
[Link] ("\n Out put...");
[Link]("
x = " + x );
[Link]("
y = " + y );
[Link]("
++x = " + (++x) );
[Link]("
y++ = " + (y++) );
[Link]("
x = " + x );
[Link]("
y = " + y );
[Link]("
--x = " + (--x) );
[Link]("
y-- = " + (y--) );
[Link]("
x = " + x );
[Link]("
y = " + y );
// Negation Operation
[Link]("\n\n Negation Operation ");
[Link]("
x = " + x );
y = -x;
[Link]("
-x = " + y );
// Bitwise Complement Operation
[Link]("\n\n Bitwise Complement Operation ");
[Link]("
x = " + x );
y = ~x;
[Link]("
~x = " + y );
}
}
Binary Bitwise / Shift Integer Operators
Binary integer operators act on a pair of integers
By SRK
35
C:\>javac [Link]
C:\>java IncDec
Out put...
x = 10
y = 20
++x = 11
y++ = 20
x = 11
y = 21
--x = 10
y-- = 21
x = 10
y = 20
Negation Operation
x = 10
-x = -10
Bitwise Complement Operation
x = 10
~x = -11
Description
Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise Left shift
Bitwise Right shift
Zero-fill right shift
Operator
&
|
^ Page 17 of
<<
>>
>>>
Fundamentals of the Java Programming Language
class BasicBinOper{
public static void main(String args[]){
int a = 15, b =16;
int x=12, y = -13;
[Link] ("\n Out put...");
// Bitwise Operators
[Link](" \n\n Bitwise Operation ");
[Link]("
a&b = " + (a&b) );
[Link]("
a|b = " + (a|b) );
[Link]("
a^b = " + (a^b) );
C:\>javac [Link]
C:\>java BasicBinOper
Out put...
Bitwise Operation
a&b = 0
a|b = 31
a^b = 31
Out put: applying shift operators...
[Link]("\n Out put: applying shift operators..."); -----------------------------------[Link]("--------------------------------------------"); ...Left Shift Operator...
x<<2 = 48
[Link]("...Left Shift Operator...");
//
//
//
Left Shift Operator
x << 2 : Left shifts individual bits two times. The vacuum
created at the right is filled with zeros
[Link]("x<<2 = " + (x<<2) );
[Link]("y<<2 = " + (y<<2) );
[Link]("--------------------------------------------");
[Link]("...Right Shift Operator...");
//
//
//
//
y<<2 = -52
-----------------------------------...Right Shift Operator...
x>>2 = 3
y>>2 = -4
-----------------------------------...Zero-fill Right Shift Operator...
x>>>2 = 3
y>>>2 = 1073741820
Right Shift Operator
x >> 2 : Right shifts individual bits two times. The vacuum
created at the left is filled with zeros. For negative integer,
the vacuum created at the left side is filled with 1.
[Link]("x>>2 = " + (x>>2) );
[Link]("y>>2 = " + (y>>2) );
[Link]("--------------------------------------------");
[Link]("...Zero-fill Right Shift Operator...");
//
//
//
Zero-fill Right Shift Operator
x >>> 2 : Right shifts individual bits two times. The
vacuum created at the left is filled with zeros.
[Link]("x>>>2 = " + (x>>>2) );
[Link]("y>>>2 = " + (y>>>2) );
}
}
Relational Integer Operator
By SRK
35
Description
Operator
Less than
<
Greater than
>
Page
18
of
Less than or equal to
<=
Greater than or equal to
>=
Equal to
==
Not equal to
!=
Fundamentals of the Java Programming Language
Relational Interger operators operate on integers. These operations perform comparison between
integers. The result of this operation is a boolean value true or false. Relational operators are used to
compare values. Boolean values cannot be compared with non-boolean values. Only object references
are checked for equality, and not their states. Objects cannot be compared with null. null is not the same
as .
class RelOperators
{
public static void main(String args[])
{
int x=5, y = 8;
[Link]("\n Output : Relational operators...");
[Link]("--------------------------------------------");
[Link]("x value is = " + x );
[Link]("y value is = " + y );
[Link]("--------------------------------------------");
[Link]("");
[Link]("x Less than y : ( x < y ) : " + (x<y));
[Link]("");
[Link]("x Greater than y : ( x > y ) : " + (x>y));
[Link]("");
[Link]("--------------------------------------------");
[Link]("");
[Link]("x less than/equal to y : " + (x<=y));
[Link]("");
[Link]("x greater than/equal to y : " + (x>=y));
[Link]("");
[Link]("--------------------------------------------");
[Link]("");
[Link]("x Equal to y - ( x == y) : " + (x == y));
[Link]("");
[Link]("x Not Equal to y - ( x != y):"+(x != y));
}
}
By SRK
35
C:\>javac [Link]
C:\>java RelOperators
Output : Relational operators...
-------------------------------------x value is = 5
y value is = 8
-------------------------------------x Less than y : ( x < y ) : true
x Greater than y : ( x > y ) : false
-------------------------------------x less than/equal to y : true
x greater than/equal to y : false
-------------------------------------x Equal to y - ( x == y) : false
x Not Equal to y - ( x != y):true
Page 19 of
Fundamentals of the Java Programming Language
Floating Point Operators
As in the case of integers, three types of operations can be performed on floating point numbers.
Unary
Binary
Relational
Unary Floating Point Operators
Unary floating point operators act on a single floating point number.
The increment/decrement operator increases/decreases the value of a
floating point variable by 1.0. Rest is similar as that applied to unary
integer operator.
By SRK
35
Description
Increment
Decrement
Negation
Operator
++
-Page 20 of
Fundamentals of the Java Programming Language
Binary Floating Point Operators
Binary floating point operators act on a pair of floating point numbers
Description
Addition
Subtraction
Multiplication
Division
Modulus
Operator
+
*
/
%
Relational Floating Point Operators
Floating point relational operators are exactly the same as integer relational operators.
Boolean Operators
Boolean operators act on boolean type operands and return a boolean value.
Logical operators are used to compare boolean expressions
! inverts a boolean value
Operator
Description
&, | evaluate both operands
&&, || evaluate operands conditionally
!
NOT
By SRK
35
&
AND
OR
XOR
&&
Short-circuit AND
||
Short-circuit OR
Page 21 of
Fundamentals of the Java Programming Language
Similar to the Boolean operators, but with an added ability to short-circuit part of the process,
using a couple of mathematical rules:
o
If the left operand of an && operation is false, the result is automatically false, and the right
operand is not evaluated
boolean a = false;
If the left operand of an || operation is true, the result is automatically true, and the right
operand is not evaluated
boolean b = true;
Boolean Complement ( ! ):
o
The NOT function inverts the value of boolean
boolean c = false;
Conditional Boolean Operators
The ternary operator ( ? : ) provides a handy way to code simple if-else() statements in a single
expression, it is also known as the conditional operator.
If condition is true, then exp1 is returned as the result of operation.
If condition is false, then exp2 is returned as the result of operation.
Can be nested to accommodate chain of conditions.
By SRK
35
Page 22 of
Fundamentals of the Java Programming Language
Assignment Operators
Assignment operators are used to set the value of a variable
String Operators
Assign
+=
Add and assign
-=
Subtract and assign
*=
Multiply and assign
/=
Divide and assign
%= Modulo and assign
&= AND and assign
String operator (+) is used to concatenate operands
If one operand is String, the other operands are converted to
String
|=
OR and assign
^=
XOR and assign
Evaluation Order Operator Precedence levels
[Link]
Operator Name
1
1
.
Unary
2
++
3
*
Arithmetic
4
+
5
Shift
>>
6
>
Comparison Operator
7
instanceof
By SRK
35
2
()
-/
>>>
>=
==
3
[]
~
%
<<
<
!=
<=
Page 23 of
Fundamentals of the Java Programming Language
8
9
10
11
12
13
14
Bitwise
Short Circuit
Conditional or Iterator
Assignment
&
^
|
&&
||
?:
=
+=
-=
*=
/=
Expressions
You already know about variables, literals and operators. To do something meaningful and useful we
should be able to generate expressions using these. Operators enable you to perform computation or
evaluation on data objects like variables and literals. Operators applied to variables and literals form
expressions.
Ex :
int x, y;
X = 10;
Y = 5 + 2 * x;
In this expression x and y are variables, 5 and 2 are literals and =, + and * are operators.
Type Conversion and Casting
The process of converting one datatype to another is called type-casting. If two types are compatible,
then Java will perform the conversion automatically.
Ex: It is always possible to assign an int value to a long variable
However, not all types are compatible, and thus, not all type conversions are implicitly allowed.
Fortunately, it is possible to obtain a conversion between incompatible types. To do so, you must use a
cast, which performs an explicit conversion between incompatible types.
Javas Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will take
place if the following two conditions are met
The two types are compatible
The destination type is larger than the source type
When these two conditions are met, a widening conversion takes place. Therefore, the numeric types,
including integer and floating-point types, are compatible with each other. However, the numeric types
are not compatible with char or boolean.
Java performs automatic type conversions when storing a literal integer constant into variables of type
byte, short, or long.
Casting Incompatible Types
By SRK
35
Page 24 of
Fundamentals of the Java Programming Language
To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit
type conversion.
Syntax :
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
For example, what if you want to assign an int value to a byte variable? This conversion will not be
performed automatically, because a byte is smaller than an int. This kind of conversion is sometimes
called a narrowing conversion, since you are explicitly making the value narrower so that it will fit into the
target-type.
Ex :
int a;
byte b;
.
b = (byte) a;
A different type of conversion will occur when a floating point value is assigned to an integer type :
truncation. As you know, integers do not have fractional components. Thus, when a floating point value is
assigned to an integer type variable, the fractional component is lost.
Ex :
if the value 7.23 is assigned to an integer, the resulting value will simply be 7. the 0.23 will have
been truncated.
Ex :
The return type of function f2() may be a character. The return value of f2() has to go as an
argument to another function f1(), which accepts only the integer argument. The solution here is
to type cast the return value of f2() to integer and then use it as argument for function f1().
f1( (int) f2() );
Casting is converting from one data type to another
Implicit casting is an implied casting operations
Explicit casting is a required casting operations
Primitive casting is converting a primitive data type to another
o Widening conversion is casting a narrower data type to a broader data type
o Narrowing conversion is casting a broader data type to a narrower data type
Reference casting is converting a reference data type to another
o Upcasting is conversion up the inheritance hierarchy
o Downcasting is conversion down the inheritance hierarchy
Casting between primitive and reference type is not allowed
In Java, casting is implemented using () operator
By SRK
35
Page 25 of
Fundamentals of the Java Programming Language
Primitive Casting Rule
Operation
arithmetic
relational
shift
bitwise
assignment
parameter passing
logical
ternary ?:
Boolean
(all others)
Conversion Type
implicit widening conversion
implicit widening conversion
implicit widening conversion
implicit widening conversion
implicit widening conversion (if target is broader )
implicit widening conversion (if formal parameter is broader)
none
none
none
explicit casting (narrowing or widening conversion)
Implementing Primitive Casting
By SRK
35
Page 26 of
Fundamentals of the Java Programming Language
Flow Controls
A programming language uses control statements to cause the flow of execution to advance and branch
based on changes to the state of a program.
Javas program control statements can be put into the following categories
Selection
Iteration
jump
Statement label
Selection -
statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
By SRK
35
if() statement
o Nested ifs
o The if-else-if Ladder
Page 27 of
Fundamentals of the Java Programming Language
Iteration -
switch() statement
o Nested switch statements
statements enable program execution to repeat one or more statements
Jump -
for() statement
while() statement
do-while() statement
statements allow your program to execute in a nonlinear fashion.
break statement
continue statement
return statement
Types of Flow Controls
Sequential
Perform statements in
the order they are written
Selection
Perform statements based on condition
Iteration
Perform statements repeatedly
based on condition
if-else() Statement
if-else() performs statements based on two conditions
Condition should result to a boolean expression
If condition is true, the statements following if are executed
If condition is false, the statements following else are executed
Can be nested to allow more conditions
By SRK
35
Page 28 of
Fundamentals of the Java Programming Language
switch() Statement
switch() performs statements based on multiple conditions
exp can only be char byte short int, val should be a unique constant of exp
case statements falls through the next case unless a break is encountered
default is executed if none of the other cases match the exp
for() Loop
for() performs statements repeatedly based on a condition
Init is a list of either declarations or expressions, evaluated first and only once
Condition is evaluated before each iteration
Exp is a list of expressions, evaluated after each iteration
All entries inside () are optional, for(;;) is an infinite loop
By SRK
35
Page 29 of
Fundamentals of the Java Programming Language
while() Loop
while() performs statements repeatedly while condition remains true
do-while() Loop
do-while() performs statements repeatedly (at least once) while condition remains true
By SRK
35
Page 30 of
Fundamentals of the Java Programming Language
break Statement
break exits loops and switch() statements
continue Statement
continue is used inside loops to start a new iteration
By SRK
35
Page 31 of
Fundamentals of the Java Programming Language
return Statement
return branching statement is used to exit from the current method.
Two forms:
return <value>;
return;
Statement label
By SRK
35
Page 32 of
Fundamentals of the Java Programming Language
A label is an identifier placed before a statement, it ends with :
break labelName is used to exit any labelled statement
continue labelName is used inside loops to start a new iteration of the labelled loop
Arrays
What is an Array?
By SRK
35
Page 33 of
Fundamentals of the Java Programming Language
Creating an Array
Creating and Array declaration
Creating an Array construction
Creating and Array Initialization
By SRK
35
Page 34 of
Fundamentals of the Java Programming Language
Manupliating Arrays
By SRK
35
Page 35 of