Data
Types in Java
Java
is a typed language means each variable in java must have a data type. Data type specifies the size and type of the
values a variable can store. The variety
of data types available in java allows programmers to select specific data type
as per requirement in the program.
1.
Primitive
(intrinsic)Type
a.
Numeric
: Integer and float
b.
Non
numeric: Character and Boolean
2.
Non
Primitive (Derived) Type
a.
Classes
b.
Arrays
c.
Interfaces.
Integer
Type
Integer
data type is used to store numerical values without fractional part (decimal
values). Negative values are allowed in integer type. There are four Integer
types java.
Type Size Minimum Value Maximum
Value
byte` 1 byte –128 127
short 2 bytes –32,768 32,767
int 4 bytes 2,147,483,648 2,147,483, 647
long 8 bytes –9,223,372,036,854,775,808 9,223,372,036,854,775,807
Floating Point Type
Floating
point type data type is used to store numerical values with fractional part
(decimal values). Negative values are allowed in integer type. There are four
Integer types java.
Type Size Minimum Value Maximum
Value
float 4 bytes 3.4e-038 3.4e+038
double 8 bytes 1.7e-308 1.7e+308
The
float type values are single precision numbers and double type values are
double precision numbers. All mathematical functions supported by java like
sin, sqrt etc returns double type value.
Character Type
Character
type is used to describe a single character generally a character constant in
memory.
Type Size Minimum Value Maximum
Value
char 2 bytes Single Character Single Character
Boolean Type
The
Boolean type can hold only two values true
or false. It is used to check logical
condition during execution of a program.
Type Size Minimum Value Maximum
Value
boolean -- true/false true/false
Variables
in Java
Each variable in java has a data
type. To declare a variable first we will have to place type and then name of
the variable. As shown below
int age;
float x, y, z;
long populationofIndia;
Boolean done;
After each variable declaration semicolon is necessary as
declaration is a complete statement. A variable name must begin with a letter
('A' to 'Z', 'a' to 'z', '_', or any Unicode character that denotes a letter) and
a followed by a sequence of letter or digits. Like int ageofEmployeeNo12. Symbols like '+'or '©' and blank space
cannot be used in the name of a variable. The length of variable name in java
is unlimited. Java reserved word (int, float, long, char etc.) of java cannot
be used as the name of variables.
Initialization of variables
We must initialize variables by assigning proper value before
using it we cannot use value of uninitialized variables. For example
int age;
System.out.println(age);
// Error:- Variable not initialize
In
this statement we are displaying value of variable which has no value. This
will give an error because the variable is not initialized. So first we must
initialize a variable and then use it as shown below.
int age;
age = 12;
System.out.println(age);
We can initialize the variable at
the time of declaration also
int age = 12;
System.out.println(age);
We can assign value to mare then
one same type of variables.
float
x, y, z = 0;
OR
float x, y, z;
x=y=z=0;
In java we can put declaration of
variable anywhere in the program. Example
int age = 12;
System.out.println(age);
float x = 0; // Declaration in between the code
-----------------
---------------------
long populationofIndia; // Declaration in between the code
------------
-------------
Scope
of variables
Instance Variables:
Class Variables:
Local Variables:
Constants
in Java
Sometimes we need to
use a unique value at multiple places in our program. Instead of using value
directly in the code we define a constant for that value and we use that
constant in the code when we need to use value. Example
public class ConstantsExample
{
public static void main(String[] args)
{
final double CM_PER_INCH = 2.54;
double TableWidth = 24.5;
double TableLength = 36;
System.out.println("Table size in centimeters: "
+ TableWidth *
CM_PER_INCH + " by " + TableLength * CM_PER_INCH);
}
}
The line “final double CM_PER_INCH = 2.54” declares a constant named CM_PER_INCH. The key word final
is used with a variable to define it a constant. Means declaration of constant
is just like declaration of variable plus using keyword “final” before the
type. Generally capital letters are used for the name of the constant. More
examples of constants
final int MAXIMUM_MARKS = 100;
final double PI = 3.14;
final char
GRADE = 'A';
Type
Casting
Sometimes situation
arises when we needs to store the value of one type into another type of
variable. Example
int x = 50;
byte y = (byte) x;
long count = (long)
x;
In this example x is an
integer variable but we want to store value of x into the variable y which is a
byte type and into count which is long type. To store integer value of x into
byte variable y or long variable count we have to cast it as shown in second
and third line of above example. Casting is necessary when a method return
different type of value then we require. But when we cast from bigger type like
long (8 byte) to smaller type like int (4 byte) then we may loss data
because the value stored in source variable may be bigger than maximum value
destination can store. There is no loss of data when we cast from smaller type
to bigger type.
Operators
Operators are the symbols
which tell system to perform some mathematical or logical operation on the
data.
Arithmetic
Operators
Arithmetic operators
are used to perform mathematical operations. Java supports all the basic
arithmetic operators.
Operator Meaning
+ Addition
or unary plus
- Subtraction
or unary minus
* Multiplications
/ Division
% Modulo division (Reminder)
Example:
a and b are two integers and their
values are a = 15 and b = 6
public class ArithmeticOperators {
public static void main(String[] args)
{
int a = 15, b = 6, c;
c
= a + b;
System.out.println("a + b = " + c);
c
= a-b;
System.out.println("a - b = " + c);
c
= a * b;
System.out.println("a * b = " + c);
c
= a / b;
System.out.println("a / b = " + c);
c
= a % b;
System.out.println("a % b = " + c);
}
}
The output of this program is
a + b = 21
a - b = 9
a * b = 90
a / b = 2 // decimal
part truncated
a
% b = 3 // reminder of integer division
Relational
Operators
We sometimes need to compare two quantities to take
decision on the basis of their relation. We can compare price of two items or
we can compare age of two person. A
simple relational operator contains only one relational operator.
Operator Meaning
< is
less then
<= is
less then or equal to
> is
grater than
>= is
grater than or equal to
= = is
equal to
!= is
not equal to
Example:
______________________________________________________________________________
public class RelationalOperators {
public static void main(String[] args)
{
float a = 15.0F, b = 20.75F, c = 15.0F;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" c = " + c);
System.out.println(" a < b is " + (a<b));
System.out.println(" a > b is " + (a>b));
System.out.println(" a == c is " + (a==c));
System.out.println(" a <= c is " + (a<=c));
System.out.println(" a >= c is " + (a>=c));
System.out.println(" b != c is " + (b!=c));
System.out.println(" b == a+c is " + (b==a+c));
}
}
Result of above
program is
a = 15.0
b = 20.75
c = 15.0
a < b is true
a > b is false
a == c is true
a <= c is true
a >= c is true
b != c is true
b == a+c is false
Logical Operators
In addition
to relation operators java supports three logical operators.
Operator Meaning
&& Logical AND
|| Logical
OR
! Logical
NOT
The logical
operators && or || are used to form compound conditions by combining
more than one relations.
Example:
a > b && x == 10
This kind
of expression which contains two or more relational expressions is called as logical expression or compound relational expression.
Truth table:
A B A
&& B A || B
true true true true
true false false true
false true false true
false false false false
Example of
use of logical expression
If (age
>=50 && salary=10000)
If
(number<0 || number>100)
Assignment
Operators
Assignment operators are used to assign a value of
expression to a variable. “=” is a assignment operator in java. We can assign a
value to a variable using “=”. Example
A =
B + C or A = 5 + 4
In addition to “=” java provides some shorthand
assignment operators also. Example
X
+= Y + 1
The shorthand operator is “+=” in this statement. This
statement is same as
X =
X + (Y + 1);
Shorthand Assignment
Operators
Simple Assignment
Operators Shorthand
Assignment Operators
x = x + 1 x += 1
x = x – 1 x -= 1
x = x * (n+1) x *= n + 1
x = x / (n+1) x /= n + 1
x = x % y x %= y
Increment
and Decrement Operators
Java provides two very
useful operators increment “++” and decrement “--”. Operator ++ adds 1 to
operand and operator – subtracts 1 from the operand. These operators are used
in following form.
++x or x++:
is equivalent to x = x + 1 or x +=1
--x
or x--: is
equivalent to x = x -1 or x -=1
++x and x++ are the
same but behaves differently when used on the right side of the expression.
Example: If the value of
x
= 5
y
= ++x
Now the value of y is 6
and value of x is also six. Means first x will be incremented by one and then assignment
to y will happen.
Suppose we write this
statement as
x = 5
y = x++
Then
value of y will be 5 and x will be 6. Means first assignment will happen y = 5
(present value of x) and then increment will happen.
Example:
Increment and Decrement Operators
public class IncrementDecrementOperators {
public static void main(String[] args)
{
int x = 10, y = 20;
System.out.println(" x = " + x);
System.out.println(" y = " + y);
System.out.println(" ++x = " + ++x);
System.out.println(" y++ = " + y++);
System.out.println(" x = " + x);
System.out.println(" y = " + y);
}
}
The result of above
program after execution:
x = 10
y = 20
++x = 11
y++ = 20
x
= 11
y
= 21
Conditional
Operators
The pair of characters
“?” an “:” is ternary operator in java.
Example:
x = 10
y = 15
z
= (x > y) ? x: y:
The
value of z will be 15, because the value of y will be assigned to z. This
statement is similar to:
if (x>y)
z = x
else
z = y
Bitwise
Operators
Java supports
special operators known as bitwise operators to manipulate values of data at
bit level. These operators are used to shift the values of bits to left or
right. These operators are not applicable to float or double types.
& Bitwise AND
! Bitwise
OR
^ Bitwise
exclusive OR
~ One’s
compliment
<< Shift left
>> Shift Right
>>> Shift right with zero fill
Special
Operators
Java provides two special operators instanceof and member selection
operator “.” (dot operator).
Instanceof operator is object reference operator
which returns true if object on the
left side is instance of the class on the right side. This
operator allows us to check whether the object is instance of a class or not. Example
person instanceof employee
This statement is true if object person is instance of the class employee otherwise false.
The dot (.) operator is used to access methods and
variables of a class. This is also used to access the classes and sub packages
from packages. Example
person.age // Reference to variable age
Person.salary()
// Reference to method salary()
Mathematical
Functions
The Math class of java contains various
mathematical functions. To take square root we can use sqrt function. Example
double x = 4;
double y = Math.sqrt(x);
System.out.println(y); // prints 2.0
Math.pow(x, y) Returns x raised to y (xy)
Math.exp(x) Returns e raised to x (ex)
Math.log(x) Returns log of x
Math.sqrt(x) Returns square root of x
Math.rint(x) Returns the truncated value of x
Math.round(x) Returns the integer closer to argument
Math.abs(x) Returns the absolute value of x
Math.max(x,y) Returns maximum of x and y
Math.min(x,y) Returns minimum of x and y
Math.sin(x) Returns sin of angle x
Math.cos(x) Returns the cos of
angle x
Math.tan(x) Returns the tan of
angle x
Math.atan(x) Returns the angle
whose tangent is x
Math.atan2(x,y) returns the angel whose
tangent is x/y
Inputs
and outputs
In many situations in programming we want to accept
input and format output.
Reading
Input
We have already seen that we can print output using “standard
output stream” by calling System.out.println. Similarly we can use
“standard input stream” to read input from the screen. To read consol input first
we will need to construct a Scanner that
is attached to System.in.
Scanner in = new Scanner(System.in);
Scanner is a class
which provides various methods to read different types of input from the
screen.
nextLine: This method is used to
read a complete line from the screen. Line may include blank spaces also.
System.out.print("What is your full name?: ");
String name = in.nextLine();
The first line will display a message on
the screen “What is your full name?: ” and it will wait to get input from user. Take your pointer in
front of this line and click there, cursor will start blinking then write your
full name and press enter. It will read input from the screen and jump to next
line.
next: To read a word from the screen we can use this method.
System.out.print("Enter your first name (One
word) only: ");
String firstName = in.next();
With help of this method we can read
only a word from the screen.
nextInt: This method is used to
read an integer from the screen.
System.out.print("Enter your Age (Int): ");
int age = in.nextInt();
Similarly Scanner class provides some
more functions to read different type of values.
Example
import java.util.Scanner;
public class FirstJavaProgram
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("What is your full name (First and Last)?: ");
String name =
in.nextLine(); // Read a complete line including spaces
System.out.println("Your full Name is: " +
name); System.out.println("");
System.out.print("Enter your first name (One word) only: ");
String firstName =
in.next();
System.out.println("Your first Name is: " + firstName);
System.out.println("");
System.out.print("Enter your Age (Int): ");
int age = in.nextInt();
System.out.println("Your Age is: " + age);
System.out.println("");
}
}
Output of this program:
What is
your full name (First and Last)?: Amitabh
Bacchan
Your
full Name is: Amitabh Bacchan
Enter
your first name (One word) only: Amitabh
Your
first Name is: Amitabh
Enter
your Age (Int): 67
Your Age is: 67
Formatting Output
No comments:
Post a Comment