1. Contents
1
Data types in Java
Strings & Characters
Arithmetic Operators & Expressions
Type Conversion
Comments
Arrays
Keywords
RAJESHREE KHANDE
2. Data Types, Variables, and
Constants
2
Declaring Variables
Primitive Data Types
Initial Values and Literals
String Literals and Escape Sequences
Constants
RAJESHREE KHANDE
3. Data Types
3
To declare a variable, assign a name (identifier) and a data type
Data type tells compiler:
How much memory to allocate
Format in which to store data
Types of operations you will perform on data
Compiler monitors use of data
Java is a "strongly typed" language
Java "primitive data types"
byte, short, int, long, float, double, char, boolean
RAJESHREE KHANDE
4. Declaring Variables
4
Variables hold one value at a time, but that value can change
Syntax:
dataType identifier;
or
dataType identifier1, identifier2, …;
Naming convention for variable names:
first letter is lowercase
embedded words begin with uppercase letter
RAJESHREE KHANDE
5. Integer Types - Whole Numbers
Example declarations:
int testGrade;
int numPlayers, highScore;
short xCoordinate, yCoordinate;
byte ageInYears;
long cityPopulation;
Type Size in
byte
Minimum Value Maximum Value
byte 1 -128 127
short 2 -32768 +32677
int 4 -2, 147, 483, 648 2, 147, 483, 647
long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807
5RAJESHREE KHANDE
6. Floating-Point Data Types
Example declarations:
float salesTax;
double interestRate;
double paycheck,
sumSalaries;
Type Size in
byte
Minimum Value Maximum Value
Float 4 1.4E-45 3.4028235E38
Double 8 4.9E-324 1.7976931348623157E308
6RAJESHREE KHANDE
7. char Data Type
One Unicode character (16 bits - 2 bytes)
Type Size Minimum Value Maximum Value
in Bytes
char 2 character character
encoded as 0 encoded as
FFFF
Example declarations:
char finalGrade;
char newline, tab, doubleQuotes;
7RAJESHREE KHANDE
8. boolean Data Type
8
Two values only:
true
false
Used for decision making or controlling the order
of execution of a program
Example declarations:
boolean isEmpty;
boolean passed, failed;
RAJESHREE KHANDE
9. Assigning Values to Variables
9
Assignment operator =
Value on the right of the operator is assigned to the variable
on the left
Value on the right can be a literal (text representing a specific
value), another variable, or an expression (explained later)
Syntax:
dataType variableName = initialValue;
Or
dataType variable1 = initialValue1,
variable2 = initialValue2, …;
RAJESHREE KHANDE
10. Assigning the Values of Other
Variables
10
Syntax:
dataType variable2 = variable1;
Rules:
1. variable1 needs to be defined before this statement appears
in the source code
2. variable1 and variable2 need to be compatible data types; in
other words, the precision of variable1 must be lower than or
equal to that of variable2.
RAJESHREE KHANDE
11. Compatible Data Types
11
Any type in right column can be assigned to type in left
column:
Data Type Compatible Data Types
byte byte
short byte, short
int byte, short, int, char
long byte, short, int, long, char
float float, byte, short, int, long, char
double float, double, byte, short, int, long, char
boolean boolean
char char
RAJESHREE KHANDE
12. String Concatenation Operator (+)
12
Combines String literals with other data types for printing
Example:
String hello = "Hello";
String there = "there";
String greeting = hello + ' ' + there;
System.out.println( greeting );
Output is:
Hello there
RAJESHREE KHANDE
13. Escape Sequences
13
To include a special character in a String, use an
escape sequence
Character Escape Sequence
Newline n
Tab t
Double quotes "
Single quote '
Backslash
Backspace b
Carriage return r
Form feed f
See Example 2.3 Literals.java
RAJESHREE KHANDE
14. Assigning the Values of Other
Variables
14
Syntax:
dataType variable2 = variable1;
Rules:
1. variable1 needs to be defined before this statement appears
in the source code
2. variable1 and variable2 need to be compatible data types; in
other words, the precision of variable1 must be lower than or
equal to that of variable2.
RAJESHREE KHANDE
15. Sample Assignments
15
This is a valid assignment:
float salesTax = .05f;
double taxRate = salesTax;
This is invalid because the float data type is lower
in precision than the double data type:
double taxRate = .05;
float salesTax = taxRate;
RAJESHREE KHANDE
16. String Concatenation Operator (+)
16
Combines String literals with other data
types for printing
Example:
String hello = "Hello";
String there = "there";
String greeting = hello + ' ' + there;
System.out.println( greeting );
Output is:
Hello there
RAJESHREE KHANDE
17. Common Error Trap
17
String literals must start and end on the
same line. This statement:
System.out.println( "Never pass a water fountain
without taking a drink" );
generates these compiler errors:
unclosed string literal
')' expected
Break long Strings into shorter Strings and use
the concatenation operator:
System.out.println( "Never pass a water fountain"
+ " without taking a drink" );
RAJESHREE KHANDE
18. String Concatenation Operator (+)
18
Combines String literals with other data
types for printing
Example:
String hello = "Hello";
String there = "there";
String greeting = hello + ' ' + there;
System.out.println( greeting );
Output is:
Hello there
RAJESHREE KHANDE
19. Common Error Trap
19
String literals must start and end on the same line. This
statement:
System.out.println( "Never pass a water fountain
without taking a drink" );
generates these compiler errors:
unclosed string literal
')' expected
Break long Strings into shorter Strings and use the
concatenation operator:
System.out.println( "Never pass a water fountain"
+ " without taking a drink" );
RAJESHREE KHANDE
20. 20
Declare a variable only once
Once a variable is declared, its data type cannot
be changed.
These statements:
double twoCents;
double twoCents = .02;
generate this compiler error:
twoCents is already defined
RAJESHREE KHANDE
21. 21
Once a variable is declared, its data type cannot
be changed.
These statements:
double cashInHand;
int cashInHand;
generate this compiler error:
cashInHand is already defined
RAJESHREE KHANDE
22. Constants
22
Value cannot change during program execution
Syntax:
final dataType constantIdentifier =
assignedValue;
Note: assigning a value when the constant is
declared is optional. But a value must be
assigned before the constant is used.
RAJESHREE KHANDE
23. Mixed-Type Arithmetic
23
When performing calculations with operands of different
data types:
Lower-precision operands are promoted to higher-precision
data types, then the operation is performed
Promotion is effective only for expression evaluation;
not a permanent change
Called "implicit type casting“
Bottom line: any expression involving a floating-point operand
will have a floating-point result.
RAJESHREE KHANDE
24. Rules of Promotion
24
Applies the first of these rules that fits:
1. If either operand is a double, the other operand is converted
to a double
2. If either operand is a float, the other operand is converted to a
float.
3. If either operand is a long, the other operand is converted to a
long.
4. If either operand is an int, the other operand is promoted to an
int
5. If neither operand is a double, float, long, or an int, both
operands are promoted to int.
RAJESHREE KHANDE
25. Explicit Type Casting
25
Syntax:
(dataType)( expression )
Note: parentheses around expression are optional
if expression consists of 1 variable
Useful for calculating averages
RAJESHREE KHANDE
26. Operator Precedence
26
Operator Order of
evaluation
Operation
( ) left - right parenthesis for explicit grouping
++ -- right - left preincrement, predecrement
++ -- right - left postincrement, postdecrement
* / % left - right multiplication, division, modulus
+ - left - right addition or String concatenation,
subtraction
= += -= *=
/= %=
right - left assignment
RAJESHREE KHANDE
27. Variables and Assignments
27
Variables
Types
char 16 bits Unicode character data
boolean Boolean Variable
byte 8 bits signed integer
short 16 bits signed integer
int 32 bits signed integer
long 64 bits signed integer
float 32 bits signed floating point number
double 64 bits signed floating point number
RAJESHREE KHANDE
28. Strings and Characters
28
String : sequence of character
String s = “Enter an integer value: ” ;
Char c = ‘A’;
Concatenation Operator ‘+’
String s = “Lincoln said: ” + “” Four score and seven
years ago”” ;
Result :
Lincoln said: “Four score and seven years ago”
RAJESHREE KHANDE
29. Expression
29
char ch; int i; float f; double outcome;
ch = ‘0’; i = 10; f = 10.2f;
outcome = ch * i / f;
double
double float
float long
long int
Yes No
Yes No
Yes No
RAJESHREE KHANDE
30. Assignment
30
Widening Conversion
byte b = 127;
int i;
i = b;
Narrowing Conversion
byte b;
int i = 258;
b = (byte) i;
Wrong Conversion
byte b;
int i = 127;
b = i;
Right Conversion (But data may be lost)
byte b;
int i = 127;
b = (byte) i;
Type Casting
RAJESHREE KHANDE
31. Java Keywords
31
50 Java Keywords
abstract double int super
boolean else interface switch
break extends long synchronized
byte final native this
case finally new throw
catch float package throws
char for private transient*
class goto* protected try
const* if public void
continue implements return volatile
default import short while
do instanceof static strictfp
assert (New in 1.5) enum (New in 1.5)
The “assert” is recognized as keyword in JDK1.4 compiler, but we could not
use it.
It can be used it from 1.5.RAJESHREE KHANDE
32. Flow of Control
32
Java executes one statement after the other in the
order they are written
Many Java statements are flow control statements:
Alternation: if, if else, switch
Looping: for, while, do while
Escapes: break, continue, return
RAJESHREE KHANDE
34. If – The Conditional Statement
34
The if statement evaluates an expression and if that
evaluation is true then the specified action is taken
if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10
It could have been written:
if ( x < 10 )
x = 10;
Or, alternatively:
if ( x < 10 )
{ x = 10; }
RAJESHREE KHANDE
35. If… else
35
The if … else statement evaluates an expression and
performs one action if that evaluation is true or a
different action if it is false.
if (x != oldx)
{
System.out.print(“x was changed”);
}
else {
System.out.print(“x is unchanged”);
}
RAJESHREE KHANDE
36. Nested if … else
36
if ( myVal > 100 ) {
if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(“myVal is in range”);
}
RAJESHREE KHANDE
37. else if
37
Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute code
block #3
}
RAJESHREE KHANDE
38. The switch Statement
38
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
//execute code block #4
break;
}
RAJESHREE KHANDE
39. The for loop
39
Loop n times
for ( i = 0; i < n; n++ )
{
// this code body will execute n times
// ifrom 0 to n-1
}
Nested for:
for ( j = 0; j < 10; j++ )
{
for ( i = 0; i < 20; i++ )
{
// this code body will execute 200 times
}
}
RAJESHREE KHANDE
41. do {… } while loops
41
do
{
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);
RAJESHREE KHANDE
42. Break
42
A break statement causes an exit from the
innermost containing while, do, for or switch
statement.
for ( int i = 0; i < maxID, i++ )
{
if ( userID[i] == targetID )
{
index = i;
break;
}
} // program jumps here after break
RAJESHREE KHANDE
43. Continue
43
Can only be used with while, do or for.
The continue statement causes the innermost loop to start the
next iteration immediately.
for ( int i = 0; i < maxID; i++ )
{
if ( userID[i] != -1 )
continue;
System.out.print( “UserID ” + i + “ :” + userID)
}
RAJESHREE KHANDE
44. Arrays
44
Am array is a list of similar things
An array has a fixed:
name
type
length
These must be declared when the array is created.
Arrays sizes cannot be changed during the execution
of the code
RAJESHREE KHANDE
45. 45
myArray has room for 8 elements
The elements are accessed by their index
in Java, array indices start at 0
3 6 3 1 6 3 4 1myArray =
0 1 2 3 4 5 6 7
Arrays
RAJESHREE KHANDE
46. Declaring Arrays
46
int myArray[];
declares myArray to be an array of integers
myArray = new int[8];
sets up 8 integer-sized spaces in memory, labelled
myArray[0] to myArray[7]
int myArray[] = new int[8];
combines the two statements in one line
RAJESHREE KHANDE
47. Assigning Values
47
Refer to the array elements by index to store values in
them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...
Can create and initialise in one step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};
RAJESHREE KHANDE
48. Iterating Through Arrays
48
for loops are useful when dealing with arrays:
for (int i = 0; i < myArray.length; i++)
{
myArray[i] = getsomevalue();
}
RAJESHREE KHANDE
49. Class & Object
49
What Are Classes?
A class is a blueprint or prototype that defines the
variables and the methods common to all objects of a
certain kind.
What Is an Object?
An object is a software bundle of variables and
related methods. Software objects are often used to
model real-world objects you find in everyday life.
RAJESHREE KHANDE
50. 50
Class vs. Object
Specifies the structure
(the number and types)
of its objects’ attributes
the same for all of its
objects
Specifies the possible
behaviors of its objects
Holds specific values of
attributes
These values can
change while the
program is running
Behaves appropriately
when called upon
RAJESHREE KHANDE
51. 51
Class vs. Object
A piece of the program’s
source code
Written by a
programmer
An entity in a running
program
Created when the
program is running (by
the main method or a
constructor)
RAJESHREE KHANDE
52. 52
Classes
public class Car
{
...
}
Car.java By convention, the
name of a class (and
its source file) always
starts with a capital
letter.
(In Java, all names are case-sensitive.)
RAJESHREE KHANDE
53. public class SomeClass
53
Fields
Constructors
Methods
}
Attributes / variables that define the
object’s state; can hold numbers,
characters, strings, other objects
Procedures for constructing a
new object of this class and
initializing its fields
Actions that an object of this
class can take (behaviors)
{
Class header
SomeClass.java
import ... import statements
RAJESHREE KHANDE
54. Classes
54
A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
The basic syntax for a class definition:
Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
Class ClassName
{
[fields declaration]
[methods declaration]
}
RAJESHREE KHANDE
55. Classes
55
Classes describe the data held by each of its objects
A class may describe any number of objects
A class may describe a single object, or even no
objects at all.
RAJESHREE KHANDE
57. Adding Fields: Class Circle
with fields
57
Add fields
The fields (data) are also called the instance
varaibles.
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
RAJESHREE KHANDE
58. Adding Methods
58
A class with only data fields has no life. Objects created
by such a class cannot respond to any messages.
Methods are declared inside the body of the class but
immediately after the declaration of data fields.
The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
RAJESHREE KHANDE
59. Adding Methods to Class
Circle
59
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
RAJESHREE KHANDE
60. Data Abstraction &
Encapsulation
60
The wrapping of data & method in single unit called
class is known as encapsulation.
The data is not accessible to the outside world & only
those methods which wrapped inside the class can
access it.
These methods provide the interface between objects
data & program.
The insulation of data from direct access is called as
data hidingRAJESHREE KHANDE
61. Data Abstraction & Encapsulation
61
Abstraction refers to representing essential features
without including the background details.
Classes uses the concept of abstraction & are defined
as list of abstract attribute such as size ,weight & cost
and method that operate on theses data.
Declare the Circle class, have created a new data type
– Data Abstraction
Circle aCircle;
Circle bCircle;
RAJESHREE KHANDE
62. Class of Circle cont.
62
aCircle, bCircle simply refers to a Circle object, not
an object itself.
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
RAJESHREE KHANDE
63. Creating objects of a class
63
Objects are created dynamically using the new
keyword.
aCircle and bCircle refer to Circle objects
bCircle = new Circle() ;aCircle = new Circle() ;
RAJESHREE KHANDE
64. 64
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
Before Assignment
RAJESHREE KHANDE
65. Automatic garbage collection
65
The object does not have a reference and
cannot be used in future.
The object becomes a candidate for automatic garbage
collection.
Java automatically collects garbage periodically and
releases the memory used to be used in the future.
Q
RAJESHREE KHANDE
66. Accessing Object/Circle Data
66
Similar to C syntax for accessing data defined in a
structure.
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
RAJESHREE KHANDE
67. Executing Methods in Object/Circle
67
Using Object Methods:
Circle aCircle = new Circle();
double area1;
aCircle.r = 1.0;
area1 = aCircle.area();
sent ‘message’ to aCircle
RAJESHREE KHANDE
68. Using Circle Class
68
// Circle.java: Contains both Circle class and its user class
public class Circle
{
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
RAJESHREE KHANDE
69. Using Circle Class
69
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
System.out.println("Radius="+ aCircle.r+ " Area=“ + area);
}
} RAJESHREE KHANDE
70. Access Specifiers
70
In Java code, class and variable and method and
constructor declarations can have “access specifiers”
:
- private
- protected
- public.
- none (default)
The purpose of access specifiers is to declare which
entity can not be accessed from where.
RAJESHREE KHANDE
71. Access Specifiers for Class
Variables and Methods
71
Specifier class subclass package World
private Y
protected Y Y Y
public Y Y Y Y
none Y Y
RAJESHREE KHANDE
72. Protected
72
If a variable is declared protected, then the class
itself can access it.
Its subclass can access it
Any class in the same package can also access it.
RAJESHREE KHANDE
73. Public
73
Public classes, methods, and fields can be accessed from
everywhere.
The only constraint is that a file with Java source code can only
contain one public class whose name must also match with the
filename.
If it exists, this public class represents the application or the
applet, in which case the public keyword is necessary to enable
your Web browser or appletviewer to show the applet.
You use public classes, methods, or fields only if you explicitly
want to offer access to these entities.
public class Square
{ // public class public x, y, size; // public instance variables }
RAJESHREE KHANDE
74. Access Specifiers
74
None
If a class member doesn't have any access
specifier , then the class itself can access it.
Any class in the same package can also access it.
RAJESHREE KHANDE
75. Access Specifiers
75
class P
{
int x = 7;
}
public class AS
{
public static void main(String[] args)
{
P p = new P();
System.out.println(p.x);
}
}
The code compiles and
runs. But, if you add
“private” in front of “int x”,
then you'll get a compiler
error: “x has private
access in P”. This is
because when a
member variable is
private, it can only be
accessed within that
class
RAJESHREE KHANDE
76. Access Specifiers for Classes
76
For classes, only the “public” access specifier can be used.
Basically, Java has this “One Class Per File” paradigm.
That is, in every java source code file, only one class in the file is
public accessible, and that class must have the same name as
the file.
Optionally, the class can be declared with “public” keyword.
If you use any other access specifier on classes, or declare more
than one class “public” in a file, the compiler will give an error.
RAJESHREE KHANDE
77. Pass by value
77
Pass-by-value
The actual parameter (or argument expression) is fully
evaluated and the resulting value is copied into a location
being used to hold the formal parameter's value during
method/function execution.
That location is typically a chunk of memory on the runtime
stack for the application (which is how Java handles it), but
other languages could choose parameter storage differently.
Pass-by-reference
The formal parameter merely acts as an alias for the actual
parameter. Anytime the method/function uses the formal
parameter (for reading or writing), it is actually using the actual
parameter.
Java is strictly pass-by-value,
RAJESHREE KHANDE
78. Pass by value
78
In Java, Objects are passed by reference, and
primitives are passed by value.
This is half incorrect. Everyone can easily agree that
primitives are passed by value; there's no such thing
in Java as a pointer/reference to a primitive.
However, Objects are not passed by reference. A
correct statement would be Object references are
passed by value.
RAJESHREE KHANDE
79. this keyword
79
Sometimes a method will need to refer to the object
that invoked it.
To allow this, Java defines the this keyword.
this can be used inside any method to refer to the
current object.
That is, this is always a reference to the object on
which the method was invoked.
RAJESHREE KHANDE
80. this keyword
80
'this' is used for pointing the current class instance.
It can be used with variables or methods. Look into
the following example:
class Test
{ private int i=10;
public void m()
{ System.out.println(this.i);
}
}
RAJESHREE KHANDE
81. this keyword
81
this keyword is useful when we use same name
for parameter and instance variable
In the above code this is used for the current
instance.
Since this is instance of a class it cannot be used
inside a static method.
RAJESHREE KHANDE
82. this : Example
82
class Cat
{
int height weight;
public accept( int height, int weight)
{
this.height = height;
this.weight =weight;
}
}
RAJESHREE KHANDE
83. Static variable & Static Method
83
Like instance variable, static variable is declare inside
a class but outside any method.
Keyword static is used while declaring static variable.
Syntax
static int count;
static int max(int x, int y);
Static variable
Static method
RAJESHREE KHANDE
84. Static variable & Static Method
84
The static variable & static method belong to class
rather than object these variables is also called as
class variable and class method.
Static variable is defined when we have a variable
common to all instance of class.
These member are accessed with class name.
Syntax:
classname.staticVariableName;
classname.staticMethodName();
RAJESHREE KHANDE