Transcript Document

Chapter: 4:XI_IP
Programming Fundamentals
Prepared By :
VINAY ALEXANDER (विनय अलेक्सजेंड़र)
PGT(CS) ,KV JHAGRAKHAND
Java Character Set
Character set is a set of valid characters that a
language can recognize. A character represent any
letter, digit or any other sign.
=>Java uses Unicode character set. Unicode is twobyte character code set that has representing almost
all character in almost all languages and writing
systems
around
the
world
including
English,arabic,chinese and many more.
=>ASCII: American Standard code for information
interchange.
=>TOKEN: The smallest individual unit in a program
is know as a token.
=>TYPES OF TOKEN:
• 1.KEYWORDS
• 2.IDENTIFIERS
• 3.LITERALS
• 4.PUNCTUATIONS
• 5.OPERATORS
=>Reserved words or keywords are words
that have a specific meaning to the compiler
and cannot be used for other purposes in the
program. For example, when the compiler sees
the word class, it understands that the word
after class is the the name for the class
•
•
•
•
•
•
•
•
•
•
• 1.KEYWORDS
– Reserved identifier: An identifier with a pre-defined
meaning that can not be changed
– Java reserved identifiers
while
super
native
float
const
volatile
strictfp
long
finally
class
void
static
interface
final
char
try
short
int
extends
catch
transient
return
instanceof enum
case
throws
public
import
else
byte
throw
protected implements double
break
this
private
if
do
boolean
synchronized package goto
default
assert
switch
new
for
continue
4
abstract
• Java is case-sensitive; maxval, maxVal, and
MaxVal are three different names.
• 2.IDENTIFIERS
An Identifier are fundamental building blocks of a
program and are used as the general terminology for
the names given to different parts of the program viz.
variable , objects etc.
That is Names given to variables, objects, methods
Identifiers are programmer-defined names for:
– classes
– variables
– methods
• Identifiers may not be any of the Java reserved
keywords.
5
=>Identifiers must follow certain rules:
• An identifier must start with a letter, an underscore, or a
dollar sign.
• An identifier cannot contain operators, such as
+, -, and so on.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, Or null .
• An identifier can be of any length.
• Followed by any number of characters, digits
• Identifiers should be well chosen
– use complete words (even phrases)
– this helps program documentation
– An identifier may only contain:
•
•
•
•
letters a–z or A–Z,
the digits 0–9,
underscores (_), or
the dollar sign ($)
– The first character may not be a digit.
– Identifiers are case sensitive.
• itemsOrdered is not the same as itemsordered.
– There are some existing Java identifiers
sqrt String Integer System in out
– We can make up new identifiers
test1 x1 aNumber MAXIMUM A_1
--- An identifier is case-sensitive;
• LITERAL: A Constant value assign to a
variable is known as Literal.
• Types: 1.Integer 2. Character 3.Floating
• 3. String 4. Boolean 5.The Null
7
• INTEGER: An integer constant must have at least
one digit and must not contain any decimal point. It
may contain either + or –sign. Default is a positive
• Java allows three types of integer literals.
• Decimal(base 10) : An integer literal consisting of
a sequence of digits. It contains( 0 to 9)
• Octal (base 8): A sequence of digits starting with
0(digit zero) is taken to be an octal integer.
• It must not contain 8 and 9. It contains( 0 to 7)
• Hexadecimal base 16) : A sequence of digits
preceded
by 0x or 0X is taken to be an
Hexadecimal integer.
• Hexadecimal integer only 0-9 and A- F.
8
(10A,11B, 12C,13D,14E,15F)
(2) Floating - are also called real literals
Real literals are numbers having fractional
parts. These may be written in one of the two
forms called fractional form or the exponent
form.
=>The rule for writing a real constant in
fractional form is given below :
A real literal in fractional form must have at
least one digit before decimal point and at least
one digit after point. It may also have either +
or - sign preceding it. A real literal with no sign
is assumed to be positive.
Example: valid real literals
2.0,17.5
Example: Invalid real literals
7
7.
+17/2
(3) Boolean literals
Boolean literals type has two values,
represented by the literals true or
Boolean values false from ASII letters.
(4) Character literals
A character is one character enclosed in
single quotes that is 's'.
A character literal in java must contain
one character and must be enclosed in
single quotation marks.
Escape Sequences
• To include a special character in a String, use
an escape sequence
Character
Newline
Tab
Double quotes
Single quote
Backslash
Backspace
Carriage return
Form feed
Escape Sequence
\n
\t
\"
\'
\\
\b
\r
\f
(5) String literals
'Multiple character' constants are treated as
string-literals. The rule for writing string-literal is
given below :
A string is a sequence of zero or more
character surrounded by double quotes. Each
character may be represented by an escape
sequence.
(6) The Null Literal
The null type has one value .the null reference,
represented by the literals null, which is form
ASCII character.
=>Separators: The following nine ASCII
Characters are the separators(punctuations).
() { } [ ] ; , .
Concept Of Data Types
Data types are means to identify the types of
data and associated operations of handling it.
Java data types are two types :
1.Primitive Data types comes as a part of the
language. Java provides eight primitive
Data types which are : byte, short, int, float,
double, char, Boolean.
Reference data type : They are
constructed from primitive data types these
data types generally store the memory
addresses of a class.
Primitive Data types: They
are the "basic" data
values. There are four types of primitive data types :
Numeric Integral Primitive Data types.
• Fractional Primitive Data types
• Character Primitive Data types
• Boolean Primitive Data types
=>Numeric Integral Primitive Data types : The
data types are used to store some numeric values fall
under this sub-catagoary.
There are four Numeric Integral Primitive Data types
in java.
• 1.byte(8 bits(1 bytes))
• 2.short(16 bits(2 bytes))
• 3.int(32 bits(4bytes))
• 4.long(64 bits(8bytes))
Size
Names
Signed Range
Unsigned Range
8 bits
Byte
−128 to +127
0 to 255
16 bits
Word, short int
−32,768 to
+32,767
0 to 65,535
32 bits
Double Word, long int
(win32, win64, 32-bit
Linux[1])
−2,147,483,648
to
+2,147,483,647
0 to
4,294,967,295
64 bits
long int (C in 64-bit
linux[1]), long long (C),
long (Java, the signed
integer variant only[2])
−9,223,372,036,8
0 to
54,775,808 to
18,446,744,073,7
+9,223,372,036,8
09,551,615
54,775,807
unlimited
Bignum
Fractional Primitive Data types
•
These can store fractional numbers i.e., having decimal
values.
There are two types of Fractional Primitive Data types.
1.Float (32 bits(4 bytes))
2.Double(64 bits(8 bytes))
=>Character Primitive Data types : CHAR data types are
used to store characters. A character in java can represents all
ASCII as well as unicodes characters .
• There is only one type Character Primitive Data types :
• *Char (16 bits (2 bytes) )
=>Boolean Type: It is used to represent a single true/false
value. A Boolean value e have only one of two types :True or
False. In a java program, the words true and false always
mean these Boolean values. Boolean { java reserves 8 bits but
only uses 1 bit}.
• Reference Data types
Broadly a reference in java is a data element
whose value is an address of a memory
location. Arrays (a group of similar data items
), Class (a blue print of some entity e.g., a
student ) and interfaces are reference types.
=> Variables: A variable is a named memory
location, which holds a data value of a
particular data type.
Declaration of a variable: The declaration
of a variable takes the following form:
Data type name of the variable;
Example:
int age;
Initialization of a variable:
name of the variable= value
Example: age=20;
=>Dynamic Initialization: A variable can be
initialized at run time using expression at the place of
declaration.
Example:
float avg,sum;
int count;
avg =sum/count; // Dynamic Initialization
Example: double a=3.0,b=4.0;
Double c= math.sqrt(a*a+b*b);
=>Initial(default) values of variable:
Each variable in a
program must have a value before its value is used.
Data type
Default value
Data type
Default value
byte
0
Double
0.0D
Short
0
Chart
Null character(‘\u0000’)
int
0
Boolean
false
long
oL
All reference types
null
float
0.0F
• Text Interaction in GUIs
• For text interaction in a GUI, you need to use
basically four types of methods :
• getText( ) method
• parse------( ) methods
• setText( ) method
• JoptionPane.showMassageDialog() Method.
1.getText ( ) method : Obtaining text from a GUI component.
A get Text ( ) method returns the currently stored in a text based on GUI
component. The Swing components that support getText ( ) method
include : Text Field, Text Area , Button , Label , Checkbox and Radio
Button.
=>The getText( ) returns a value of string type, so we store then value
returned by getText( ) in String type variable .Thus ,complete statement to
obtain text from title field would be :
• String str1 = titleTF.getText( );
• String str2 = fNameTF.getText( );
• String srt3 = lNameTF.getText( );
2.Parse---------( ) method -Obtaining Number from GUI component.
It is use text type components GUI but you intend to use it for obtaining
numeric values .It is used to convert Textual data into a numeric type.
• 1.Byte.parseByte(String s) // converts strings into a byte type value
• 2.Short.parse Short(string s) // converts strings into a short type value
• 3.Integer.parse Into(string s) // converts strings into a int type value
• 4.Long.parse Long(string s) // converts strings into a long type value
• 5.Float.parse Float(string s) // converts strings into a float type value
• 6.Double.parse Double(string s) // converts strings into a double type
value
3.SetText()method -Storing text into a GUI
component. A setText( ) method stores or changes
text in a text based GUI component. The swing
components that support setText( )method include :
TextrArea,Button,Label,CheckBox, and
Radio
Button.
=>System.out.print() and System.out.println()
methods are used to output in non-GUI manner.
These methods output the information on standard
output device, which is generally a monitor.
If you write:
System.out.print(“ Hello world”);
Then on the monitor ,it will display
Hello world
4. JoptionPane.showMassageDialog()
Method: Displaying message in a dialog form.
To use this method, you need to perform it in
two steps:
(a). Firstly , in the source editor , where you
type your code, at most position type following
line:
import.javax.swing.JoptionPane;
(b). Now display desired message as per
following syntax:
JOPtionPane.showMessageDialog(null, “
desired message here”);
=>Variable Scope: Scope generally refers to programregion within which a variable is accessible. the variable
is accessible within the set of braces it is declared in.
=>Constants: Constants means that the value can not
be changed during program execution. The reserved
word final tells the compiler that the value will not
changed in the program. The name of constants follow
the same rules as the name for variables.
Advantages of Constants
1. They make your program easier to read and check
for correctness.
2. If a constant need to be changed { for instance a
new tax law changes the rates } all you need to do is
changed the declaration . you don't have to search
through your program for every occurrence of specific
number.
=> OPERATORS: “An operator is a
symbol (+,-,*,/) that directs the
computer to perform certain
mathematical or logical manipulations
and is usually used to manipulate data
and variables”
=>The objects of the operation(s) are
referred to as Operands.
Ex:
a+b
operands
Operator
Arithmetic Operators
=>Unary Operator: It act on one operand .
=> Unary +: The operator unary ‘+’ precedes an
operand.
Example: if a=5 then +a means 5.
=> Unary -: The operator unary ‘-’ precedes an
operand.
Example: if a=5 then -a means -5.
Arithmetic Operators
=>Arithmetic operators +, -, * are the same
as in math
=>Division operator / if used on integers
returns integer (without rounding) or
exception
=>Division operator / if used on real
numbers returns real number or Infinity or
NaN
=>Remainder operator % returns the
remainder from division of integers.
If nominator is less than denominator then
remainder is always the nominator value.
=> Binary Operator: It act upon two
operands .
Arithmetic operators
Operator
+
*
/
Description
Adds two operands
Subtracts second operand from
the first
Multiply both operands
Divide numerator by denumerator
Example
A + B will give 30
,if A=20 and B=10
A - B will give -10
A * B will give 200
B / A will give 2
%
Modulus Operator and remainder
B % A will give 0
of after an integer division
++
Increment operator, increases
integer value by one
A++ will give 11
Decrement operator, decreases
integer value by one
A-- will give 9
--
Increment(++) & Decrement(– –)
Operators
JAVA supports 2 useful operators
namely
1. Increment ++
2. Decrement – – operators
=>The ++ operator adds a value 1 to
the operand
=>The – – operator subtracts 1 from
the operand
++a
//pre-increment
a++ //post-increment
– –a //pre- Decrement
a– – //post- Decrement
Rules for ++ & -- operators
1. These
require
variables
as
their
operands
2. The postfix either ++ or – – operators
follow use-then-change rule i.e., they first
use the value of their operand in evaluating
the expression and then change(++/ – – ) the
operand value .
3. The prefix either ++ or – – operators
follow change-then-use rule i.e., they first
change(++/ – – ) the value of their operand,
then use the new value in evaluating the
expression.
Examples for ++ & -- operators
Let the value of a =5 and b=++a then
a = b =6
Let the value of a = 5 and b=a++ then
a =6 but b=5
i.e.:
1. a prefix operator first adds 1 to the
operand and then the result is
assigned to the variable on the left
2. a postfix operator first assigns the
value to the variable on left and then
increments the operand.
Q.1: Evaluate z=++x + x++ if x=10 initially.
Output:22
Relational Operators: The relational
operators determine the relation
among different operands.
Operator
Meaning
<
Is less than
<=
Is less than or equal to
>
Is greater than
>=
Is greater than or equal to
==
Equal to
!=
Not equal to
Operator
==
!=
>
<
>=
<=
Description
Checks if the value of two operands is
equal or not, if equal then condition
becomes true.
Checks if the value of two operands is
equal or not, if values are not equal then
condition becomes true.
Checks if the value of left operand is
greater than the value of right operand,
if yes then condition becomes true.
Checks if the value of left operand is
less than the value of right operand, if
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
right operand, if yes then condition
becomes true.
Checks if the value of left operand is
less than or equal to the value of right
operand, if yes then condition becomes
Example
(A == B) is true.
(A != B) is true.
(A > B) is true.
(A < B) is true.
(A >= B) is true.
(A <= B) is true.
Logical Operators:
There are following logical operators supported by
C++ language
Operator
Meaning
&&
Logical AND
||
Logical OR
!
Logical NOT
Logical expression or a compound relational expression:
An expression that combines two or more relational
expressions
Ex: if (a==b && b==c)
operator
&&
Description
Example
Called Logical AND operator. If (A && B) is false.
both the operands are non zero If any input values
then condition becomes true.
is zero
||
Called Logical OR Operator. If
any of the two operands is non
(A || B) is true.
zero then condition becomes
true.
!
Called Logical NOT Operator.
Use to reverses the logical
state of its operand. If a
condition is true then Logical
NOT operator will make false.
!(A && B) is true.
Truth Table
a b
0 0
Value of the expression
a && b
a || b
0
0
0 1
0
1
1 0
1 1
0
1
1
1
Conditional(Ternary) operators
Syntax:
exp1 ? exp2 : exp3
Where exp1,exp2 and exp3 are expressions
Working of the ? Operator:
Exp1 is evaluated first, if it is nonzero(1/true)
then the expression2 is evaluated and this
becomes the value of the expression,
If exp1 is false(0/zero) exp3 is evaluated and its
value becomes the value of the expression
Ex: m=2;
n=3
r=(m>n) ? m : n;
Output: r=3
Assignment Operators:
Operator
=
Description
Simple assignment operator, Assigns values from right side
operands to left side operand
Example
C = A + B will assign value of
A + B into C
+=
Add AND assignment operator, It adds right operand to the left C += A is equivalent to C = C +
operand and assign the result to left operand
A
-=
Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C = C from the left operand and assign the result to left operand
A
*=
Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C = C *
with the left operand and assign the result to left operand
A
/=
Divide AND assignment operator, It divides left operand with
the right operand and assign the result to left operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to C = C
operands and assign the result to left operand
%A
<<=
Left shift AND assignment operator
C <<= 2 is same as C = C << 2
>>=
Right shift AND assignment operator
C >>= 2 is same as C = C >> 2
&=
Bitwise AND assignment operator
C &= 2 is same as C = C & 2
^=
bitwise exclusive OR and assignment operator
C ^= 2 is same as C = C ^ 2
|=
bitwise inclusive OR and assignment operator
C |= 2 is same as C = C | 2
Special operators
1.
2.
3.
4.
Comma operator ( ,)
sizeof operator – sizeof( )
Pointer operators – ( & and *)
Member selection operators – ( . and ->)
=>The [ ] Operator: The square brackets are used to declare
arrays
Example: float [ ] array of floats=new float[10];
=>access the 7th array element.
array of floats[6];
=> The . Operator: The (dot) . Operator accesses instance
members of an object or class members of a class.
=> The parenthesis ( ) Operator: when declaring or
calling a method, the method’s arguments are listed between
parenthesis ( and ).
=> The (Type ) Operator: It Converts a value to the
specified type.
=>The new Operator: The new operator is used to create a
new object or a new array.
=> The instance of Operator: The instanceof operator tests
whether its first operand is an instance of its second. Example:
op1 instanceof op2; where op1 must be the name of an object
and op2 must be the name of a classs.
Precedence of operators: Operator precedence
determines the grouping of terms in an
expression. This affects how an expression is
evaluated.
Certain
operators
have
higher
precedence than others; for example, the
multiplication operator has higher precedence
than the addition operator:
=>BODMAS
RULE:
Brackets
of
Division
Multiplication Addition Subtraction
Brackets will have the highest precedence and have
to be evaluated first, then comes of , then comes
division,
multiplication,
addition
and
finally
subtraction.
C++ language uses some rules in evaluating the
expressions and they r called as precedence rules
or sometimes also referred to as hierarchy of
operations, with some operators with highest
precedence and some with least.
The 2 distinct priority levels of arithmetic operators
in c++ areHighest priority : * / %
Lowest priority : + -
Rules for evaluation of expression
1.
2.
3.
4.
5.
6.
First parenthesized sub expression from left
to right are evaluated.
If parentheses are nested, the evaluation
begins with the innermost sub expression
The precedence rule is applied in determining
the order of application of operators in
evaluating sub expressions
The associatively rule is applied when 2 or
more operators of the same precedence level
appear in a sub expression.
Arithmetic expressions are evaluated from
left to right using the rules of precedence
When parentheses are used, the expressions
within parentheses assume highest priority
Here operators with the highest precedence appear at the
top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be
evaluated first.
Category
Postfix
Unary
Multiplicative
Additive
Shift
Relational
Equality
Bitwise AND
Bitwise XOR
Bitwise OR
Logical AND
Logical OR
Conditional
Assignment
Comma
Operator
() [] -> . ++ - -
Associativity
Left to right
+ - ! ~ ++ - - (type)* & sizeof
Right to left
*/%
+<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Left to right
Right to left
= += -= *= /= %=>>= <<= &= ^= |= Right to left
,
Left to right
Example 1
Evaluate
x1=(-b+ sqrt (b*b-4*a*c))/(2*a) @ a=1, b=-5,
c=6
=(-(-5)+sqrt((-5)(-5)-4*1*6))/(2*1)
=(5 + sqrt((-5)(-5)-4*1*6))/(2*1)
=(5 + sqrt(25 -4*1*6))/(2*1)
=(5 + sqrt(25 -4*6))/(2*1)
=(5 + sqrt(25 -24))/(2*1)
=(5 + sqrt(1))/(2*1)
=(5 + 1.0)/(2*1)
=(6.0)/(2*1)
=6.0/2 = 3.0
Arithmetic Expressions
Relational Expressions
Compound Expressions
Arithmetic Expressions
can either be integer
expressions
or
real
expressions. Sometimes
a mixed expressions can
also be formed which is
a mixer of real and
integer expressions.
• Integer Expressions are formed by
connecting integer constants and/or
integer
variables using integer
arithmetic operators. The following
are valid integer expressions :
• int I,J,K,X,Y,Z,count;
• A) k - x
• B) k + x – y + count
• C) –j + k * y
• D) z % y
=> Math Function
• Real Expressions are formed by
connecting real constants and/or
real variables using real arithmetic
operators. The following are valid
real expressions:
• float qty,amount,,value;
• double fin,inter; const bal=250.53;
• i) qty/amount
• ii) (amount + qty*value)-bal
• iii) fin + qty* inter
• iv) inter – (qty * value) + fin
The process of converting one
predefined type into another
is called Type Conversion.
Java facilitates the type
conversion in two forms:
An implicit type conversion is a
conversion performed by the compiler
without programmer’s intervention.
An implicit conversion is applied
generally whenever differing data
type are intermixed in an expression,
so as not to lose information.
An
explicit
type
conversion is user-defined
that forces an expression
to be of specific type.
The java compiler converts
all operands upto the type of
the largest operand, which is
called Type Promotion.
The
explicit
conversion of
an
operand
to
a
specific
type
is
called type casting.
The
expressions
that
result into 0(false) or
1(true) are called logical
expressions. The logical
expressions
are
combination of constants,
variables and relational
operators.
A
Logical
Expressions
may
contain
just
one
signed
or
unsigned variable or a constants,
or it may have two or more
variables or/and constants, or two
or more expressions joined
by
valid relational and/or logical
operators. Two or more variables
or operators should not occur in
continuation.
Target Type
Expression Type
Possible Info
Loss
signed char
char
char
short int
High-order 8 bits
char
int
High-order 8 bits
char
long int
High-order 8 bits
int
long int
High-order 16 bits
int
float
Fractional part and
possibly more
float
double
Precision, result rounded
double
long double
Precision, result rounded
If value >127, target is
negative
 JAVA offers special shorthands that
simplify the coding of a certain type of
assignment statement.
 Following are some example of JAVA
shorthands:
 x - = 10 ;
equivalent to x = x – 10;
x * = 3 ;
equivalent to x = x * 3;
x / = 2 ;
equivalent to
x = x/2 ;
x % = z ;
equivalent to x = x % z ;
=>
Java
Statement:
A
statement
represents an action or a sequence of
actions.
The
statement
System.out.println("Welcome
to
Java!"); in the program in Example 1.1
is a statement to display the greeting
"Welcome to Java!" Every statement in
Java ends with ;
=> Null or Empty statement: The
statements are terminated with a
semicolon ; . The simplest statement of
them all is the empty ,or null statement.
;
It is null statement.
=> BLOCK: It is agroup of zero or more
statements between pair of braces{ }
in a program forms a and can be
used anywhere a single statement
is allowed.
public class Test {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Class block
Method block
=> Java Statement:
=> Java Statement:
=> Java Statement:
=> Java Statement:
=> Java Statement:
In
Java,
comments are preceded by two slashes
(//) in a line, or enclosed between /* and
*/ in one or multiple lines. When the
compiler sees //, it ignores all text after //
in the same line. When it sees /*, it scans
for the next */ and
=>Comments
Line:
=>END