Core Java
Lesson 2—Working with Java Variables
© Simplilearn. All rights reserved.
Learning Objectives
At the end of this lesson, you should be able to:
Declare and initialize variables (including casting of primitive data types)
Explain object reference variables and primitive variables
Explain how to write and read from object fields
Explain an object's lifecycle
Explain how to convert Wrapper class to Primitive class and vice versa
Java Variables
Topic 1—Declaring and Initializing Variables
Declaring and Initializing Variables
A variable is a named storage that a program uses.
Each variable has a specific type, which determines the value that can be stored within it and the
operations that can be applied to it.
You must declare a variable before you use it.
A variable can be declared using the eight primitive data types: byte, short, int, long, float, double,
char, or boolean.
Declaring a variable only reserves a name and some memory for it, whereas initializing the
variable gives the variable a value.
Declaring and Initializing Variables (Contd.)
Basic form of a variable declaration:
Name of the variable
data type variable [ = value][, variable [ = value] ...] ;
One of Java's datatypes, Value of the variable
for example “int”
To declare more than one variable of the specified type, use a
comma-separated list.
Declaring and Initializing Variables (Contd.)
Syntax to declare a variable:
int a;
data type
variable name
Examples:
int a, b, c; Declares three integers a, b, and c
int a = 10, b = 20, c; Initialization, where “int” variables are given values
byte B = 25; Initialization, where a “byte” variable b is given a value of 25
Declaring and Initializing Variables (Contd.)
There are three types of variables in Java, which include:
Local variables—A variable declared inside methods, constructors, or blocks
Instance variables—
• A variable that is declared inside the class but outside the method
• A variable that is not declared as static
Class/Static variables—A variable that is declared as static and that cannot be local
Examples:
class A{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
}//end of class
Java Variables
Topic 2—Primitive Data Types
Primitive Data Types
byte
• An 8-bit integer
short
• With default value of 0
int • Ranges between 128 and 127
long
Example:
float byte a=100
double
boolean
char
Primitive Data Types
byte
• A 16-bit integer
short
• With default value of 0
int • Ranges between 32768 and 32767
long
Example:
float short s = 10000
double
boolean
char
Primitive Data Types
byte
• A 32-bit integer
short
• With default value of 0
int • Ranges between 2147483648 and 2147483647
long
Example:
float int a = 100000
double
boolean
char
Primitive Data Types
byte
• A 64-bit integer
short
• With default value of 0L
int • Ranges between 2^63 and 2^63 -1
long
Example:
float long a = 100000L
double
boolean
char
Primitive Data Types
byte
• A 32-bit floating point
short
• With default value of 0.0f
int • Ranges between 6 and 7 decimals
long
Example:
float float f1 = 234.5f
double
boolean
char
Primitive Data Types
byte
• A 64-bit floating point
short
• With default value of 0.0d
int • 15 decimals
long
Example:
float double d1 = 123.4
double
boolean
char
Primitive Data Types
byte
• A data type of one bit
short
• With default value of false
int • True or False
long
Example:
float boolean one = true
double
boolean
char
Primitive Data Types
byte
• A single 16-bit Unicode character
short
• Ranges between ‘\u0000’ (0) and \uffff (65535)
int
Example:
long
char letterA = 'A'
float
double
boolean
char
Primitive Types Casting
Converting the value of one primitive data type to another primitive data type is known as
primitive casting
In Java, primitive type casting can be classified into:
Widening casting (implicit casting)
Narrowing casting (explicit casting)
Except boolean, all the other seven primitive data types can be assigned to
one another either implicitly or explicitly.
Primitive Types Casting (Contd.)
Widening casting (implicit casting)
• A process of assigning a data type of lower size (occupying less memory) to a data type of higher size
• This is done implicitly by the JVM and is also know as automatic type conversion
• Takes place when:
o The two data types are compatible
o The target data type is larger than the source data type
byte short int long float double
Widening casting
Primitive Types Casting (Contd.)
Widening casting (implicit casting)
Examples
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l); Output:
System.out.println("Float value "+f); Int value 100
} Long value 100
Float value 100.0
}
Primitive Types Casting (Contd.)
Narrowing casting (explicit casting)
• A process of assigning a larger type value to a data type of smaller data type
• This is not done implicitly by the JVM and requires a casting operation to be performed by the programmer
double float long int short byte
Narrowing casting
Primitive Types Casting (Contd.)
Narrowing casting (explicit casting)
Examples
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i); Output:
Double value 100.04
} Long value 100
Int value 100
}
Core Java
Topic 3—Read and Write Java Object Fields
Reading and Writing Java Object Fields
We have fields within our class as variables, and these variables become object or reference
variables when inside the instance of a class.
Often we can add more control by setting the modifier to private. We can read and write to fields
via methods known as “getters” and “setters.”
Reading and Writing Java Object Fields (Contd.)
Provide public methods through which new values can be assigned to variables and the values they
hold can be accessed. These methods are known as get and set methods.
Get methods: Provide access to the value a variable holds.
Set methods: Assign values to the variables of the objects.
Reading and Writing Java Object Fields (Contd.)
Example: Using get and set method
package test;
import java.util.Scanner;
public class MainMethod {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
User k = new User();
System.out.println("enter first name of user");
k.setFirstName(s.nextLine());
System.out.println("enter first name of user");
k.setLastName(s.nextLine());
System.out.println("eneter age of user");
k.setAge(s.nextInt());
System.err.println("information of existing user");
System.out.println("First Name"+"\t"+"Last Name"+"\t"+"age");
System.out.println(k.getFirstName()+"\t"+k.getLastName()+"\t"+k.getAge());
}
}
Reading and Writing Java Object Fields (Contd.)
The ObjectOutputStream class allows you to write primitive data types and Java objects to an
OutputStream.
Objects that support the java.io.Serializable interface can only be written to streams
The ObjectInputStream class deserializes objects and primitive data written using an
ObjectOutputStream
Reading and Writing Java Object Fields (Contd.)
Example
import java.io.*;
class Persist{
public static void main(String args[])throws Exception{
Student s1 =new Student(211,“John");
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
In the above example, the objects in the Student class are sterilized.
Reading and Writing Java Object Fields (Contd.)
The ObjectInputStream class deserializes objects and primitive data written using an
ObjectOutputStream.
Example
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close(); Output:
}
211 John
}
Reading objects in Java is similar to writing objects using ObjectOutputStreamObjectInputStream
Core Java
Topic 4—Object Lifecycle
Object Lifecycle
An object lifecycle involves 7 stages:
Once an object is created, it is
assigned to some variable.
public Cat getCat(){
Cat cat= new Cat(); // creation
of Object Cat
return cat;
}
Object Lifecycle
An object lifecycle involves 7 stages:
If an object is held with a
strong reference, then it is
considered to be “In Use.”
Cat = new Cat();// Here, cat is
strong reference to Cat Object
Object Lifecycle
An object lifecycle involves 7 stages:
An object is in invisible state when there is no strong reference to access the program.
public void execute(){
try{
Object ob = new Object();
}catch(Exception e){
e.printStackTrace();
}
while(true){
…………….
}
}
Object Lifecycle
An object lifecycle involves 7 stages:
An Object becomes unreachable when
there are no references and it can’t be
accessed.
Cat = new Cat(); //line 1
cat = null; //line 2
Object Lifecycle
An object lifecycle involves 7 stages:
Once we observe an unreachable
object, it moves to the collected
state.
It is a phase before deallocation.
Object Lifecycle
An object lifecycle involves 7 stages:
Once an object is collected
and it has a finalize method, it
is moved into finalize state.
Object Lifecycle
An object lifecycle involves 7 stages:
The deallocated state is the final
step in garbage collection. If an
object is still unreachable, then it
is the state for deallocation.
Core Java
Topic 5—Wrapper Class
Conversion from Primitive to Wrapper
Using a wrapper class to convert primitive into object is known as autoboxing.
Example to convert Primitive to Wrapper:
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a); //converting int into Integer
Integer j=a; //autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}}
Output:
20 20 20
Conversion from Wrapper to Primitive
Wrapper class provides the mechanism to convert wrapper to primitive is known as unboxing.
Example to convert Wrapper to Primitive:
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue(); //converting Integer to int
int j=a; //unboxing, now compiler will write a.intValue() internally
System.out.println(a+" "+i+" "+j);
}}
Output:
333
List of Primitive Types and Their Wrapper Classes
There are 8 primitive types of java.lang package, which include:
Primitive Wrapper Class Constructor Argument
boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double, or String
double Double double or String
long Long long or String
short Short short or String
Key Takeaways
A variable can be declared using the eight primitive data types: byte, short, int,
long, float, double, char, or boolean.
Declaring a variable only reserves a name and some memory for it. However,
initializing the variable gives the variable a value.
Syntax to declare a variable in java: data type is followed by variable name.
There are three types of variables in Java: Local Variables, Instance Variables,
and Static Variables
Converting the value of one primitive data type to another primitive data type is
known as primitive casting
In Java, primitive type casting can be classified into Widening casting and
Narrowing casting
Serialization is a process of writing the state of an object into a byte stream.
Once objects are converted into a byte-stream, they can be written to a file.
Quiz
QUIZ
Which of these data types are of 16bit?
1
a. byte
b. int
c. char
d. short
QUIZ
Which of these data types are of 16bit?
1
a. byte
b. int
c. char
d. short
The correct answer is c and d.
byte is 8-bit and short is 16-bit in Java. Java supports uni-code character set; that’s why char is 16-bit
too.
QUIZ
Conversion of larger data type to smaller data type is called:
2
a. Internal casting
b. Implicit casting
c. External casting
d. Explicit casting
QUIZ
Conversion of larger data type to smaller data type is called:
2
a. Internal casting
b. Implicit casting
c. External casting
d. Explicit casting
The correct answer is c. External casting
Conversion of larger data type to smaller data type is called external casting.
Thank You