SlideShare a Scribd company logo
1 of 85
Contents
1
 Data types in Java
 Strings & Characters
 Arithmetic Operators & Expressions
 Type Conversion
 Comments
 Arrays
 Keywords
RAJESHREE KHANDE
Data Types, Variables, and
Constants
2
 Declaring Variables
 Primitive Data Types
 Initial Values and Literals
 String Literals and Escape Sequences
 Constants
RAJESHREE KHANDE
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
 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
 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
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
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
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
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
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
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
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
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
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
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
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
Relational Operators
Operator Meaning
== Equal to
!= Not equal to
>= Greater than equal to
<= Less than equal to
< Less than
> Greater than
33RAJESHREE KHANDE
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
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
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
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
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
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
while loops
40
while(response == 1)
{
System.out.print( “ID =” + userID[n]);
n++;
response = readInt( “Enter”);
}
RAJESHREE KHANDE
do {… } while loops
41
do
{
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);
RAJESHREE KHANDE
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Class
56
Circle
centre
radius
circumference()
area()
RAJESHREE KHANDE
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
this : Example
82
class Cat
{
int height weight;
public accept( int height, int weight)
{
this.height = height;
this.weight =weight;
}
}
RAJESHREE KHANDE
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
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
Static variable & Static Method
85
Class MathOp
{
static float mul(float x, float
y)
{
return x*y;
}
static float divide(float x, float
y)
{
return x/y;
}
}
Class MathApp
{
public static void main(String
args[])
{
float a= MathOp.mul(4.0,5.0);
float b= MathOp.divide(a,2.0);
System.out.println( “a = ” + a);
System.out.println( “b = ” + b);
}
}
RAJESHREE KHANDE

More Related Content

What's hot

Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vb
alldesign
 

What's hot (19)

M C6java2
M C6java2M C6java2
M C6java2
 
Introduction to c
Introduction to cIntroduction to c
Introduction to c
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
M C6java7
M C6java7M C6java7
M C6java7
 
Daa chapter4
Daa chapter4Daa chapter4
Daa chapter4
 
Selection & Making Decisions in c
Selection & Making Decisions in cSelection & Making Decisions in c
Selection & Making Decisions in c
 
Chapter 7 expressions and assignment statements ii
Chapter 7 expressions and assignment statements iiChapter 7 expressions and assignment statements ii
Chapter 7 expressions and assignment statements ii
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
 
Unit 2.5
Unit 2.5Unit 2.5
Unit 2.5
 
A Role of Lexical Analyzer
A Role of Lexical AnalyzerA Role of Lexical Analyzer
A Role of Lexical Analyzer
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Keywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.netKeywords, identifiers and data type of vb.net
Keywords, identifiers and data type of vb.net
 
Data types in java | What is Datatypes in Java | Learning with RD | Created b...
Data types in java | What is Datatypes in Java | Learning with RD | Created b...Data types in java | What is Datatypes in Java | Learning with RD | Created b...
Data types in java | What is Datatypes in Java | Learning with RD | Created b...
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
 
LISP: Type specifiers in lisp
LISP: Type specifiers in lispLISP: Type specifiers in lisp
LISP: Type specifiers in lisp
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
LISP:Predicates in lisp
LISP:Predicates in lispLISP:Predicates in lisp
LISP:Predicates in lisp
 
Data types and operators in vb
Data types and operators  in vbData types and operators  in vb
Data types and operators in vb
 

Similar to Dr. Rajeshree Khande : Java Basics

Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
Abed Bukhari
 
1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf
Javier Crisostomo
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
GANESHBABUVelu
 

Similar to Dr. Rajeshree Khande : Java Basics (20)

Java chapter 2
Java chapter 2Java chapter 2
Java chapter 2
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
 
vb.net.pdf
vb.net.pdfvb.net.pdf
vb.net.pdf
 
Java: Primitive Data Types
Java: Primitive Data TypesJava: Primitive Data Types
Java: Primitive Data Types
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
Php intro by sami kz
Php intro by sami kzPhp intro by sami kz
Php intro by sami kz
 
Literals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiersLiterals, primitive datatypes, variables, expressions, identifiers
Literals, primitive datatypes, variables, expressions, identifiers
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
Lecture no 1
Lecture no 1Lecture no 1
Lecture no 1
 
Token and operators
Token and operatorsToken and operators
Token and operators
 
1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf1_1_python-course-notes-sections-1-7.pdf
1_1_python-course-notes-sections-1-7.pdf
 
Pointers
PointersPointers
Pointers
 
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.) I...
 
C# overview part 1
C# overview part 1C# overview part 1
C# overview part 1
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Java Programming
Java Programming Java Programming
Java Programming
 
C tutorial
C tutorialC tutorial
C tutorial
 
Chapter 2 java
Chapter 2 javaChapter 2 java
Chapter 2 java
 

More from DrRajeshreeKhande

More from DrRajeshreeKhande (20)

.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
Exception Handling in .NET F#
Exception Handling in .NET F#Exception Handling in .NET F#
Exception Handling in .NET F#
 
.NET F# Events
.NET F# Events.NET F# Events
.NET F# Events
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
F# Console class
F# Console classF# Console class
F# Console class
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
F# array searching
F#  array searchingF#  array searching
F# array searching
 
Net (f#) array
Net (f#)  arrayNet (f#)  array
Net (f#) array
 
.Net (F # ) Records, lists
.Net (F # ) Records, lists.Net (F # ) Records, lists
.Net (F # ) Records, lists
 
MS Office for Beginners
MS Office for BeginnersMS Office for Beginners
MS Office for Beginners
 
Java Multi-threading programming
Java Multi-threading programmingJava Multi-threading programming
Java Multi-threading programming
 
Java String class
Java String classJava String class
Java String class
 
JAVA AWT components
JAVA AWT componentsJAVA AWT components
JAVA AWT components
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
Dr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive inputDr. Rajeshree Khande Java Interactive input
Dr. Rajeshree Khande Java Interactive input
 
Dr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to javaDr. Rajeshree Khande :Intoduction to java
Dr. Rajeshree Khande :Intoduction to java
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Recently uploaded (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 

Dr. Rajeshree Khande : Java Basics

  • 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
  • 33. Relational Operators Operator Meaning == Equal to != Not equal to >= Greater than equal to <= Less than equal to < Less than > Greater than 33RAJESHREE 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
  • 40. while loops 40 while(response == 1) { System.out.print( “ID =” + userID[n]); n++; response = readInt( “Enter”); } 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
  • 85. Static variable & Static Method 85 Class MathOp { static float mul(float x, float y) { return x*y; } static float divide(float x, float y) { return x/y; } } Class MathApp { public static void main(String args[]) { float a= MathOp.mul(4.0,5.0); float b= MathOp.divide(a,2.0); System.out.println( “a = ” + a); System.out.println( “b = ” + b); } } RAJESHREE KHANDE