0% found this document useful (0 votes)
53 views

Variables and Data Types

This document provides an overview of variables and their scope in Java programming. It discusses the three types of variables in Java: local variables, instance variables, and class (static) variables. Local variables are declared within methods and blocks while instance variables are declared within a class but outside methods. Class variables are declared with the static keyword and only one copy is created for the class. The document also covers variable initialization and provides examples of variable usage.

Uploaded by

indu kaur
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Variables and Data Types

This document provides an overview of variables and their scope in Java programming. It discusses the three types of variables in Java: local variables, instance variables, and class (static) variables. Local variables are declared within methods and blocks while instance variables are declared within a class but outside methods. Class variables are declared with the static keyword and only one copy is created for the class. The document also covers variable initialization and provides examples of variable usage.

Uploaded by

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

CSE310: Programming in Java

Topic: Variables & their Scope


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
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.
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);
}
}
• Which of the following is INCORRECT header
for the main method in java?

A. public static void main(String [] arg)


B. static public void main(String arg [])
C. public static void main(String...arg)
D. None of These
• Which of the following is NOT a feature of
Java?
A. secure    B. platform-dependent    
C. robust    D. multi-threaded
• Which of the following statement is TRUE about the following class?
        class A{} 

A. It can be saved in a file named as B.java and compiled using command


javac B.java
B. It can be saved only with name A.java and compiled using command
javac A.java
C. It can not be instantiated.
D. None of These  
• Which of the following statement is TRUE
about the following class?
        class A{}
A. Class will not compile
B. Class will compile but can not be executed
directly.
C. Instance of A CAN NOT be created.
D. Both B & C
• Which of the following statement(s) is/are
correct?
A. Java is portable and platform-dependent.
B.  Java was invented by James Gosling.
C. Java uses Interpreter for execution of
program.
D. Both B & C.
• Which of the following is full form of "JDK"
and "JVM"?
A. Java Deployment Kit, Java Virtual Mail 
B. Java Distribution Kit, Java Virtual
Machine  
C. Java Development Kit, Java Vital Machine
D. None of These
• In order for a java source code file,
containing the public class Test, to
successfully compile, which of the following
must be true?

A. It must have only one class in it. 


B. It must be named Test.java. 
C. It must import java.lang package. 
D. Both A & B 
• The following class is saved in a file named as Hello.java. Which of the
following is TRUE about it? 
public class A{}
A. It can be compiled using command javac A.java
B. It will be compiled using command javac A.java
C. It must be saved in a file named as A.java, otherwise it will not
compile.
D. None of These
• All the tools like javac. java etc available in
_____.
A. java --> jdk --> bin
B. java --> jre --> bin
C. java --> jdk --> jre --> bin
D. java --> jdk --> tools --> bin
• All the objects in Java are created inside ______ and local variable in
______.
A. Class Area, Heap
B. Heap, Class Area
C. Heap, Stack
D. Class Area, Stack
• Which of the following is the minimum
requirement for executing a java Program?
A. JDK         B. JVM        
C. JRE         D. Both JDK and JRE
• class Demo{ class Student {
• public static void main(String args[])int a; //initialized to zero
{ static int b; //initialized to zero only when
• Student s1 = new Student(); class is loaded not for each object created.
• s1.showData();
• Student s2 = new Student(); public void showData(){
• s2.showData(); a++;
• //Student.b++; b++;
• System.out.println("Value of a = "+a);
//s1.showData();
System.out.println("Value of b = "+b);
• } }
• }

}
print()
• print() method in Java is used to display a
text on the console. This text is passed as the
parameter to this method in the form of
String.
• This method prints the text on the console
and the cursor remains at the end of the text
at the console. The next printing takes place
from just here.
• void print(boolean b) – Prints a boolean
value.
• void print(char c) – Prints a character.
• void print(char[] s) – Prints an array of
characters.
• void print(double d) – Prints a double-precision
floating-point number.
• void print(float f) – Prints a floating-point
number.
• void print(int i) – Prints an integer.
• void print(long l) – Prints a long integer.
• void print(Object obj) – Prints an object.
• void print(String s) – Prints a string.
println()

• println() method in Java is also used to


display a text on the console. This text is
passed as the parameter to this method in
the form of String. This method prints the
text on the console and the cursor remains
at the start of the next line at the console.
The next printing takes place from next
line.
• void println() – Terminates the current line by writing the line
separator string.
• void println(boolean x) – Prints a boolean and then terminate the line.
• void println(char x) – Prints a character and then terminate the line.
• void println(char[] x) – Prints an array of characters and then
terminate the line.
• void println(double x) – Prints a double and then terminate the line.
• void println(float x) – Prints a float and then terminate the line.
• void println(int x) – Prints an integer and then terminate the line.
• void println(long x) – Prints a long and then terminate the line.
• void println(Object x) – Prints an Object and then terminate the line.
• void println(String x) – Prints a String and then terminate the line.
Formatted output in Java

• It is essential to print the output in a given


specified format. Most users are familiar
with printf function in C.
• Let us see discuss how we can format the
output in Java:
Data Types
Java defines eight primitive types of data: byte ,
short, int, long , char , float, double, and boolean.
These can be put in four groups:
Integers: This group includes byte , short, int, and long,
which are for whole-valued signed numbers.
Floating-point numbers: This group includes float and
double, which represent numbers with fractional
precision.
Characters: This group includes char , which represents
symbols in a character set, like letters and numbers.
Boolean: This group includes boolean , which is a
special type for representing true/false values.
• Non-primitive data types are called reference types because they refer to
objects.
• The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive
types are created by the programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive
types have all the same size.
Name, width and range of
Data Types
Name Width Range

byte 8 –128 to 127

short 16 –32,768 to 32,767

int 32 –2,147,483,648 to 2,147,483,647

long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float 32 1.4e–045 to 3.4e+038

double 64 4.9e–324 to 1.8e+308

char 16 0 to 65,536

Boolean true or false


Variables
• The variable is the basic unit of storage in a
Java program.
• A variable is defined by the combination of an
identifier, a type, and an optional initializer.
• Declaring a Variable:
– In Java, all variables must be declared before they
can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
• Here are several examples of variable declarations of various types. Note
that some include an initialization.

– int a, b, c; // declares three ints, a, b, and c.


– int d = 3, e, f = 5; // declares three more ints,
// initializing d and f.
– byte z = 22; // initializes z.
– double pi = 3.14159; // declares an approximation of
// pi.
– char x = 'x'; // the variable x has the value 'x'.
 Dynamic Initialization: Although the preceding examples have used only
constants as initializers, Java allows variables to be initialized dynamically,
using any expression valid at the time the variable is declared.
 For example, here is a short program that computes the length of the
hypotenuse of a right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

You might also like