SlideShare a Scribd company logo
1 of 36
Identifiers, Keywords and Types
Objectives
 Comments
 Identifiers
 Keywords
 Primitive types
 Literals
 Primitive variable and
Reference Variable
 Variables of class
type
 Construct an object
using new
 Default initialization
Comments
 Three permissible styles of comment in a
Java technology Program are
// Comment on one line
/* Comment on one or
more lines */
/** Documentation comment */
Semicolons, Blocks and Whitespace
 A statement is one or more lines of code terminated by a
semicolon (;)
total = a + b + c
+ d + e;
 A block is a collection of statements bound by opening
and closing braces
{
x = y + 1;
y = x + 1;
}
Semicolons, Blocks and Whitespace
 You can use a block in a class definition
Public class MyDate{
private int day;
private int month;
private int year;
}
 You can nest block statements
 Any amount of whitespace is allowed in a Java
Program
Identifiers
 Are names given to a variable, class or method
 Can start with a letter(alphabet), underscore(_), or
dollar sign($)
 Are case sensitive and have no maximum length
 Egs
identifier
username
user_name
_sys_var1
$change
Java Keywords
abstract do implements private this
boolean double import protected throw
break else instanceof public throws
byte extends int return transient
case false interface short true
catch final long static try
char finally native strictfp void
class float new super volatile
continue for null switch while
default if package synchronized
Primitive Types
 The Java programming language defines 8
primitive types
 Logical boolean
 Textual char
 Integral byte, short, int and long
 Floating double and Float
Logical-boolean
 The boolean data type has two literals,
true and false
 Example
//declare the variable flag and assign it the value true
boolean flag = true;
 Note:
There are no casts between integer and boolean types
Textual – char and String
char
 Represents a 16 bit Unicode character
 Must have its literal enclosed in single quotes(‘ ‘)
 Uses the following notations
‘a’ The letter a
‘t’ A tab
‘u????’ A specific unicode character
Eg. ‘u03A6’ is the Greek letter phi ϕ
Textual – char and String
String
 Is not a primitive data type, it is a class
 Has its literal enclosed in double quotes (“ ”)
“The quick brown fox jumps over the lazy dog”
 Example
String greeting=“Good Morning!!n”;
String errorMessage=“Record not found!”;
Integral- byte, short, int and long
 Uses 3 forms – Decimal, octal or hexadecimal
 2 The decimal value is two
 077 The leading 0 indicates an octal value
 0xBAAC The leading 0x indicates a hexadecimal value
 Default is int
 Defines long by using the letter L or l
Range of Integral data types
Type Name Length Range
byte 8 bits -27
to 27
-1
short 16 bits -215
to 215
-1
int 32 bits -231
to 231
-1
long 64 bits -263
to 263
-1
Floating Point – float and double
 Default is double
 Floating point literal includes either a decimal point or
one of the following:
 E or e (exponential value)
 F or f (float)
 D or d (double)
3.14 A simple floating point value (double)
6.02E23 A large floating point value
2.718F A simple float size value
123.4E+32D A Large double value with a redundant D
Floating point data type Ranges
 Note –
Floating point literals are double unless
explicitly declared as float
Type Name Length
float 32 Bits
double 64 Bits
Java Reference Types
 Beyond primitive types all others are reference
types
 A reference variable contains a handle to an object
class MyDate{
private int day = 1;
private int month=1;
private int year=2002;
}
public class TestMyDate{
public static void main(String args[]){
MyDate today = new MyDate();
}
}
Constructing and Initializing Objects
 Calling new Xxx() to allocate space for the new
object results in:
 Memory Allocation
 Explicit attribute initialization is performed
 A constructor is executed
 Variable assignment is made to reference the object
 Example
MyDate dob = new MyDate(17, 3, 1976);
Memory Allocation and Layout
 A declaration allocates storage only for a
reference:
MyDate dob = new MyDate(17,3,1976);
dob
 Use the new Operator to allocate space for MyDate:
????
????
0
0
0
dob
day
month
year
Explicit Attribute Initialization
????
1
1
2002
dob
day
month
year
MyDate dob = new myDate(17,3,1976);
• The default values are taken from the attribute
declaration in the class
Executing the Constructor
????
17
3
1976
dob
day
month
year
MyDate dob = new myDate(17,3,1976);
• Executes the matching constructor
Variable Assignment
0x91abcdef
17
3
1976
dob
day
month
year
MyDate dob = new myDate(17,3,1976);
• Assign newly created object to reference variable
Assignment of Reference Variables
int x = 7;
int y = x;
MyDate s = new MyDate(22, 7, 1974);
MyDate t = s;
t = new MyDate(22, 12, 1974);
•A variable of class type is a reference type
Pass-by-Value
 The Java programming language only passes
arguments by value
 When an object instance is passed as an
argument to a method, the value of the
argument is a reference to the object
 The contents of the object can be changed in
the called method, but the object reference is
never changed
PassTest.java
The this Reference
 Few uses of the this keyword
 To reference local attribute and method members
within a local method or constructor
 This is used to disambiguate a local method or
constructor variable from an instance variable
 To pass the current object as a parameter to
another method or constructor
MyDate.java
Java Coding Conventions
 Packages
package banking.objects;
 Classes
class SavingAccount;
 Interfaces
interface Account
 Methods
balance Account()
 Variables
currentCustomer()
 Constants
HEAD_COUNT
MAXIMUM_SIZE
Expressions and Flow Control
Objectives
 Distinguish Instance and local variables
 Identify and correct a Possible reference before
assignment
 Java Operators
 Legal and illegal assignments of primitive types
 Boolean expressions
 Assignment compatibility and casts
 Programming constructs
Variables and Scope
 Local variables are
 Variables that are defined inside a method and
are called local, automatic, temporary or stack
variables
 Variables that are created when the method is
executed are destroyed when the method is
exited
 Variables that must be initialized before they are
used or compile time errors will occur.
Variable Scope Example
Execution Stack
4
5
7
8
scopemain
this
i
j
this
i
j
firstMethod
secondMethod
1
ScopeExample
Heap Memory
i
TestScoping.java
Logical Opeators
 The boolean operators are
! – NOT & - AND
| - OR ^ - XOR
 The Short-Circuit operators are
&& - AND || - OR
 Ex
MyDate d;
If((d != null) && (d.day>31)){
//do something
}
Bitwise Operators
 The Integer bitwise operators are:
~ - Complement & - AND
^ - XOR | - OR
 Examples 0 0 1 0 1 1 0 1
~ 0 1 0 0 1 1 1 1 & 0 1 0 0 1 1 1 1
============ ===========
1 0 1 1 0 0 0 0 0 0 0 0 1 1 0 1
0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1
^ 0 1 0 0 1 1 1 1 | 0 1 0 0 1 1 1 1
========== ===========
0 1 1 0 0 0 1 0 0 1 1 0 1 1 1 1
Right-Shift Operators >> and >>>
 Arithmetic or signed right shift (>>) is used as
follows:
128 >> 1 returns 128/21
= 64
256 >> 4 returns 256/24
= 16
-256 >> 4 returns -256/24
= -16
 The sign bit is copied during the shift
 A logical or Unsigned right shift operator(>>>)
places zeros in the most significant bits
1010------ >> 2 gives 111010 -----
1010 ----- >>> 2 gives 001010 ----
String Concatenation with +
 The + operator
 Performs String Concatenation
 Produces a new String:
String salutation = “Dr.”;
String name = “James” + “ “ + “Gosling”;
String title=salutation+” “+name;
 One argument must be a String object
 Non-strings are converted to String objects automatically
Casting
 If information is lost in an assignment, the programmer must
confirm the assignment with a typecast.
 The assignment between long and int requires an explicit cast
long bigValue = 99L;
int squashed = bigValue; //Wrong, needs a cast
int squashed = (int) bigValue; //OK
int squashed = 99L; //Wrong needs a cast
int squashed=(int)99L; //OK
int squashed=99; //default integer literal
Promotion of Casting of Expressions
 Variables are automatically promoted to a longer form.
 Expression is assignment compatible if the variable type
is at least as large as the expression type
long bigval = 6; // 6 is an int type, OK
int smallval = 99L; // 99L is a long, illegal
double z = 21.414F; //12.414F is float OK
float z1 = 12.414; //12,414 is double, Illegal
Branching and Looping Statements
 The if, else Statement
 The switch Statement
 The for Statement
 The while Loop
 The do/while statement
 Special Loop Flow Control
break [label];
continue [label];
label: statement; // Where statement should be a loop

More Related Content

What's hot

Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
FALLEE31188
 

What's hot (19)

C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
C++ oop
C++ oopC++ oop
C++ oop
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
OOP C++
OOP C++OOP C++
OOP C++
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Oops concept in c#
Oops concept in c#Oops concept in c#
Oops concept in c#
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Visula C# Programming Lecture 8
Visula C# Programming Lecture 8Visula C# Programming Lecture 8
Visula C# Programming Lecture 8
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Object Oriented Programming With C++
Object Oriented Programming With C++Object Oriented Programming With C++
Object Oriented Programming With C++
 

Similar to java tutorial 2

Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
Walepak Ubi
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 

Similar to java tutorial 2 (20)

java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Cpprm
CpprmCpprm
Cpprm
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
P1
P1P1
P1
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Csharp4 basics
Csharp4 basicsCsharp4 basics
Csharp4 basics
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
introductory concepts
introductory conceptsintroductory concepts
introductory concepts
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C++ theory
C++ theoryC++ theory
C++ theory
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
presentation of java fundamental
presentation of java fundamentalpresentation of java fundamental
presentation of java fundamental
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 

java tutorial 2

  • 2. Objectives  Comments  Identifiers  Keywords  Primitive types  Literals  Primitive variable and Reference Variable  Variables of class type  Construct an object using new  Default initialization
  • 3. Comments  Three permissible styles of comment in a Java technology Program are // Comment on one line /* Comment on one or more lines */ /** Documentation comment */
  • 4. Semicolons, Blocks and Whitespace  A statement is one or more lines of code terminated by a semicolon (;) total = a + b + c + d + e;  A block is a collection of statements bound by opening and closing braces { x = y + 1; y = x + 1; }
  • 5. Semicolons, Blocks and Whitespace  You can use a block in a class definition Public class MyDate{ private int day; private int month; private int year; }  You can nest block statements  Any amount of whitespace is allowed in a Java Program
  • 6. Identifiers  Are names given to a variable, class or method  Can start with a letter(alphabet), underscore(_), or dollar sign($)  Are case sensitive and have no maximum length  Egs identifier username user_name _sys_var1 $change
  • 7. Java Keywords abstract do implements private this boolean double import protected throw break else instanceof public throws byte extends int return transient case false interface short true catch final long static try char finally native strictfp void class float new super volatile continue for null switch while default if package synchronized
  • 8. Primitive Types  The Java programming language defines 8 primitive types  Logical boolean  Textual char  Integral byte, short, int and long  Floating double and Float
  • 9. Logical-boolean  The boolean data type has two literals, true and false  Example //declare the variable flag and assign it the value true boolean flag = true;  Note: There are no casts between integer and boolean types
  • 10. Textual – char and String char  Represents a 16 bit Unicode character  Must have its literal enclosed in single quotes(‘ ‘)  Uses the following notations ‘a’ The letter a ‘t’ A tab ‘u????’ A specific unicode character Eg. ‘u03A6’ is the Greek letter phi ϕ
  • 11. Textual – char and String String  Is not a primitive data type, it is a class  Has its literal enclosed in double quotes (“ ”) “The quick brown fox jumps over the lazy dog”  Example String greeting=“Good Morning!!n”; String errorMessage=“Record not found!”;
  • 12. Integral- byte, short, int and long  Uses 3 forms – Decimal, octal or hexadecimal  2 The decimal value is two  077 The leading 0 indicates an octal value  0xBAAC The leading 0x indicates a hexadecimal value  Default is int  Defines long by using the letter L or l
  • 13. Range of Integral data types Type Name Length Range byte 8 bits -27 to 27 -1 short 16 bits -215 to 215 -1 int 32 bits -231 to 231 -1 long 64 bits -263 to 263 -1
  • 14. Floating Point – float and double  Default is double  Floating point literal includes either a decimal point or one of the following:  E or e (exponential value)  F or f (float)  D or d (double) 3.14 A simple floating point value (double) 6.02E23 A large floating point value 2.718F A simple float size value 123.4E+32D A Large double value with a redundant D
  • 15. Floating point data type Ranges  Note – Floating point literals are double unless explicitly declared as float Type Name Length float 32 Bits double 64 Bits
  • 16. Java Reference Types  Beyond primitive types all others are reference types  A reference variable contains a handle to an object class MyDate{ private int day = 1; private int month=1; private int year=2002; } public class TestMyDate{ public static void main(String args[]){ MyDate today = new MyDate(); } }
  • 17. Constructing and Initializing Objects  Calling new Xxx() to allocate space for the new object results in:  Memory Allocation  Explicit attribute initialization is performed  A constructor is executed  Variable assignment is made to reference the object  Example MyDate dob = new MyDate(17, 3, 1976);
  • 18. Memory Allocation and Layout  A declaration allocates storage only for a reference: MyDate dob = new MyDate(17,3,1976); dob  Use the new Operator to allocate space for MyDate: ???? ???? 0 0 0 dob day month year
  • 19. Explicit Attribute Initialization ???? 1 1 2002 dob day month year MyDate dob = new myDate(17,3,1976); • The default values are taken from the attribute declaration in the class
  • 20. Executing the Constructor ???? 17 3 1976 dob day month year MyDate dob = new myDate(17,3,1976); • Executes the matching constructor
  • 21. Variable Assignment 0x91abcdef 17 3 1976 dob day month year MyDate dob = new myDate(17,3,1976); • Assign newly created object to reference variable
  • 22. Assignment of Reference Variables int x = 7; int y = x; MyDate s = new MyDate(22, 7, 1974); MyDate t = s; t = new MyDate(22, 12, 1974); •A variable of class type is a reference type
  • 23. Pass-by-Value  The Java programming language only passes arguments by value  When an object instance is passed as an argument to a method, the value of the argument is a reference to the object  The contents of the object can be changed in the called method, but the object reference is never changed PassTest.java
  • 24. The this Reference  Few uses of the this keyword  To reference local attribute and method members within a local method or constructor  This is used to disambiguate a local method or constructor variable from an instance variable  To pass the current object as a parameter to another method or constructor MyDate.java
  • 25. Java Coding Conventions  Packages package banking.objects;  Classes class SavingAccount;  Interfaces interface Account  Methods balance Account()  Variables currentCustomer()  Constants HEAD_COUNT MAXIMUM_SIZE
  • 27. Objectives  Distinguish Instance and local variables  Identify and correct a Possible reference before assignment  Java Operators  Legal and illegal assignments of primitive types  Boolean expressions  Assignment compatibility and casts  Programming constructs
  • 28. Variables and Scope  Local variables are  Variables that are defined inside a method and are called local, automatic, temporary or stack variables  Variables that are created when the method is executed are destroyed when the method is exited  Variables that must be initialized before they are used or compile time errors will occur.
  • 29. Variable Scope Example Execution Stack 4 5 7 8 scopemain this i j this i j firstMethod secondMethod 1 ScopeExample Heap Memory i TestScoping.java
  • 30. Logical Opeators  The boolean operators are ! – NOT & - AND | - OR ^ - XOR  The Short-Circuit operators are && - AND || - OR  Ex MyDate d; If((d != null) && (d.day>31)){ //do something }
  • 31. Bitwise Operators  The Integer bitwise operators are: ~ - Complement & - AND ^ - XOR | - OR  Examples 0 0 1 0 1 1 0 1 ~ 0 1 0 0 1 1 1 1 & 0 1 0 0 1 1 1 1 ============ =========== 1 0 1 1 0 0 0 0 0 0 0 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 ^ 0 1 0 0 1 1 1 1 | 0 1 0 0 1 1 1 1 ========== =========== 0 1 1 0 0 0 1 0 0 1 1 0 1 1 1 1
  • 32. Right-Shift Operators >> and >>>  Arithmetic or signed right shift (>>) is used as follows: 128 >> 1 returns 128/21 = 64 256 >> 4 returns 256/24 = 16 -256 >> 4 returns -256/24 = -16  The sign bit is copied during the shift  A logical or Unsigned right shift operator(>>>) places zeros in the most significant bits 1010------ >> 2 gives 111010 ----- 1010 ----- >>> 2 gives 001010 ----
  • 33. String Concatenation with +  The + operator  Performs String Concatenation  Produces a new String: String salutation = “Dr.”; String name = “James” + “ “ + “Gosling”; String title=salutation+” “+name;  One argument must be a String object  Non-strings are converted to String objects automatically
  • 34. Casting  If information is lost in an assignment, the programmer must confirm the assignment with a typecast.  The assignment between long and int requires an explicit cast long bigValue = 99L; int squashed = bigValue; //Wrong, needs a cast int squashed = (int) bigValue; //OK int squashed = 99L; //Wrong needs a cast int squashed=(int)99L; //OK int squashed=99; //default integer literal
  • 35. Promotion of Casting of Expressions  Variables are automatically promoted to a longer form.  Expression is assignment compatible if the variable type is at least as large as the expression type long bigval = 6; // 6 is an int type, OK int smallval = 99L; // 99L is a long, illegal double z = 21.414F; //12.414F is float OK float z1 = 12.414; //12,414 is double, Illegal
  • 36. Branching and Looping Statements  The if, else Statement  The switch Statement  The for Statement  The while Loop  The do/while statement  Special Loop Flow Control break [label]; continue [label]; label: statement; // Where statement should be a loop