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

Unit 1 - 2

The document discusses various Java data types including primitive and non-primitive types. It describes numeric types like integer and floating point, and non-numeric types like boolean and character. It also covers variable declaration and initialization, constants, type casting, and basic operators.

Uploaded by

Vinayak kalel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Unit 1 - 2

The document discusses various Java data types including primitive and non-primitive types. It describes numeric types like integer and floating point, and non-numeric types like boolean and character. It also covers variable declaration and initialization, constants, type casting, and basic operators.

Uploaded by

Vinayak kalel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Data Types

 The data type defines the kind of data represented by a variable.

 Java data types are case sensitive.

 Data type specifies the size and type of values that can be stored.

Java is rich in its data types


The classification of data types in Java
Data types in Java

Primitive Non-primitive

Numeric Non-numeric
classes Arrays
integer
char Interface

Floating point Boolean

Data types in Java


Integer data type
 Integer datatype can hold the whole numbers.
 The number can be positive number or negative
number. (Does not support unsigned)
 In Java, there are four types of integer as follows:

1. byte 1 Byte
byte x, y;
2. short 2 Bytes short x;
3. int 4 Bytes int x;
long seconds;
4. long 8 Bytes
Floating point data type
 It is also called as Real number and when we require accuracy
then we can use it.
 There are two types of floating point data type.
1. Float
2. Double
 It is represent single and double precision numbers.
 float type, is used for single precision and it uses 4 bytes for
storage space.
 Double type, is used for double precision and uses 8 bytes of
storage space.
Non-numeric Data Types
 Character data type:
– It is used to store single character in memory.
– It uses 2 bytes storage space.
 Boolean data type:
– It is used to test a particular condition during of the program.
– There are only two values that a boolean type can hold:
– true and false.
– Boolean type is denoted by the keyword boolean and uses
only one bit of storage.
Datatypes with size and range
Data type Size (byte) Range

byte 1 -128 to 127

boolean 1 true or false

char 2 A-Z,a-z,0-9,etc.

short 2 -32768 to 32767

Int 4 (about) -2 million to 2 million


-2147483648 to 2147483647
long 8 (about) -10E18 to 10E18
-9233372036854775808 to 9233372036854775807
float 4 -3.4E38 to 3.4E18

double 8 -1.7E308 to 1.7E308


Standard Default Values

 byte – Zero : 0
 short – Zero : 0
 int – Zero : 0
 long – Zero : 0L
 float – 0.0f
 double – 0.0d
 char – null
 boolean – false
Variables
 Variables are labels that express a particular position in
memory and connect it with a data type.
 The first way to declare a variable:
– It assigns zero to primitive types and null to objects.

dataType variableName;

 The second way to declare a variable:


– The initial value must be of the correct data type.

dataType variableName = initialValue;


Variables
 The first way to declare two variables:
– all of the same data type, reserves memory for each.

dataType variableNameOne, variableNameTwo;

 The second way to declare two variables:


– both of the same data type, reserves Memory, and puts an
initial value in each variable.
dataType variableNameI = initialValueI,
variableNameII=initialValueII;
Variable Names
1. Use only the characters „a„ through „z„, „A„ through „Z„, „0„
through „9„, character „_„, and character „$„.
2. A name cannot include the space character.
3. Do not begin with a digit.
4. A name can be of any realistic length.
5. Upper and lower case count as different characters.
6. A name cannot be a reserved word (keyword).
7. A name must not previously be in utilized in this block of
the program.
Constants
 Constant means fixed value which do not change at the time
of execution of program.
 In Java, there are two types of constant as follows:

 Numeric Constants
 Integer constant
• Decimal
• Octal
• Hexadecimal
 Real constant
 Character Constants
 Character constant
 String constant
Backslash character constant

 Java support some special character constant which


are given in following table.

Constant Importance
„\b„ Back space
„\t„ Tab
„\n„ New line
„\\„ Backslash
„\‟‟ Single quote
„\”„ Double quote
Symbolic constants
 These constants may appear repeatedly in a
number of places in the program.
 One example of such a constant is 3.142,
representing the value of the mathematical constant
“pi” .
 We face two problems in the subsequent use of
such programs. They are:
– 1. Problem in modification of the program

– 2. Problem in understanding the problem


Symbolic constants
 Assignment of a symbolic name to such constants
frees us from these problems.
 Example, we may use the name STRENGTH to
denote the number of students and PASS-MARK to
denote the pass marks required in a subject.
 Constant values are assigned to these names at the
beginning of the program. Subsequent use of the
names STRENGTH and PASS-MARK in the
program has the effect of causing their defined
values to be automatically substituted at the
appropriate points.
Symbolic constants
 Java provides “final” keyword to declare the value of
variable as follows:
 Syntax:
final type Symbolic_name=value;
 For example: If I want to declare the value of „PI„ then:

final float PI=3.1459;


the condition is, Symbolic_name will be in capital letter.
Scope of variable

 Java variables are actually


classified into three kinds
 1. Instance variables
 2. Class variables
 3. Local variables
Instance Variable

 Instance and class variables are declared inside the


class.
 Instance variables are created when the objects are
instantiated and therefore they are associated with
the objects.
 They take different values for each object.
Class Variable

 On the other hand, class variables are global to the


class and belong to the entire set of objects that the
class creates.
 Only one memory location is created for each class
variable.
Local Variables

 Variables declared and used inside the methods are called


local variables.
 They are not available for use outside the method definition.
 These variables are visible to the program only from the
beginning of its program block to the end of the program
block.
 When the program control leaves a block, all the variables in
the block will cease to exist.
 The area of the program where the variable is accessible(ie
Usable)is called its scope.
Type Casting
 For storing value of one type into a variable of another type.
 The Syntax is:
Type variable1 =(type) variable2;

Examples:
int m = 50;
Byte n = (byte) m;
long count= (long) m;

 Four integer types can be cast to any other type except


boolean.
 Casting into smaller type may result in loss of data.
Cast that results in NO loss of information
Automatic Conversion

 It is possible to assign a value of one type to a


variable of a different type without a cast.
 Java does the conversion of the assigned value
automatically.
 This is known as automatic type conversion.
 Example: byte b= 75;
 int a= b;
Operators
 Operator is a symbol that tells a computer to perform certain
mathematical or logical manipulations.
 Operators are used in programs to manipulate data and variables. Java
operators can be classified into:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special Operators
Arithmetic operators
• Arithmetic operators are used to make mathematical expressions
and the working out as same in algebra.
• Java provides the fundamental arithmetic operators.
• These can operate on built in data type of Java.
• Following table shows the details of operators.

Operator Importance/ significance


+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or remainder
Arithmetic operators
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b); 15
System.out.println(a*b); 5
System.out.println(a/b); 50
System.out.println(a%b); 2
}} 0
Relational Operators
 When evaluation of two numbers is performed depending upon their
relation, assured decisions are made.

 The value of relational expression is either true or false.


 If A=7 and A < 10 is true while 10 < A is false.
 Following table shows the details of operators.
Operator Importance/ significance
> Greater than
< Less than
!= Not equal to
>= Greater than or equal to
<= Less than or equal to
== Is equal to
Relational Operators
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
a == b = false
System.out.println("a = = b = " + (a = = b) );
a != b = true
System.out.println("a != b = " + (a != b) );
a > b = false
System.out.println("a > b = " + (a > b) );
a < b = true
System.out.println("a < b = " + (a < b) );
b >= a = true
System.out.println("b >= a = " + (b >= a) );
b <= a = false
System.out.println("b <= a = " + (b <= a) );

}}
Logical operators
• When we want to form compound conditions by combining two
or more relations, then we can use logical operators.

Following table shows the details of operators.


Operators Importance/ significance
|| Logical – OR
&& Logical –AND
! Logical –NOT

op1 && op2

The logical expression defer a value of true or false


Logical operators
public class Test {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
a && b = false
} a || b = true
!(a && b) = true
Assignment Operator
Assignment Operators is used to assign the value of an
expression to a variable and is also called as Shorthand
operators.
Variable_name binary_operator = expression;
Following table show the use of assignment operators.
Simple Assignment Operator Statement with shorthand
Operators
A=A+1 A+=1
A=A-1 A-=1
A=A/(B+1) A/=(B+1)
A=A*(B+1) A*=(B+1)
A=A/C A/=C
A=A%C A%=C
Assignment Operator

class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3; 13
System.out.println(a);
a-=4;
System.out.println(a);
9
a*=2;
System.out.println(a);
18
a/=2;
System.out.println(a); }} 9
Increment and Decrement Operators
 The increment operator ++ adds 1 to a variable.
 Usually the variable is an integer type, but it can be a floating point type.

Expression Process Example end result


A++ Add 1 to a variable int A=10,B; A=11
after use. B=A++; B=10
++A Add 1 to a variable int A=10,B; A=11
before use. B=++A; B=11
A-- Subtract 1 from a int A=10,B; A=9 B=10
variable after use. B=A--;
--A Subtract 1 from a int A=10,B; A=9 B=9
variable before use. B=--A;
Increment and Decrement Operators
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10; 22
21
System.out.println(a++ + ++a);
System.out.println(b++ + b++);
}}
Increment and Decrement Operators
class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);
10
System.out.println(++x);
12
System.out.println(x--); 12
System.out.println(--x); 10
}}
class IncrementOpr
{
public static void main(String args[])
{
int m=10, n=20;
System.out.println(“m=” +m); m=10
System.out.println(“n=” +n);
System.out.println(“++m=” + ++m);
n=20
System.out.println(“n= ” +n++); ++m=11
System.out.println(“m=” +m);
System.out.println(“n=” +n);
n++=20
} m=11
}
n=21
Conditional Operators
 The character pair ?: is a ternary operator of Java, which is used to construct
conditional expressions of the following form:

Expression1 ? Expression2 : Expression3

 The operator ? : works as follows:


 Expression1 is evaluated if it is true then Expression2 is evaluated and becomes
the value of the conditional expression.

 If Expression1 is false then Expression3 is evaluated and its value becomes the
conditional expression.

A=3; B=4;
C=(A<B)?A:B; Answer C=3
C=(3<4)?3:4;
Conditional Operators
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Answer: 2
Bit Wise Operators
 These operators are used for testing the bits, or shifting
them to right or left.
 Following table shows bit wise operator
Operator Importance/ significance
| Bitwise OR Example:
& Bitwise AND int a= 4;
&= Bitwise AND assignment int b = a<<3;
|= Bitwise OR assignment
^ Bitwise Exclusive OR Output:
<< Left shift
>> Right shift
b =32
~ One„s complement
Bit Wise Operators
public class Test {
c = a << 2; /* 240 = 1111 0000 */
public static void main(String args[]) {
System.out.println("a << 2 = " + c );
int a = 60; /* 60 = 0011 1100 */
c = a >> 2; /* 15 = 1111 */
int b = 13; /* 13 = 0000 1101 */ System.out.println("a >> 2 = " + c );
int c = 0; c = a >>> 2; /* 15 = 0000 1111 */
c = a & b; /* 12 = 0000 1100 */ System.out.println("a >>> 2 = " + c );
System.out.println("a & b = " + c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c );
}
}
Special Operators
 Java supports some special operators of interest such as
instanceof operator and member selection operator (.) .
 Instanceof Operator :
– The instanceof is an object reference operator and returns true if the object
on the left hand is an instance of the class given on right-hand side

person instanceof student

 Dot Operator :
– The dot operator (.) is used to access the instance variable and methods
of class object.

Person1.age
Person1.salary()
Operator Precedence in Java:

 An arithmetic expression without any parentheses will be


calculated from left to right using the rules of precedence of
operators.
 There are two priority levels of arithmetic operators are as
follows:
– High priority (* / %)
– Low priority (+ -)
Operator Associativit Rank
y < Left to right
[] Left to right 1 <= Left to right
() Left to right
> Left to right 6
. Left to right
- Right to left >= Left to right
++ Right to left Instanceof Left to right
2
-- Right to left == Left to right
7
! Right to left != Left to right
~ Right to left & Left to right 8
(type) Right to left
^ Left to right 9
* Left to right
| Left to right 10
/ Left to right 3
% Left to right && Left to right 11
+ Left to right || Left to right 13
4
- Left to right ?: Right to left 13
<< Left to right = Right to left 14
>> Left to right 5
>>> Left to right
Mathematical Functions
 Mathematical Functions such as cos, sqrt, log, etc. are frequently used.
 Java supports these functions through Math class defined in java.lang
package.
 These functions should be used as following :
Math.function_name();
Example : double y= Math.sqrt(x);
Function
Function sqrt()
sin() ceil()
cos() floor()
tan() round()
pow(x,y) abs(a)
exp(x) max(a, b)
log(x) min(a, b)
Evaluation of Expression
 Expressions are evaluated using an assignment statement of the form

 When the statement is encountered, the expression is


evaluated first and the result then replaces the variable on
the left-hand side.
 All the variable used in the expression must be assigned
values before evaluation is attempted.
 Examples of evaluation statements are
 x=a*b-c
 y=b/c*a;
 z=a-b/c+d;
Evaluated following

 x=a-b/3+c*2-1
 when a=9, b=12, and c=3 what will be x
Casting value

 Consider, for example, the calculation of ratio of female to males in a


town.
ratio =female _ number / male _ number
 Since female _ number and male _ number are declared as integers in
the program, the decimal part of the result of the division would be lost
ratio would not represent a correct figure.
 This problem can be solved by converting locally one of the variables to
the floating points as shown below;
 ratio=(float) female _number / male _ number
 The process of such a local conversion is known as casting value. The
general form of a cast is;
(type _ number) expression
Decision Making and Branching

 Decision making structures have one or more conditions to


be evaluated or tested by the program, along with a
statement or statements that are to be executed if the
condition is determined to be true, and optionally, other
statements to be executed if the condition is determined to be
false

 Branching: When a Program breaks the sequential flow and


jumps to another part of the code ,it is called branching.
Decision Making and Branching

 There are Two types of Branching .


– Conditional Branching :
 When a program breaks the sequential flow and jumps
to another part of the code, it is called conditional
Branching.
– Unconditional Branching:
 If Branching takes place without any decision, it is
known as unconditional Branching.

 There are the 5 ways of exercising decision


making in Java:
– 1. if 2. if-else 3. nested-if
– 4. else-if-Ladder 5. switch-case
References

 Programming with Java – A Primer : E


Balaguruswamy
 Internet

You might also like