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

4. Values and Data Types (1)

Chapter 4 covers values and types in Java, detailing character sets, ASCII characters, escape sequences, and tokens. It explains the different types of tokens, including keywords, identifiers, literals, punctuators, and operators, along with their rules and examples. Additionally, it discusses data types in Java, variable declaration, and the structure of a simple Java program, including common errors encountered during programming.

Uploaded by

jpnarayan202
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

4. Values and Data Types (1)

Chapter 4 covers values and types in Java, detailing character sets, ASCII characters, escape sequences, and tokens. It explains the different types of tokens, including keywords, identifiers, literals, punctuators, and operators, along with their rules and examples. Additionally, it discusses data types in Java, variable declaration, and the structure of a simple Java program, including common errors encountered during programming.

Uploaded by

jpnarayan202
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

CHAPTER 4

VALUES AND TYPES


CHARACTER SETS
1) letters: A-Z and a-z
2) Digits: 0-9
3) Operators: +,-,*,&
4) Delimiters: ; , . { (
5) Special symbols: # @ &
ASCII CHARACTERS AND CODE
Code: When a character is entered from the
keyboard, a specific code is generated and assigned
by the system for its storage in the memory.
ASCII: “American Standard Code for Information
Interchange”.
- The characters used in a computer are ASCII
characters.
- Each character is assigned a specific ASCII code.
- Total 128(0-127) codes.
ASCII TABLE
CHARACTERS CODES
0 48
- -
- -
9 57

A 65
- -
- -
Z 90

a 97
- -
- -
z 122

Blank space 32
Java Escape Sequences
ESCAPE SEQUENCE MEANING

\t Horizontal tab

\v Vertical tab

\’ Single quote

\” Double quote

\n New line feed


Example 1
public class prog1
{
public static void main(String args[])
{
System.out.println("name: ashwini \n"+"Age:27
years \n"+"school:PIS");
}
}
Example 2

public class prog2


{
public static void main(String args[])
{
System.out.println("name: ashwini \t"+"Age:27
years");
}
}
Example 3
public class prog3
{
public static void main(String args[])
{
System.out.println("welcome to \"computer\“
world");
}
}
Tokens
- The smallest individual unit in a program is
known as token.
- Every java statement consists of individual
words and punctuation marks which are
known as tokens.
- They may be single character or set of
characters separated by white spaces or
blanks.
Types of Tokens
1) Keywords.
2) Identifiers.
3) Literals.
4) Punctuators.
5) Operators.
6) Separators.
1) Keywords
- They are the words reserved by java language.
- They have some specific meaning to the java
compiler.
- They are the foundation of java language.
- These words cannot be used by the
programmer to name an identifier.
- All the keywords are in lowercase.
- For ex: “for” is a keyword but FOR is not.
Examples
2) Identifiers

- They represent names which can be assigned


to variables, methods and classes to uniquely
identify them.
- These are the words which are defined by the
programmer.
Rules for writing the identifiers
1) Identifiers names are case-sensitive.
2) They should not be a keyword.
3) Each identifier must have at least one character.
4) The first character must be: alphabet, underscore(_)
or dollar sign($).
5) The first character can not be a digit.
6) The rest of the characters (besides the first) can be
from: alphabet, digit, underscore, or dollar sign.
7) There cannot be any space in an identifier name.
8) Symbols like +, @,etc cannot be used inside an
identifier name.
9) They can be of any length.
Valid identifiers
- rollno
- emp_name
- _
- $program
- _ixd
- _emp_code
- PodarInternationSchool
- $BASICS
Invalid identifier
- for
- if
- Podar International School
- stock+number
- 2empid
- 1234
- student-roll-number
- emp.data
3) Literals/Constants
- Literals in Java are a sequence of characters
(digits, letters, and other characters) that
represent constant values to be stored in
variables.
- They are the fixed values that do not change
during the execution of the program.
Types of literals
1) Integer
2) Real
3) Character
4) String
5) Boolean
I) Integer constant
- They refer to the sequence of digits.
- They consist of a set of digits from 0 to 9 with
or without a minus(-) sign.
- Ex: 999, -999.
- Spaces, commas and non-digit characters are
not permitted in between the digits.
- Ex: 99 87, 765,23, 987#234 are invalid
numbers.
II) Real constant/ Floating point constant
- Numbers containing fractional parts are called
real literals.
- Valid real constants:
9.999, 2.51, -5.6, -111.99999.
- Invalid real constants:
9. (no number after decimal)
99.87.23 (2 decimal points)
12,876.45 (comma not allowed)
- The numbers are also expressed in
exponential notation.
- “mantissa e/E exponent”
- Here,
mantissa= real number expressed in decimal
notation/ an integer.
e/E= it can be e or E.
exponent= it is an integer with an optional +
or – sign.
- Valid real constant in exponential form:
0.97e4, 12e-2, .25e7.
- Invalid real constant in exponential form:
2.5e (no number specified after exponent)
76.5e8.4 (exponent cannot have decimal
part)
12,4566e8 (comma not allowed)
III) Character constant
- It contains single character enclosed with a
pair of single quote marks ‘ ’.
- They are alphanumeric in nature.
- Ex: ‘m’, ‘5’, ‘*’.
IV) String constants
- It is a sequence of alphanumeric characters
enclosed between “ ”.
- The characters may be alphabets, digits,
special characters and blank spaces.
- Ex: “hi”, “program”, “123”, “s#gh”, “ ”,
“computer textbook”.
V) Boolean constants
- They have only 2 type of values.
- i.e: true and false.
- They are reserve words of java language.
Declaration of a variable Assigning constant

int a; a= 5;

long b; b= 548745;

float f; f= 3.25;

double d; d= 2.25478;

char ch; ch= ‘K’;

String str; str= “APPLE”;

boolean p; p= false;
4) punctuators/ Separators
SYMBOL NAME DESCRIPTION
1) () parentheses Used in:
-Method signatures.
-Loops
-Conditional statements
2) {} braces Used in:
-Declaration of types.
-Block of statements
-Array initialization
3) [] brackets Used to:
- Array declaration
4) ; Semicolon Used to:
-Terminate statements
-Separate the initialization
code
SYMBOL NAME DESCRIPTION
5) : colon Used to:
-Define loops.
-Define switch
statements.
6) , comma Used to:
-Separate values
-Separate variables.
7) . period Used to:
-Separate package
names.
-Separate fields or
methods.
5) operators
- Operators are special symbols that perform
specific operations on one, two or more
operands.
- Operands can be constant or a variable.
- Hence, an operation is performed using at
least one symbol and at least one value.
- The symbol used in an operation is called an
operator.
- A value involved in an operation is called an
operand.
Types of operators

• Arithmetic operators

• Relational operators

• Logical operators

• Assignment operators

• Increment/ Decrement operators

• Conditional/Ternary operators
I) Arithmetic operators

Performs arithmetic operations like addition,


subtraction, multiplication, division etc.
OPERATOR OPERATION EX: (int a=15, b=3)

+ Used to add the values a+b

- Used to subtract the a-b


values

* Used to multiply the a*b


values

/ Used to divide the values a/b

%(modulus) Used to give remainder a%b


II) Relational operators

Used to compare two operands. Returns True or


False.
OPERATOR OPERATION EX: (int
A=15, B=10)
== (equal to) Compares two variables to check whether they A==B
are equal or not.
!= (not equal to) Compares two variables to check whether they A !=B
are unequal.
> (greater than) Compares to check whether the first value is A>B
greater than the second.
>= (greater than or Compares to check whether the first variable is A>=B
equal to) greater than or equal to the second.
< (less than) Compares to check whether the first variable is A<B
less than the second.
<= (less than or equal Compares to check whether the first variable is A<=B
to) less than or equal to the second.
III) Logical Operators
Used to combine two or more conditions using
relational operators.
OPERATOR OPERATION EX:(int A=56, B=45, C=56)

&& (and) Final result is True only if all (A>B && A>C) is False
conditions are True. It is False if any
one condition is False. (A>B && A==C) is True

|| (or) Final result is True if any one (A>B && A>C) is True
condition is True. It is False only when
all conditions are False. (A<B && A>C) is False

! (not) Used to reverse the value of an If (B>0) is True then


expression. If condition is True, it !(B>0) is False
results in False and vice versa
IV) Assignment operators

OPERATOR OPERATION EXAMPLE


Simple assignment operator. Assigns values C = A + B will assign value of
= from right side operands to left side operand. A + B into C
Add AND assignment operator. It adds right
operand to the left operand and assign the C += A is equivalent to C = C +
+=
result to left operand. A

Subtract AND assignment operator. It


subtracts right operand from the left operand C -= A is equivalent to C = C –
-=
and assign the result to left operand. A

Multiply AND assignment operator. It


*= multiplies right operand with the left operand C *= A is equivalent to C = C *
and assign the result to left operand. A

Divide AND assignment operator. It divides


left operand with the right operand and C /= A is equivalent to C = C /
/=
assign the result to left operand. A

Modulus AND assignment operator. It takes


modulus using two operands and assign the C %= A is equivalent to C = C
%=
result to left operand. %A
V) Increment/ Decrement operators

1) Increment operator: ++
2) Decrement operator: --

Ex: If x=10
x++; gives 11
x--; gives 9
VI) Conditional/Ternary operator
exp1 ? exp2 : exp3
Evaluate if Evaluate if
True/ False true false

If x=10, y=20 then

a=(x > y) ? x : y
will assign the value 20 to ‘a’

a=(x < y) ? x : y
will assign the value 10 to ‘a’
VARIABLES
- A variable is a container, that stores a data value
in it.
- It is a basic unit of storage in a java program.
- All variables must be declared before they can
be used.
Variable Definition in Java

Syntax:
type variable_name;
type variable_name, variable_name,
variable_name;
Example
/* variable definition and initialization */
int width, height=5;
char letter='C';
float age, area;
double d;

/* actual initialization */
width = 10;
age = 26.5;
Dynamic Initialization of a variable

Java allows variables to be initialized dynamically,


i.e. during the execution of a program.
Ex: int a=2, b=3;
int c=a+b;
Explanation of above snippet:
1. Three variables a, b, and c are declared.
2. First two, a and b, are initialized by constants.
3. c is initialized dynamically as the sum of a and b.
DATA TYPES IN JAVA
- Information is stored in a computer memory with
different data types.
- Whenever a variable is declared, it becomes
necessary to define data type, that what will be
the type of data that variable can hold.
CATEGORIES OF DATA TYPES
1) Primitive/Fundamental data type
2) Non-primitive data type.
1) Primitive/Fundamental data type

- Pre-defined data types provided by a


programming language to store the data in a
variable.
- Java supports 8 primitive data types.
i) byte ii) short iii) int iv) long v) float vi)
double vii) char viii) boolean
- These data types are classified into 4 groups:
I) INTEGERS
TYPE KEYWORD SIZE RANGE
NAME
byte byte 1 byte -128 to 127

short short 2 bytes -32768 to


32767
int int 4 bytes -231 to 231-1

long long 8 bytes -263 to 263-1


II) FLOATING POINT TYPES
TYPE KEYWORD SIZE RANGE
NAME

float float 4 bytes -3.4 X 10-38


to 3.4 X 1038

double double 8 bytes -1.7 X 10-308


to 1.7 X 10308
III) CHARACTERS
TYPE KEYWORD SIZE RANGE
NAME

char char 2 bytes 0 to 65535


IV) BOOLEAN
TYPE KEYWORD SIZE RANGE
NAME

boolean boolean I bit true or false


2) Non-primitive data type
1) String type: The string type is used to declare
a string variable.
Ex: String a=“this is a string”;
WRITING A SIMPLE JAVA PROGRAM
class Simple
{
public static void main(String args[])
{
System.out.println("hello");
}
}
MEANING OF
public static void main(String args[])

• Public : is an Access Modifier, which defines who


can access this Method. Public means that this
Method will be accessible by any Class.
• Static : is a keyword which identifies the class
related thing. It can be accessed without creating
the instance of a Class.
• Void : It defines what the method can return. Void
means the Method will not return any value.
• main: is the name of the Method.
• String args[] : is the parameter to the main
Method.
STEPS TO EXECUTE THE PROGRAM IN
BLUEJ
STEP 1: click on the bluej icon present on the
desktop.
Step 2: click on project(create your own
project). Every time you have to open
the same project.
Step 3: Open your project and click on new
class.
Step 4: type the program and click on compile.
Step 5: shaded region means that the program
has not been compiled properly and the
unshaded region means that the program has
been compiled properly.
ERRORS IN PROGRAMMING
1) Syntax Errors:
- Any violation of rules and poor understanding
of the programming language results in syntax
errors.
- The compiler can detect such errors.
- If syntax errors are present in the program
then the compilation of the program fails and
is terminated after showing the list of errors
and the line number where the errors have
occurred.
2) Run-time Errors:
- Runtime errors are the errors that occur during
the execution of the program.
- Some examples are, dividing by zero error.
- These are not detected by compiler while
compilation process.
- A program with these kinds of errors will run
but produce erroneous results or may
cause termination of program.
3) Logical Errors:
- As the name itself implies, these errors are
related to the logic of the program.
- Logical errors are also not detected by
compiler and cause incorrect results.
- These errors occur due to incorrect translation
of algorithm into the program, poor
understanding of the problem and a lack of
clarity of hierarchy of operators.
EXAMPLE OF SYNTAX ERRORS
class Simple
{
public static void main(String args[])
{
System.println("hello");
}
}
EXAMPLE OF RUNTIME ERRORS
class Division
{
public static void main(String args[])
{
int a= 0,b=3,c;
c=a/b;
System.out.println(“the ans is“+c);
}
}
EXAMPLE OF OPERATORS
- The symbol used in an operation is called an
operator.
- A value involved in an operation is called an
operand.
1) Assignment operator
public class demo
{
public static void main(String args[])
{
int j,k;
j=10;
j=5;
k=j;
S.O.P(“j=”+j);
S.O.P(“k=”+k);
}
}
Output:

j=5
K=5
Multiple Assignments
public class demo
{
public static void main(String args[])
{
int j,k;
k=j=10;
S.O.P(“j=”+j);
S.O.P(“k=”+k);
}
}
2) Arithmetic operators
Public class Arithmetic
{
public static void main(String args[])
{
int x, y=10, z=5;
x=y+z;
System.out.println(“the ans is”+x);
x=y-z;
System.out.println(“the ans is”+x);
x=y/z;
System.out.println(“the ans is”+x);
x=y%z;
System.out.println(“the ans is”+x);
}
}
Output:
x=15
x=5
x=2
x=0
3) INCREMENT/DECREMENT OPERATORS

There are 2 types of increment/decrement


operators:
1) Prefix increment/decrement operator:
(change-then-use)
2) Postfix increment/decrement operator:
(use-then-change)
OPERATOR USE DESCRIPTION
Postfix increment op++ Increments op by 1; evaluates to the
value of op before it was incremented.

Prefix increment ++op Increments op by 1; evaluates to the


value of op after it was incremented.

Postfix decrement op-- decrements op by 1; evaluates to the


value of op before it was decremented.

Prefix decrement --op decrements op by 1; evaluates to the


value of op after it was decremented.
Example 1
public class Pre
{
public static void main(String args[])
{
int a=5,b;
b= ++a + 5;
S.O.P(“a=”+a);
S.O.P(“b=”+b);
}
Explanation of example 1
• The above program makes use of prefix increment
operator that is ++a.
• So value of a is incremented and then used in
expression which gives
• a=a+1 which gives value of a=6
then b becomes b=6+5=11
so the output of prgram is
a=6
b=11
Example 2
public class Post
{
public static void main(String args[])
{
int a=5,b;
b= a++ + 5;
S.O.P(“a=”+a);
S.O.P(“b=”+b);
}
Explanation of Example 2
• The above program makes use of postfix
increment operator that is a++.
• So value of a is used in expression then
incremented which gives:
b = 5+5=10
a=a+1 makes value of a as 6
• So the output of program is :
a=6
b=10
Example 3
public class Ex3
{
public static void main(String args[])
{
int i=10;
int n=i++%10;
S.O.P(“i=”+i);
S.O.P(“n=”+i);
}
Output:
i=11
n=0
Example 4
int count=1;
System.out.println(++count);

displays 2.

int count=1;
System.out.println(count++);

displays 1.
Example 5
class PrePostDemo
{
public static void main(String args[])
{
int i = 3;
i++;
System.out.println(i); // "4" : use then change
++i;
System.out.println(i); // "5" :change then use
System.out.println(++i); // "6" : change then use
System.out.println(i++); // "6" :use then change
System.out.println(i); // "7“ : change from previous
}
}
4) RELATIONAL OPERATOR
class RelDemo
{
public static void main(String args[])
{
int a = 10, b = 15, c = 15;
System.out.println(" a > b = " + (a > b));
System.out.println(" a < b = " + (a < b));
System.out.println(" b >= a = " + (b >= a));
System.out.println(" b <= a = " + (b <= a));
System.out.println(" b == c = " + (b == c));
System.out.println(" b != c = " + (b != c));
}
}
5) 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));
}
}
public class LogicalOperator
{
public static void main (String args[])
{
int x=6 ,y=4, z=5;
System.out.println(" x>y & y>z-->" + (x>y &&
y>z));
System.out.println(" x>y | y>z-->" + (x>y ||
y>z));
System.out.println(" !(x>y)--> " + (!(x>y)));
}

}
6) Conditional/ternary
public class TernaryEx
{
public static void main(String[] args)
{
int minVal, a=3, b=2;
minVal = a < b ? a : b;
System.out.println("min = " + minVal);
}
}

You might also like