Professional Documents
Culture Documents
UNIVERSITY
DEPARTMENT OF ICT
Course Code: ICE0034 Course Name: Mobile Programming
UNIT - I : Introduction to Java Features of Java Object Oriented Concepts Lexical Issues
Data Types Variables Arrays Operators Control Statements.
Introduction to Java
Java programming language was originally developed by Sun Microsystems, which was initiated by
James Gosling and released in 1995 as core component of Sun Microsystemss Java platform (Java
1.0 [J2SE]).
As of December 08 the latest release of the Java Standard Edition is 6 (J2SE). With the advancement
of Java and its wide spread popularity, multiple configurations were built to suite various types of
platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.
Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME respectively.
Java is guaranteed to be Write Once, Run Anywhere.
History of Java:
James Gosling initiated the Java language project in June 1991 for use in one of his many set-top
box projects. The language, initially called Oak after an oak tree that stood outside Gosling's office,
also went by the name Green and ended up later renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run
Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open source software under the terms
of the GNU General Public License (GPL).
On 8 May 2007 Sun finished the process, making all of Java's core code free and open-source, aside
from a small portion of code to which Sun did not hold the copyright.
Features of Java
1. Object Oriented : In java everything is an Object. Java can be easily extended since it is
based on the Object model.
2. Platform independent: Unlike many other programming languages including C and C++
when Java is compiled, it is not compiled into platform specific machine, rather into platform
independent byte code. This byte code is distributed over the web and interpreted by virtual
Machine (JVM) on whichever platform it is being run.
3. Simple :Java is designed to be easy to learn. If you understand the basic concept of OOP
java would be easy to master.
4. Secure : With Java.s secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
5. Architectural- neutral :Java compiler generates an architecture-neutral object file format
which makes the compiled code to be executable on many processors, with the presence Java
runtime system.
7. Robust :Java makes an effort to eliminate error prone situations by emphasizing mainly on
compile time error checking and runtime checking.
9. Interpreted :Java byte code is translated on the fly to native machine instructions and is not
stored anywhere. The development process is more rapid and analytical since the linking is an
incremental and light weight process.
10. High Performance: With the use of Just-In-Time compilers Java enables high performance.
11. Distributed :Java is designed for the distributed environment of the internet.
12. Dynamic : Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now and you'll find
many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state
(name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state
(current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal
cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to
begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each
object that you see, ask yourself two questions: "What possible states can this object be in?" and
"What possible behavior can this object perform?". Make sure to write down your observations. As
you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only
two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio
might have additional states (on, off, current volume, current station) and behavior (turn on, turn off,
increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in
turn, will also contain other objects. These real-world observations all translate into the world of
object-oriented programming.
A software object.
Software objects are conceptually similar to real-world objects: they too consist of state and related
behavior. An object stores its state in fields (variables in some programming languages) and exposes
its behavior through methods (functions in some programming languages). Methods operate on an
object's internal state and serve as the primary mechanism for object-to-object communication.
Hiding internal state and requiring all interaction to be performed through an object's methods is
known as data encapsulation a fundamental principle of object-oriented programming.
Consider a bicycle, for example:
Bundling code into individual software objects provides a number of benefits, including:
1. Modularity: The source code for an object can be written and maintained independently of the
source code for other objects. Once created, an object can be easily passed around inside the
system.
2. Information-hiding: By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be
thousands of other bicycles in existence, all of the same make and model. Each bicycle was built
from the same set of blueprints and therefore contains the same components. In object-oriented
terms, we say that your bicycle is an instance of the class of objects known as bicycles.
A class is the blueprint from which individual objects are created.
What is Encapsulation?
Packing up an object's variables within its methods is called encapsulation.
Encapsulating the related variables and methods into neat software bundle seems simple but is a
powerful idea that provides two benefits to the software developer:
Modular programming
The source code for any of the object can be written and maintained independently from those of
the source code written for other objects. Also, an object can be easily used passing around in the
system. For example you can give your bicycle to someone else and it will still work for them too.
Information hiding
An object has a public interface by which other objects can communicate with it. But on the
other hand objects can maintain private information and methods that cannot be communicated
to others.
What Is polymorphism?
What Is inheritance?
------------------------------------------------------------------------------------
Lexical Issues
Whitespace
Java is a free-form language. This means that you do not need to follow any special
indentation rules. For example, the Example program could have been written all on one line
or in any other strange way you felt like typing it, as long as there was at least one whitespace
character between each token that was not already delineated by an operator or separator. In
Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with a
numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Literals
Comments
As mentioned, there are three types of comments defined by Java. You have already seen two:
1. single-line comments------//
2. multiline comments.
3. documentation comment.
This type of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements.
Data Types
Data type defines a set of permitted values on which the legal operations can be performed.
In java, all the variables needs to be declared first i.e. before using a particular variable, it must be
declared in the program for the memory allocation process.
Like , int pedal = 1;
This statement exists a field named "pedal" that holds the numerical value as 1. The value assigned
to a variable determines its data type, on which the legal operations of java are performed. This
behavior specifies that, Java is a strongly-typed programming language.
The data types in the Java programming language are divided into two categories and can be
explained using the following hierarchy structure:
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not
initialized will be set to a reasonable default by the compiler.
The following chart summarizes the default values for the above data types.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
Local variables are slightly different; the compiler never assigns a default value to an uninitialized
local variable. If you cannot initialize your local variable where it is declared, make sure to assign it
a value before you attempt to use it. Accessing an uninitialized local variable will result in a
compile-time error.
Variables
As you learned in the previous lesson, an object stores its state in fields.
int cadence = 0;
int speed = 0;
int gear = 1;
In the Java programming language, the terms "field" and "variable" are both used; this is a common
source of confusion among new developers, since both often seem to refer to the same thing.
2. Class Variables (Static Fields) A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in existence,
regardless of how many times the class has been instantiated. A field defining the number of
gears for a particular kind of bicycle could be marked as static since conceptually the same
number of gears will apply to all instances. The code static int numGears = 6; would create
such a static field. Additionally, the keyword final could be added to indicate that the number of
gears will never change.
3. Local Variables Similar to how an object stores its state in fields, a method will often store
its temporary state in local variables. The syntax for declaring a local variable is similar to
declaring a field (for example, int count = 0;). There is no special keyword designating a variable
as local; that determination comes entirely from the location in which the variable is declared
which is between the opening and closing braces of a method. As such, local variables are only
visible to the methods in which they are declared; they are not accessible from the rest of the
class.
4. Parameters You've already seen examples of parameters, both in the Bicycle class and in
the main method of the "Hello World!" application. Recall that the signature for the main method
is public static void main(String[] args). Here, the args variable is the parameter to this method.
The important thing to remember is that parameters are always classified as "variables" not
"fields". This applies to other parameter-accepting constructs as well (such as constructors and
exception handlers) that you'll learn about later in the tutorial.
Naming a Variable:
Every programming language has its own set of rules and conventions for the kinds of names that
you're allowed to use, and the Java programming language is no different.
The rules and conventions for naming your variables can be summarized as follows:
1. Variable names are case-sensitive. A variable's name can be any legal identifier an
unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign
"$", or the underscore character "_".
2. The convention, however, is to always begin your variable names with a letter, not "$" or
"_". White space is not permitted.
3. Subsequent characters may be letters, digits, dollar signs, or underscore characters. When
choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so
will make your code easier to read and understand. keep in mind that the variable name must
not be a keyword or reserved word.
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
4. The Variable name consists of only one word, spell that word in all lowercase letters. If it
consists of more than one word, capitalize the first letter of each subsequent word. The names
gearRatio and currentGear are prime examples of this convention. By convention, the
underscore character is never used elsewhere.
As stated, main( ) is the method called when a Java application begins. Keep in mind that Java is
case-sensitive. Thus, Main is different from main. It is important to understand that the Java
compiler will compile classes that do not contain a main( ) method. But the Java interpreter
has no way to run these classes. So, if you had typed Main instead of main, the compiler would still
compile your program. However, the Java interpreter would report an error because it would be
unable to find the main( ) method.
Any information that you need to pass to a method is received by variables specified within the set
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
of parentheses that follow the name of the method. These variables are called parameters. If there are
no parameters required for a given method, you still need to include the empty parentheses. In
main( ), there is only one parameter, albeit a complicated one.
String args[ ] declares a parameter named args, which is an array of instances of the class String.
Objects of type String store character strings. In this case, args receives any command-line
arguments present when the program is executed.
import java.util.*;
public class AreaOfSquare
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int a, s; //declare the boxes to hold side and area
System.out.printf("Enter length of side: ");
s = in.nextInt(); //read and store length in s
a = s * s; //calculate area; store in a
System.out.printf("\nArea of square is %d\n", a);
} //end main
} // end AreaOfSquare
Arrays
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements
of the same type. An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes
from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable
can be combined in one statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Example:
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
Operators
Operators are special symbols that perform specific operations on one, two, or three operands, and
then return a result.
As we explore the operators of the Java programming language, it may be helpful for you to know
ahead of time which operators have the highest precedence. The operators in the following table are
listed according to precedence order. The closer to the top of the table an operator appears, the higher
its precedence.
Operators with higher precedence are evaluated before operators with relatively lower precedence.
Operators on the same line have equal precedence. When operators of equal precedence appear in
the same expression, a rule must govern which is evaluated first. All binary operators except for the
assignment operators are evaluated from left to right; assignment operators are evaluated right to
left.
Operator Precedence
Operators Precedence
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
ternary ?:
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate boolean expressions. The goal of the operator is to decide which value should
be assigned to the variable.
The operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
CONTROL STATEMENTS
The statements inside the source files are generally executed from top to bottom, in the order that
they appear. Control flow statements, however, break up the flow of execution by employing
decision making, looping, and branching, enabling your program to conditionally execute particular
blocks of code.
This section describes,
1. The decision-making statements (if-then, if-then-else, switch),
2. The looping statements (for, while, do-while), and
3. The branching statements (break, continue, return) supported by the Java programming
language.
The following program, SwitchDemo, declares an int named month whose value represents a month
out of the year. The program displays the name of the month, based on the value of month, using the
switch statement.
class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month) {
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}
In this case, "August" is printed to standard output.
The body of a switch statement is known as a switch block. Any statement immediately contained by
the switch block may be labeled with one or more case or default labels. The switch statement
evaluates its expression and executes the appropriate case.
Of course, you could also implement the same thing with if-then-else statements:
int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
. . . // and so on
Deciding whether to use if-then-else statements or a switch statement is sometimes a judgment call.
You can decide which one to use based on readability and other factors. An if-then-else statement
can be used to make decisions based on ranges of values or conditions, whereas a switch statement
can make decisions based only on a single integer or enumerated value.
Another point of interest is the break statement after each case. Each break statement terminates the
enclosing switch statement. Control flow continues with the first statement following the switch
block. The break statements are necessary because without them, case statements fall through; that
is, without an explicit break, control will flow sequentially through subsequent case statements.
The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall
through:
class SwitchDemo2
{
public static void main(String[] args)
{
int month = 2;
int year = 2000;
int numDays = 0;
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = " + numDays);
}
}
This is the output from the program.
Number of Days = 29
Technically, the final break is not required because flow would fall out of the switch statement
anyway. However, we recommend using a break so that modifying the code is easier and less error-
prone. The default section handles all values that aren't explicitly handled by one of the case
sections.
The following program, ForDemo, uses the general form of the for statement to print the numbers
1 through 10 to standard output:
class ForDemo
{
public static void main(String[] args)
{
for(int i=1; i<11; i++){
System.out.println("Count is: " + i);
}
}
}
The output of this program is:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Notice how the code declares a variable within the initialization expression. The scope of this
variable extends from its declaration to the end of the block governed by the for statement, so it can
be used in the termination and increment expressions as well. If the variable that controls a for
statement is not needed outside of the loop, it's best to declare the variable in the initialization
expression. The names i, j, and k are often used to control for loops; declaring them within the
initialization expression limits their life span and reduces errors.
The three expressions of the for loop are optional; an infinite loop can be created as follows:
for ( ; ; ) { // infinite loop
Branching Statements:
The break Statement
The break statement has two forms: labeled and unlabeled. You saw the unlabeled form in the
previous discussion of the switch statement. You can also use an unlabeled break to terminate a for,
while, or do-while loop, as shown in the following BreakDemo program:
class BreakDemo {
public static void main(String[] args) {
int i;
boolean foundIt = false;
if (foundIt) {
System.out.println("Found " + searchfor
+ " at index " + i);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This program searches for the number 12 in an array. The break statement, shown in boldface,
terminates the for loop when that value is found. Control flow then transfers to the print statement at
the end of the program. This program's output is:
Found 12 at index 4
An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but
a labeled break terminates an outer statement. The following program, BreakWithLabelDemo, is
similar to the previous program, but uses nested for loops to search for a value in a two-dimensional
array. When the value is found, a labeled break terminates the outer for loop (labeled "search"):
class BreakWithLabelDemo
{
public static void main(String[] args)
{
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
Prepared by: Mr. Thinakaran Anansingh
INFORMATION AND COMMUNICATIONS
UNIVERSITY
DEPARTMENT OF ICT
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
This is the output of the program.
Found 12 at 1, 0
The break statement terminates the labeled statement; it does not transfer the flow of control to the
label. Control flow is transferred to the statement immediately following the labeled (terminated)
statement.