UNIT-
1
INDEX
History of Java,
Java buzzwords, data types.
variables, scope and life time of variables
arrays, operators, expressions
control statements
type conversion and casting
simple java program
classes and objects
constructors, methods,
Access control, this keyword
garbage collection
overloading methods and constructors
parameter passing
Recursion
string handling
Java History
Computer language innovation and development
occurs for two fundamental reasons:
1) to adapt to changing environment
2) to implement improvements in the art of
programming
Many Java features are inherited from the earlier
languages:
Before Java: C
Designed by Dennis Ritchie in
1972.
Before C: BASIC, COBOL,
FORTRAN
C- structured, efficient.
Before Java: C++
Designed by Bjarne Stroustrup in 1979.
Response to the increased complexity of programs:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
OOP – methodology that helps to organize complex programs
through the use of inheritance, encapsulation, abstraction and
polymorphism.
Java: History
In 1990, Sun Microsystems started a project
assigned to James Gosling.
Objective: to develop software for consumer
electronics.
Java Buzzwords
The key considerations were summed up by the Java team in the
following list of buzzwords:
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
JVM is short for Java Virtual Machine. JVM is an abstract
computing machine, or virtual machine. It is a platform-
independent execution environment that converts Java bytecode
into machine language and executes it. Most programming
languages compile source code directly into machine code that is
designed to run on a specific microprocessor architecture or
operating system, such as Windows or UNIX.
Bytecode
The Just-In-Time (JIT) compiler is a component of the runtime environment that
improves the performance of Java™ applications by compiling bytecodes to
native machine code at run time. The JIT compiler helps improve the
performance of Java programs by compiling bytecodes into native machine
code at run time
The main difference between Interpreter and JIT compiler is that
the interpreter is a software that converts the source code into native machine
code line by line while JIT compiler is a component in JVM that improves the
performance of Java programs by compiling bytecodes into native machine
codes at runtime
Editing, compiling, and executing.
Data Types
Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data streams( data from network).
short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
long: 64-bit integer type.
Range: -9223372036854775808 to 9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold the desired value
float: 32-bit floating-point number.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage: 1) fractional part is needed
2) large degree of precision is not required
double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Standard set of characters known as ASCII ranges from 0 – 127 and
Extended 8-bit character set, ISO-latin-1, ranges from 0 - 255
Example: char c = ‘a’;
Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in (almost) all human languages.
2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.
boolean: Two-valued type of logical values.
Range: true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as conditional or looping statements
Literals
A constant value in java is created by using a literal
Types of literals:
Integer literals
Floating point literals
Boolean literals
Character literals
String literals
Integer Literals
Decimal values(base 10):
Octal values(base 8): leads by 0. example : 02, 09
Binary values (base 2): leads by 0b or 0B :
Hexadecimal values(base 16): leads by 0x or 0X
For long integers: 9999L/l
From JDK 7, allows to embed 1 or more underscores
Floating-points Literals
Standard notation: 2.366
Scientific notation: 2366E-3, 23.66e-2
Default is double precession.
To make as float precession, append it by F or f.
To use hexadecimal floating point numbers, use P or p instead of E or e.
For long integers: 9999L/l
From JDK 7, allows to embed 1 or more underscores
Boolean Literals
True or False not equal to 1 or 0.
Only for Boolean variables. EX: boolean b1=true;
Character Literals
These are 16 bit values that can be converted to integers.
So integer operations like add, sub.
Represented inside a pair of ‘.
Escape sequences: \n ‘\’ \ooo \uhhhh \\ \t
String Literals
Not as array of characters.
Represented inside a pair of “.
String s=“Welcome”
Variables
Java uses variables to store data.
To allocate memory space for a variable JVM requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3) optionally, the variable may be assigned an initial value
All done as part of variable declaration.
Variables
declaration –to assign a type to a variable
initialization –to give an initial value to a variable
scope – how the variable is visible to other parts of the program
lifetime – how the variable is created, used and destroyed
type conversion – how Java handles automatic type conversion
type casting – how the type of a variable can be narrowed down
type promotion – how the type of a variable can be expanded
Variable Declaration
type identifier [=value];
type must be
A simple datatype
User defined datatype (class type)
Identifier is a recognizable name confirm to identifier rules
Value is an optional initial value.
Variable Declaration
We can declare several variables at the same time:
type identifier [=value][, identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
Variable Scope
Scope determines the visibility of program element.
In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{
…
}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
Variable Lifetime
Variables are created when their scope is entered by control flow and
destroyed when their scope is left:
A variable declared in a method will not hold its value between
different invocations of this method.
A variable declared in a block looses its value when the block is left.
Initialized in a block, a variable will be re-initialized with every re-
entry. Variables lifetime is confined to its scope.
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion
• Smaller Data Type Larger Data Type
– Narrowing Type Conversion
• Larger Data Type Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
• Widening Type Conversion
– Implicit conversion by compiler automatically
byte
byte ->
-> short,
short, int,
int, long,
long, float,
float, double
double
short
short -> -> int,
int, long,
long, float,
float, double
double
char
char -> -> int,
int, long,
long, float,
float, double
double
int
int ->
-> long,
long, float,
float, double
double
long
long ->-> float,
float, double
double
float
float ->-> double
double
• Narrowing Type Conversion
– Programmer should describe the conversion explicitly
byte
byte ->
-> char
char
short
short ->
-> byte,
byte, char
char
char
char ->
-> byte,
byte, short
short
int
int ->
-> byte,
byte, short,
short, char
char
long
long ->-> byte,
byte, short,
short, char,
char, intint
float
float ->
-> byte,
byte, short,
short, char,
char, int,
int, long
long
double
double ->-> byte,
byte, short,
short, char,
char, int,
int, long,
long, float
float
Type Conversion
byte and short are always promoted to int
if one operand is long, the whole expression is promoted to long
if one operand is float, the entire expression is promoted to float
if any operand is double, the result is double
Type Casting
General form: (target_Type) value
Examples:
1) integer value will be reduced module bytes range:
int i =257;
byte b = (byte) i; 257%256
2) floating-point value will be truncated to integer value and even then if it large
than integer range, it will be reduced by module int range:
float f = 323.142;
int i = (int) f;
byte a=(byte) f;
Automatic Type Promotion in Expressions
Examples:
1) byte a=40; byte b=50; byte c=100; byte d= a*b/c;
2) byte k= b*2; //invalid
byte k= (byte)(b*2);
Arrays
An array is a group of same-typed elements separated by a
common
Arrays are:
1) declared
2) created
3) initialized
4) used
Also, arrays can have one or several dimensions.
Array Declaration
Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
Array Creation
After declaration, no array actually exists.
In order to create an array, we use the new operator:
type[size];
array-variable = new type[size];
Example: int a[]=new int[10];
This creates a new array to hold size elements of type, which reference will be kept
in the variable array-variable.
Array Indexing
Later we can refer to the elements of this array through their
indexes.
array-variable[index]
The array index always starts with zero.
The Java run-time system makes sure that all array indexes are in the
correct range, otherwise raises a run-time error.
Array Initialization
Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
int a[]=new int[4];
a[0]=12;
a[3]=5;
Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements
Multidimensional Arrays
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation: int array = new int[2][3];
type array_name[][]= new int[Size][];
array_name[0]=new int[Size1];
array_name[1]=new int[Size2];
array_name[2]=new int[Size3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
Operators Types
Java operators are used to build value expressions.
Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) Boolean logical
5) bitwise
6) conditional operator
Basic Arithmetic Operators
+ op1 + op2 ADD
- op1 - op2 SUBSTRACT
* op1 * op2 MULTIPLY
/ op1 / op2 DIVISION
% op1 % op2 REMAINDER
++ Op++ or ++op Increment
-- Op-- or --op Decrement
int a=13;
int b=a%10; b=3
Float f=34.6;
float d=f%10; d=4.6
Arithmetic assignments
+= v += expr; v = v + expr ;
-= v -=expr; v = v - expr ;
*= v *= expr; v = v * expr ;
/= v /= expr; v = v / expr ;
%= v %= expr; v = v % expr ;
Relational operators
== Equals to Apply to any type
!= Not equals to Apply to any type
> Greater than Apply to numerical type
< Less than Apply to numerical type
>= Greater than or equal Apply to numerical type
<= Less than or equal Apply to numerical type
Boolean Logical operators int a=20;
if(a&&(b<2))
& op1 & op2 Logical AND
| op1 | op2 Logical OR
&& op1 && op2 Short-circuit
AND
|| op1 || op2 Short-circuit OR
! ! op Logical NOT
^ op1 ^ op2 Logical XOR
Bitwise operators
~ ~op Inverts all bits
& op1 & op2 Produces 1 bit if both operands are 1
| op1 |op2 Produces 1 bit if either operand is 1
^ op1 ^ op2 Produces 1 bit if exactly one operand is 1
11001111
>>
11100111 op1 >> op2 Shifts all bits in op1 right by the value of op2
11110011
<< op1<<op2 Shifts all bits in op1 left by the values of op2
>>> op1 >> op2 Shifts all bits in op1 right by the value of
op2(unsigned shift)
11001111
01100111
00110011
a<b?c=2:c=10
Op1=op2
int a=10,b=10,c=10,d=10;
a=b=c=d=10
Expressions
An expression is a construct made up of variables, operators, operands and/ or method
invocations, which are constructed according to the syntax of the language, that evaluates to
a single value.
Examples of expressions are in bold below:
number = 0;
Array[0] = 100;
[Link] ("Element 1 at index 0: " + Array[0]);
result = 1 + 2; // result is now 3
if(value1 == value2)
[Link]("value1 == value2");
Control Statements
Java control statements cause the flow of execution to advance and branch based on
the changes to the state of the program.
Control statements are divided into three groups:
1) selection statements allow the program to choose different parts of the program
execution based on the outcome of an expression
2) iteration statements enable program execution to repeat one or more statements
3) jump statements enable your program to execute in a non-linear fashion
Selection or Conditional or branch Statements
Java selection statements allow to control the flow of program’s execution based upon
conditions known only during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) nested-if
5) switch-case
1) if
The syntax of if statement is :
if(condition)
statement;
Ex: boolean available=true;
if(available)
[Link](“Yes”);
Ex: int a=9,b=87;
if(a>b)
[Link](a);
Ex: if(a)
[Link](a);
2) if-else
The syntax of if-else statement is :
if(condition)
statement 1;
else
statement 2;
Ex: int a=9,b=87;
if(a>b)
[Link](a);
else
[Link](b);
3) if-else-if
The syntax of if-else-if statement is :
if(condition 1) statement 1;
else if(condition 2) statement 2;
else if(condition 3) statement 3;
…
else statement k;
Ex: int a=9,b=87,c=10;
if(a>b) [Link](a);
else if(b>c) [Link](b);
else [Link](c);
4) Nested- if
Ex: int a=9,b=87, c=10;
The syntax of nested-if statement
if(a>b)
is : {
if(condition 1) if(a>c)
{if(condition 2) statement 1; [Link](a);
else statement 2; else
} [Link](c);
else }
{ if(condition 3) statement 3; else
else statement 4; {
} if(b>c)
[Link](b);
else
[Link](c);
}
5) Switch-case
Ex: int a;
The syntax of switch-case
switch(a)
statement is : {
switch(expression) case 1: [Link](“1”);
{ case 2: [Link](“2”);
case value1: //statement case 3: [Link](“3”);
sequence1 case 4: [Link](“4”);
case value2: //statement case 5: [Link](“5”);
sequence1 default: [Link](“not between 1
case value3: //statement & 5”);
sequence1 }
case value4 //statement
sequence1
…
default: // default sequence
}
Note: 1. from JDK 7: byte, short, int,
Iteration Statements
Java iteration statements enable repeated execution of part of a program until a
certain termination condition becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for
1) while
Ex: int a=5;
The syntax of while loop
while(a<10)
statement is : {
while(condition) [Link](a);
{// statements a++;
} }
[Link](a);
while(condition);
Ex: int a=5;
while(a++<10);
[Link](a);
2) do-while
Ex: int a=5;
The syntax of while loop
do
statement is : {
do [Link](a);
{// statements a++;
} while(condition); } while(a<10);
3) for
Ex: int a;
The syntax of for loop statement
for(a=5;a<10;a++)
is : {
for(initialization; condition; [Link](a);
updation) }
{// statements
}
Ex: int a;
for(a=5;a<10;a++);
[Link](a);
for(initialization;condition;updatio
n); Ex:
int a,b;
for(a=10,b=0;a<b;a--,b++);
[Link](“a=“+a+” b=“+b);
Allows commas.
4) For each
Ex: int a[]= {20,5,6,1};
Since JDK5, for-each
for(int x: a )
The syntax of for loop statement {
[Link](x);
is : }
for(type variable: collection_name)
{// statements
} Ex: int a[]={1,2,3,4};
for(int i=0;i<=4;i++)
A variable receives one value at a
{
time from 1st element to last
[Link](a[i]);
element.
}
Prevents boundary errors
multi
4) For each
Ex: int a[][]= new int[3][];
Since JDK5, for-each
a[0]=new int[2];
The syntax of for loop statement a[1]=new int[4];
a[2]=new int[1];
is : a[0]= a[1]={100,200,300,400};
for(type variable: collection_name)
a[2]={1};
{// statements for(int i=0;i<3;i++)
} {
for(int x: a[i] )
A variable receives one value at a
{
time from 1st element to last
[Link](x);
element.
}
Prevents boundary errors
}
Multi dimensional arrays
Jump Statements
Java jump statements enable transfer of control to other parts of
program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that can also alter the
control flow of a program.
Simple Java Program
A class to display a simple message:
class MyProgram
public static void main(String[] args)
[Link](“First Java program.");
}
What is an Object?
Real world objects are things that have:
1) state
2) behavior
Example: your dog:
state – name, color, breed,
behavior – sitting, barking, waging tail, running
A software object is a collection of variables (states) and methods
(operations).
What is a Class?
int a;
A class is a blueprint or template that defines the char b;
string s;
variables and methods common to all objects of a
certain kind.
Example: ‘your dog’ is a object of the class Dog. O O2
1
An object holds values for the variables defined in
the class.
An object is called an instance of the Class
Object Creation
class_name obj= new class_name();
class A
{ int i,j;}
A object1=new A();
Object Destruction
A program accumulates memory through its execution.
Two mechanism to free memory that is no longer need by the program:
1) manual – done in C/C++
2) automatic – done in Java
In Java, when an object is no longer accessible, it is eventually removed
from the memory by the garbage collector.
Garbage collector is a part of the Java Run-Time Environment.
Class
A basis for the Java language.
Each concept we wish to describe in Java must be included inside a
class.
A class is a template for objects
An object is an instance of a class
Class Definition
A class contains a name, several variable declarations (instance variables) and
several method declarations. All are called members of the class.
General form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
…
type method-name-m(parameter-list) { … }
}
Example: Class Usage
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link] ("Volume is " + vol);
} }
Methods
General form of a method definition:
type name(parameter-list) {
…
… return value;
}
Components:
1) type - type of values returned by the method. If a method does not return any value,
its return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.
Within a class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
[Link]("Volume is ");
[Link](width * height * depth);
}
}
Parameterized Method
Parameters increase generality and applicability of a method:
1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }
Parameter: a variable receiving value at the time the method is invoked.
Argument: a value passed to the method when it is invoked.
Constructor
A constructor initializes the instance variables of an object.
It is called immediately after the object is created but before the new operator
completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type is that class
itself
When the class has no constructor, the default constructor automatically
Example: Constructor
class Box {
double width;
double height;
double depth;
Box() {
[Link]("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
Parameterized Constructor
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
Keyword -this
• Can be used by any object to refer to itself in any class method
• Typically used to
– Avoid variable name collisions
Keyword this allows a method to refer to the object that invoked it.
It can be used inside any method to refer to the current object:
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
Garbage Collection
Garbage collection is a mechanism to remove objects from memory when they are
no longer needed.
Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many references an object has.
2) It removes an object from memory when it has no longer any references.
3) Thereafter, the memory occupied by the object can be allocated again.
4) The garbage collector invokes the finalize method.
finalize() Method
A constructor helps to initialize an object just after it has been created.
In contrast, the finalize method is invoked just before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { … }
2) implemented when the usual way of removing objects from memory is
insufficient, and
some special actions has to be carried out
Method Overloading
It is legal for a class to have two or more methods with the same name.
However, Java has to be able to uniquely associate the invocation of a
method with its definition relying on the number and types of arguments.
Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement polymorphism.
Example: Overloading
class OverloadDemo
{
void test() {
[Link]("No parameters");
}
void test(int a) {
[Link]("a: " + a);
}
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
double test(double a) {
[Link]("double a: " + a); return
a*a;
}
}
Constructor Overloading
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
Box() {
width = -1; height = -1; depth = -1;
Box(double len) {
width = height = depth = len;
double volume() { return width * height * depth; }
}
Parameter Passing
Two types of variables:
1) simple types
2) class types
Two corresponding ways of how the arguments are passed to methods:
1) by value- a method receives a copy of the original value; parameters of
simple types
2) by reference - a method receives the memory address of the original value,
not the value itself; parameters of class types
Call by value
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
[Link]("a and b before call: “);
[Link](a + " " + b);
[Link](a, b);
[Link]("a and b after call: ");
[Link](a + " " + b);
}
Call by reference
As the parameter hold the same address as the argument, changes to the object
inside the method do affect the object used by the argument:
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
[Link]("ob.a and ob.b before call: “);
[Link](ob.a + " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: ");
[Link](ob.a + " " + ob.b);
}
}
Recursion
A recursive method is a method that calls itself:
1) all method parameters and local variables are allocated on the stack
2) arguments are prepared in the corresponding parameter positions
3) the method code is executed for the new arguments
4) upon return, all parameters and variables are removed from the stack
5) the execution continues immediately after the invocation point
Example: Recursion
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
[Link]("Factorial of 5 is ");
[Link]([Link](5));
} }
String Handling
String is probably the most commonly used class in Java's class library.
The first thing to understand about strings is that every string you create is
actually an object of type String. Even string constants are actually String
objects.
For example, in the statement
[Link]("This is a String, too");
the string "This is a String, too" is a String constant
Java defines one operator for String objects: +.
It is used to concatenate two strings. For example, this statement
String myString = "I" + " like " + "Java.";
String myString=“I like Java”;
results in myString containing
"I like Java."
The String class contains several methods that you can use. Here are a few.
You can test two strings for equality by using equals( ).
You can obtain the length of a string by calling the length( ) method.
You can obtain the character at a specified index within a string by calling charAt( ).
The general forms of these three methods are shown here:
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
[Link]("Length of strOb1: " +[Link]());
[Link] ("Char at index 3 in strOb1: " +[Link](3));
if([Link](strOb2))
[Link]("strOb1 == strOb2");
else
[Link]("strOb1 != strOb2");
if([Link](strOb3))
[Link]("strOb1 == strOb3");
else
[Link]("strOb1 != strOb3");
}}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3