100% found this document useful (1 vote)
92 views

Variables and Data Types

This document discusses variables and their scope in Java. It outlines three types of variables: 1) Local variables, which are declared in methods, constructors, or blocks and only visible within that block. 2) Instance variables, which are declared in a class but outside methods and can be accessed from any non-static method using an object reference. 3) Class variables, also known as static variables, which are declared with the static keyword and shared among all objects of a class.

Uploaded by

nighat
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
92 views

Variables and Data Types

This document discusses variables and their scope in Java. It outlines three types of variables: 1) Local variables, which are declared in methods, constructors, or blocks and only visible within that block. 2) Instance variables, which are declared in a class but outside methods and can be accessed from any non-static method using an object reference. 3) Class variables, also known as static variables, which are declared with the static keyword and shared among all objects of a class.

Uploaded by

nighat
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

CSE310: Programming in Java

Topic: Variables & their Scope

By
Amarinder Kaur
Asst. Professor, LPU
Outlines [Expected Time: 1 Hours]

• Variables and their Scope


• Local Variable
• Instance Variable
• Class Variable
Variables
 Variable are the data members or the fields defined
inside a class.

 There are three types of variables:


 Local Variable
 Instance Variable
 Class Variable

*This and super keyword is not used in static methods.


*Non static methods or data members cant access directly in
static methods.
Local Variable
 Local variables are those data members which are
declared in methods, constructors, or blocks.

 They are created only when the method, constructor or


block is executed and destroyed as soon as the
execution of that block is completed.

 So the visibility of local variables is inside the block


only, they can’t be accessed outside the scope of that
block.
Important

 Access modifiers are NOT ALLOWED with local variables.

 Local variables are created in STACK.

 Default value is NOT ASSIGNED to the local variables in


Java.
Instance Variables
• Variables which are declared in a class, but outside a
method, constructor or any block are known as instance
variables.

• They are created inside the object in heap.

• Each object has its own set of instance variables and


they can be accessed/modified separately using object
reference.
• Instance variables are created when an object is created
with the use of the 'new' keyword and destroyed when the
object is destroyed.

• Access modifiers can be used with instance variables.

• Instance variables have default values.

• For numbers the default value is 0,


• for Booleans it is false
• and for object references it is null.
Class Variable
 Class variables are also known as static variables.
 Variable which are declared in a class, but outside a
method, constructor or a block and qualified with ‘static’
keyword are known as class variables.

 Only one copy of each class variable is created, regardless


of how many objects are created from it.

 Static variables can be accessed by calling with the class


name.
ClassName.VariableName
 Static variables are created with the start of execution of a
program and destroyed when the program terminates.

 Default values are same as instance variables.

 A public static final variable behaves as a CONSTANT in


Java.

 Static variables can be initialized using static block also.


Variable Initialization
Local variables must be initialized explicitly by the
programmer as the default values are not assigned to them
where as the instance variables and static variables are
assigned default values if they are not assigned values at the
time of declaration.
Data Type Default Value Default size

boolean false 1 bit


char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
1. Numeric datatypes
2. Character datatype
char letter = 'A';
char numChar = '4';

Java supports Unicode


65,536 characters possible in a 16-bit encoding
16-bit Unicode takes two bytes.
 The range of a char is 0 to 65,536. There are no negative chars.
The standard set of characters known as ASCII still ranges from 0 to 127 as always.
The increment and decrement operators can also be used on char variables to get the next
or preceding Unicode character

.
2. Character datatype

Escape Sequences for special characters


.
3. Boolean datatype

The boolean data type is used to declare Boolean variables.

A boolean variable can hold one of the two values: true and false

true and false are literals

4. float g= 34.5//error if we are writing in this way JVM convert into double
so float g= 34.5f
Automatic type promotion in expressions

Consider the following line of code:

byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!

The code is attempting to store 50 * 2, a perfectly valid byte value, back into a
byte variable. However, because the operands were automatically promoted to
int when the expression was evaluated, the result has also been promoted to
int.
Thus, the result of the expression is now of type int, which cannot be assigned
to a byte without the use of a cast.
Type Conversion, Casting and Promotion

1. Numeric Type Conversions

Consider the following statements:


byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

When performing a binary operation involving two operands of different types,


Java automatically converts the operand based on the following rules:
 
1. All byte, short, and char values are promoted to int.
2. if one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands is double, the result is double.
   
Type Conversion, Casting and Promotion

1. Numeric Type Conversions

The result of 1/2 is 0 but result of 1.0/2 is 0.5


range increases

byte, short, int, long, float, double


Casting converts a value of one data type into a value of another data type
* widening a type – 1. Casting a variable of a type with a small range to a variable of a type with a
larger range
2. can be performed automatically (implicit casting)
* narrowing a type – 1. Casting a variable of a type with a large range to a variable of a type with a
smaller range
2. must be performed explicitly (explicit casting)

Note: Not all the types are compatible,Ex. boolean is not compatible with numeric or char
types.
Type Conversion, Casting and Promotion

1. Numeric Type Conversions

The result of 1/2 is 0 but result of 1.0/2 is 0.5


range increases

byte, short, int, long, float, double

Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)

What is wrong? int x = 5 / 2.0; It would work if int x = (int)( 5 / 2.0 );


• Sequence:
• byte short int  long float  double
• byte char int  long float  double
Either char and short need same memory but we need their explicit
typecasting.

Char c=‘4’;
Short s=(short)c;

Short s=78;
Char c=(char)s;
Type Conversion, Casting and Promotion

2. Character Type Conversions


 A char can be cast into any numeric type, and vice versa
 When an integer is cast into a char, only its lower 16 bits of data are used; the other
part is ignored
char ch = (char)0XAB0041; // the lower 16 bits hex code 0041 is assigned to ch
System.out.println(ch); // ch is character A

int i = 65;
char ch = (char)i;
System.out.println(ch); // ch is character A
 When a floating-point value is cast into a char, the floating-point value is first cast into
an int, which is then cast into a char
char ch = (char)65.25; // decimal 65 is assigned to ch
System.out.println(ch); // ch is character A
 Implicit casting can be used if the result of a casting fits into the target
variable. Otherwise, explicit casting must be used.
• int i = 'a'; //correct
• byte b = i; // incorrect byte b = (byte) i; //correct
Type Conversion, Casting and Promotion

2. Character Type Conversions

All numeric operators can be applied to char operands. A char operand is automatically
cast into a number if the other operand is a number or a character. If the other operand
is a string, the character is concatenated with the string.

class Test
{ public static void main(String [] ar)
{
int i = '2' + '3'; // (int)'2' is 50 and (int)'3' is 51
System.out.println("i is " + i); // i is 101
int j = 2 + 'a'; // (int)'a' is 97
System.out.println("j is " + j); // j is 99
System.out.println(j + " is the Unicode for character "+ (char)j);
System.out.println("Chapter " + '2');
}
}
class Promote{
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println("result = " + result);
}
}
Conversion from int to byte

• Actual method:
example : int i=300 ;
byte b=(byte)i;
Represent i into 32 bits then take 8 bits from right side and that will be
our output
Shortcut:
Output:
(If positive number)-256
(if negative number)+ 256

Exmple:300-256=44
-218+256=38
Examples:

• Int to byte:
1. int x=130;
byte b =(byte)x
SOP(b);
2. int x=132;
byte b =(byte)x
SOP(b);
3. int x=150;
byte b =(byte)x
SOP(b);
Continue…

4. int x=257;
byte b =(byte)x
SOP(b);
5. int x=-482;
byte b =(byte)x
SOP(b);
6. int x=-996;
byte b =(byte)x
SOP(b);
Casting Double to Byte
Float to int
1. float a=3.14f;
int x=(int) a
SOP(x);

2.Int i =132;
short s=15;
byte b=(byte)i;
int x=b+s
SOP(x);
Double to char
1.double d=65.25;
char c =(char)d;
SOP(c);

1. int i = 50000;
short s=i;
SOP(s);
Byte to short and vice versa

1.byte b =123;
short s =999;
s=b; //implicit conversion
SOP(s);
2. byte b =123;
short s =999;
b=s; //explicit conversion
SOP(b);
1. int i = ‘2’; //implicit converted into char to int
SOP(i);
2. Char a= ’49’; // error because 49 is not a single char. Consider
//collection of char
3. int i=50;
char c=(char)i;
System.out.println("hello world "+c);
4. Int a=5,b=6;
System.out.println(a+b+"hello world "+a+b);
int i=50;
char c=(char)i;
short s;
s=(short)c;

System.out.println(c+s+“ hello world "+c+s);


Brainstorming 1
What will be the output of the following Program?

class VariableDemo
{
public static void main(String [] rk)
{
public int x = 10;
System.out.print(x);
}
}
Brainstorming 2
What will be the output of the following Program?

class VariableDemo
{
static int x;
public static void main(String [] rk)
{
int x;
System.out.print(x);
}
}
Brainstorming 3
What will be the output of the following Program?

class VariableDemo
{
static int x;
public static void main(String [] rk)
{
int x;
System.out.print(VariableDemo.x);
}
}
Brainstorming 3
What will be the output of the following Program?

class VariableDemo
{
int x;
public static void main(String [] rk)
{
int x;
System.out.print(this.x); //Class variable
}
}

You might also like