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

Chapter 2 Variables&Scanner

Uploaded by

voila.alberto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Chapter 2 Variables&Scanner

Uploaded by

voila.alberto
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Variables

A variable is a named location that stores a value. Values may be numbers, text,
images, sounds, and other types of data. To store a value, you first have to declare a
variable.

String message;

This statement is a declaration, because it declares that the variable named message
has the type String. Each variable has a type that determines what kind of values it can
store. For example, the int type can store integers, and the char type can store
characters.

Now that we have declared variables, we want to use them to store values. We do that
with an assignment statement.

message = "Hello!"; // give message the value "Hello!"


hour = 11; // assign the value 11 to hour
minute = 59; // set minute to 59

 When you declare a variable, you create a named storage location.


 When you make an assignment to a variable, you update its value.

As a general rule, a variable has to have the same type as the value you assign to it.
For example, you cannot store a string in minute or an integer in message.
Variable declaration and initialization examples

int age; // only declaration, here age is a variable of the data type int
double salary; // salary is a variable of data type double
int age = 30; // declaration and initialization. Here 30 is called literal
double salary = 100000.00;
char c = ‘a’; // enclosed in single quote
String s = “a”; // enclosed in double quote
String employeeId = “1234”; // even, numerals are enclosed in double quote
float sum = 10.00f; // suffix f indicates float
long password = 123456789123456789L;
String s = null; // null is a literal
boolean valid = true; // true is a literal

Types of Variable

There are three types of variables in java:

o local variable

o instance variable
o static variable
1) Local Variable
 Local variables are declared in methods, constructors, or blocks.

 Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor, or block.

 Access modifiers cannot be used for local variables.

 Local variables are visible only within the declared method, constructor, or block.

 Local variables are implemented at stack level internally.

 There is no default value for local variables, so local variables should be declared
and an initial value should be assigned before the first use.

2) Instance Variable
 Instance variables are declared in a class, but outside a method, constructor or
any block.

 When a space is allocated for an object in the heap, a slot for each instance
variable value is created.

 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.

 Access modifiers can be given for instance variables.

 The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access level).
However, visibility for subclasses can be given for these variables with the use of
access modifiers.

 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside
the class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name. ObjectReference.VariableName.

3) Static variable
 Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.

 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.

 Static variables are rarely used other than being declared as constants. Constants
are variables that are declared as public/private, final, and static. Constant
variables never change from their initial value.

 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.

 Static variables are created when the program starts and destroyed when the
program stops.

 Visibility is similar to instance variables. However, most static variables are


declared public since they must be available for users of the class.

 Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values can
be assigned in special static initializer blocks.

 Static variables can be accessed by calling with the class


name ClassName.VariableName.
 When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final,
the naming syntax is the same as instance and local variables.

Example to understand the types of variables in java

1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Data types

Data type specifies the size and type of values that can be stored in an identifier. The
Java language is rich in its data types. Different data types allow you to select the type
appropriate to the needs of the application.

Data types in Java are classified into two types:

1. Primitive—which include Integer, Character, Boolean, and Floating Point.


2. Non-primitive—which include Classes, Interfaces, and Arrays.

Primitive Data Types

There are eight primitive data types in Java


 Boolean
 Byte
 Char
 Double
 Float
 Int
 Long
 Short

1. Integer

Integer types can hold whole numbers such as 123 and −96. The size of the values that
can be stored depends on the integer type that we choose.

Type Size Range of values that can be stored

byte 1 byte −128 to 127

short 2 bytes −32768 to 32767

int 4 bytes −2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807

The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits
required. For example, the byte data type requires 1 byte = 8 bits. Therefore, the range
of values that can be stored in the byte data type is −(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127
2. Floating Point

Floating point data types are used to represent numbers with a fractional part. Single
precision floating point numbers occupy 4 bytes and Double precision floating point
numbers occupy 8 bytes. There are two subtypes:

Type Size Range of values that can be stored

float 4 bytes 3.4e−038 to 3.4e+038

double 8 bytes 1.7e−308 to 1.7e+038

3. Character

It stores character constants in the memory. It assumes a size of 2 bytes, but basically it
can hold only a single character because char stores unicode character sets. It has a
minimum value of ‘u0000’ (or 0) and a maximum value of ‘uffff’ (or 65,535, inclusive).

4. Boolean

Boolean data types are used to store values with two states: true or false.

Operators

Java supports wealth of operators that allow a program to manipulate values of


variables

Assignment Operators:
Arithmetic Operators:
Unary and Equality Operators:

Relational and Logical Operators:


Bitwise and Shift Operators:

Wrapper Classes

Primitive values (like ints, doubles, chars etc) do not provide methods. For example, you
can't call equals on an int:

int i = 5;
System.out.println(i.equals(5)); // compiler error

But for each primitive type, there is a corresponding class in the Java library, called a
wrapper class. The wrapper class for char is called Character; for int it's called Integer.
Other wrapper classes include Boolean, Long, Short, Byte, Float and Double. They are
in the java.lang package, so you can use them without importing them.

The list of eight wrapper classes are given below:


Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Wrapper classes provide methods for converting strings to other types. For example,
Integer.parseInt converts a string to (you guessed it) an integer:

String str = "12345";


int num = Integer.parseInt(str);

In this context, parse means something like read and translate".


The other wrapper classes provide similar methods, like Double.parseDouble and
Boolean.parseBoolean. They also provide toString, which returns a string
representation of a value:

int num = 12345;


String str = Integer.toString(num);

The result is the string "12345".


Autoboxing and Unboxing

Java 1.5 and later versions of it supports automatic conversion of primitive data types to
their wrapper classes in assignment statements and method as well as constructor
invocations. This conversion is known as auto-boxing or simply boxing. Java also
supports automatic unboxing, where wrapper types are automatically converted into
their primitive equivalents.

Wrapper class Example: Primitive to Wrapper

1. public class WrapperExample1{


2. public static void main(String args[]){
3. //Converting int into Integer
4. int a=20;
5. Integer i=Integer.valueOf(a);//converting int into Integer
6. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}

Output:

20 20 20

Wrapper class Example: Wrapper to Primitive

1. public class WrapperExample2{


2. public static void main(String args[]){
3. //Converting Integer to int
4. Integer a=new Integer(3);
5. int i=a.intValue();//converting Integer to int
6. int j=a;//unboxing, now compiler will write a.intValue() internally
7.
8. System.out.println(a+" "+i+" "+j);
9. }}
Output:

3 3 3

The Scanner class

The Scanner class is a class in java.util that allows the user to read values of various
types. Scanner is provided by java.util, which is a package that contains classes so
useful they are called utility classes". Before you can use Scanner, you have to import it
like this:

import java.util.Scanner;

This import statement tells the compiler that when you say Scanner, you mean the one
defined in java.util. It's necessary because there might be another class named Scanner
in another package. Using an import statement makes your code unambiguous. Import
statements can't be inside a class definition. By convention, they are usually at the
beginning of the file. If you omit the import statement and later refer to Scanner, you will
get a compiler error like cannot find symbol". That means the compiler doesn't know
what you mean by Scanner.

Next you have to create a Scanner:

Scanner in = new Scanner(System.in);

This line declares a Scanner variable named in and creates a new Scanner that takes
input from System.in.
Numeric and String Methods

Method Returns
int nextInt() Returns the next token as an int. If the next
token is not an
integer, InputMismatchException is thrown.
long nextLong() Returns the next token as a long. If the next
token is not an
integer, InputMismatchException is thrown.
float nextFloat() Returns the next token as a float. If the next
token is not a float or is out of
range, InputMismatchException is thrown.
double nextDouble() Returns the next token as a long. If the next
token is not a float or is out of
range, InputMismatchException is thrown.
String next() Finds and returns the next complete token
from this scanner and returns it as a string; a
token is usually ended by whitespace such
as a blank or line break. If not token
exists, NoSuchElementException is thrown.
String nextLine() Returns the rest of the current line, excluding
any line separator at the end.
void close() Closes the scanner.
//PrintName.java
import java.io.*;
import java.util.*;

public class PrintName {


public static void main(String[] args) {
// Step1: create a Scanner instance to keyboard
Scanner sc = new Scanner(System.in);
// Step2: get first name
System.out.print("Enter your first name: " );
String fname = sc.nextLine();
// Step3: get last name
System.out.print("Enter your last name: " );
String lname = sc.nextLine();
// Step4: show
System.out.print("Your name is " + lname + " " +fname);
}
}

C:\>javac PrintName.java
C:\>java PrintName
Enter your first name: Sahana
Enter your last name: Kamath
Your name is Sahana Kamath

// PrintSum.java
import java.util.*;
public class PrintSum
{
public static void main(String[] args)
{
//Step1: create a Scanner instance to keyboard
Scanner sc = new Scanner(System.in);
//Step2: get first number
System.out.print(“Enter integer1: ” );
int a = sc.nextInt();
//Step3: get second number
System.out.print(“Enter integer2: ” );
int b = sc.nextInt();
//Step4: discard \n
sc.nextLine();
//Step5: get name
System.out.print(“Enter your name: ” );
String name = sc.nextLine();
//Step6: show
System.out.println(“Hello ” + name + “ Sum is ” +
(a+b));
}
}

C:\>javac PrintSum.java
C:\>java PrintSum
Enter integer1: 30
Enter integer2: 20
Enter your name: Sahana
Hello Sahana Sum is 50

You might also like