0
JAVA Character Set
Character set is a set of valid characters that a language can recognise.
A Character represents any le...
Token
The smallest individual unit in a program is known as Token.
In a Java program, all characters are grouped into symb...
Keywords
Keywords are words that have a specific predefined meaning in Java.
They cannot be used as variable names.

These...
Identifiers :
Identifiers are fundamental building blocks of a program and are used as the
General terminology for the nam...
Literals:
Items having fixed data values are referred to as Literals.
They are also known as Constants.
Various types of l...
Literals
Literals (often referred to as constants) are data items that never change their value
during a program run.
JAVA...
Integer Constants

Integer constants are whole numbers without any fractional part. The method of writing
integer constant...
JAVA allows three types of integer constants:
1. Decimal (base 10)

2. Octal (base 8)

3. Hexadecimal (base 16)

1. Decima...
Character Constants
A character constant is one character enclosed in single quotes. The rule for
writing character consta...
Following table gives a listing of escape sequences:
a
b
f
n
r
t
v

'
"
?
On
xHn
o
Audible bell (alert)
Backspace
Formfeed...
Floating Constants

Floating constants are also called real

constants.

Real constants are numbers having fractional part...
A real constant in exponent form consists of two parts: mantissa and exponent.
For instance, 5.8 can be written as 0.58 x ...
terminator character

String Literals
'Multiple Character' constants are treated as string-literals. The rule for writing
...
Null Literal :
The null type has one value, the null reference represented by the literal null,
Which is formed from ASCII...
Operators:
Operators are special symbols that perform specific operations on
one, two, or three operands, and then return ...
Data Types
To Identify the type of data and associated operations of handling it.
Java data types are of two types
1) Prim...
Primitive Data Types:
A primitive type is predefined by the language and is named by a reserved keyword.
Thus by primitive...

float: The float data type is a singleprecision32bitIEEE 754 floating point.

double: The double data type is a doublep...
Reference Data Types :
Reference data types store the memory address of an object.
Class, Interface and Array are the exam...
Variables :
Variable is a named storage locations, which holds a data value of a particular data
Type. And whose value can...
Initialization of Variables :
int salary;
A simple definition does not provide a first value or initial value to the varia...
TEXT Interaction in GUI
There are four types of methods
1) getText() 2) parse …..() , 3) setText() 4) JOptionPane.showMess...
Parse …. () Methods – Obtaining numbers from a GUI component
Sometimes, you use text type components in a GUI but you inte...
You can combined code to obtain numeric input from a text field
int a=Integer.parseInt(nameTextField.getText());

System.o...
setText() Method :- Storing text into a GUI component
A setText() method stores or changes text in a text based GUI compon...
JOptionPane.showMessageDialog() Method :- Displaying message in a dialog form
You can produce a basic dialog displaying a ...
Variable Scope :Scope generally refers to the program-region within which a variable is accessible.
The broad rule is : a ...
Constants :
If you do not want to change a value during a program run.
With the final keyword

final double pi=3.14;

Adva...
Operators in JAVA :The operations are represented by operators and the objects of the operations are
referred to as operan...
Binary operators :Operators that act upon two operands are referred to as binary operators.
For example :- These operators...
Operator + with Strings
For example
5+6=11

“5” + “6”=“56”
“abc” + “123” = “abc123”
“ “ +5 + “xyz”= “5xyz”
Increment/Decrement Operators (+ +, --)

JAVA includes two useful operators not generally found in other computer
language...
However, both the increment and decrement operators come in two
varieties : they may either precede or follow the operand....
Working with prefix version:- When an increment or decrement operator
precedes its operand (i.e., in its prefix form), JAV...
Working with postfix version:- When an increment or decrement operator
follows its operand and (i.e., in its postfix form)...
The increment operator + + and decrement operator - - are unary operators
i.e., they operate upon single operand.
Evaluate x = + + Y + 2y if y = 6.

Evaluate b= a + + + + + a if a is 10 initially.

Evaluate z = + +x + x+ + if x = 15 ini...
Relational Operators
In the term relational operator, relational refers to the relationships

that values (or operands) ca...
The six relational operators are :
< (less than)
<= (less than or equal to)
== (equal to)
> (greater than)
>= (greater tha...
Relational Operators
Symbol
==

Name
comparison (equality)

Example

Result

6==5

o i.e. false

Comment
returns boolean t...
The relational operators have a lower precedence than the arithmetic operators.e

Some tips regarding relational operators...
Predict the output of following code segment

int chk = 6 ;
cout « "chk = = 8 is" « chk = = 8 « "n" ;
cout « "chk = 8 is" ...
Tip :- Avoid equality comparison on floating-point numbers

Floating-point arithmetic is not as exact and accurate as the ...
Logical Operators
Relational operators that establish relationships among the values. Logical
operators that refer to the ...
The logical OR operator (||)
The logical OR operator (||) combines two expressions which make its
operands.
The logical OR...
Following are some examples of logical OR operation:

(4 = = 4) || (5 = = 8)

0 || 0

results into 1 (true) because first ...
The logical AND operator (&&)
The logical AND operators, written as &&, also combines two expressions

into one. The resul...
some examples of AND operator (&&).

(6 = = 3) && (4 = = 4)

results into 0 (false) because first expression is

false.
(4...
The Logical NOT operator ( ! )
The logical NOT operator, written as !, works on single expression or operand
i,e., it is a...
some examples of logical NOT operation:
! (5)

results into 0 (false) because 5 is non zero (i.e., true)

! (0)

results i...
Logical Operators
Sym
bol

Name

Example

Result

&&

And

(6<=6)&&(5<3)

0

Comment
returns boolean truth value (0 for fa...
JAVA offers special shorthands that simplify the coding of a certain type of
assignment statement.
For example,
a = a + 10...
The general form of JAVA shorthand is
var = var operator expression

Is same as
var operator = expression

Following are s...
Conditional Operator ? :
JAVA offers a conditional operator (?:) that stores a value depending upon

a condition. operator...
For Example :result = marks >= 50 ? ' P' : ' F' ;
The identifier result will have value 'P' if the test expression marks >...
An expression is composed of one or more operations. The objects of the
operation(s) are referred to as operands. The oper...
Type of operators used in an expression determine the expression type.
For instance, if expression is formed using arithme...
Arithmetic Expressions
Arithmetic expressions can either be integer expressions or real expressions.
Sometimes a mixed exp...
Real expressions are formed by connecting real constants and/or real
variables using real arithmetic operators (e.g., % is...
The process of converting one predefined type into another is called
Type conversion

JAVA facilitates the type conversion...
(i) Implicit type conversion. An implicit type conversion is a
conversion performed by compiler without programmer's inter...
This is done operation by operation, as described in the following type
conversion algorithm:
1. Otherwise, if either oper...
(ii) Explicit type conversion. An explicit type conversion is user-defined
that forces an expression to be of specific typ...
Type casting in JAVA is done as shown below:
(type) expression
where type is a valid JAVA data type to which the conversio...
Assigning a value to a type with a greater range (e.g., from short to long) poses
no problem, however, assigning a value o...
There are some other similar potential conversion problems that are listed below

Conversion

Potential Problems

Bigger f...
In JAVA, when a mixed expression is evaluated, it is first divided into
component sub-expressions upto the level of two op...
logical Expressions

The expressions that result into 0 (false) or 1 (true) are called logical
expressions. The logical ex...
An expression is composed of one or more operations. An expression
terminated ; semicolon) becomes a statement. Statements...
Following are some examples of assignment statements:
x = 14;
Y = 3.2;

Z =x + y;
Z = z * x;
A =b + e - d;

The symbol '='...
Block
A Block is a group of zero or more statement between balanced braces and
can be used anywhere a single statement is ...
Null or Empty Statement
The Simplest statement of them all is the empty or null statement
It takes in the following statem...
Q.No.1 Given the following code fragment
int ch = 20 ;
System.out.println(++ch);
System.out.println(ch);
i) What output do...
Q. no. 5Given the following set of identifiers :
byte b ; char ch; short sh; int intval; long longval ; float fl;
Identify...
Q. no. 11 What would be the output of the following program ?
float p = 10.45f;
p= p++ + 1;
jTextField1.setText( “ p = “ +...
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Programming fundamental
Upcoming SlideShare
Loading in...5
×

Programming fundamental

332

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
332
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
10
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Programming fundamental"

  1. 1. JAVA Character Set Character set is a set of valid characters that a language can recognise. A Character represents any letter, digit or any other sign. Java uses the Unicode character set. Unicode is a two-byte character code set that has characters representing almost all characters in almost all language and writing Systems around all the world including English, Arabic, Chinese etc.
  2. 2. Token The smallest individual unit in a program is known as Token. In a Java program, all characters are grouped into symbols called tokens. Java has the following types of tokens: keyword , Identifier, literal, punctuators,operators. lower-case <= a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z upper-case <= A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z alphabetic <= lower-case | upper-case numeric <= 0|1|2|3|4|5|6|7|8|9 alphanumeric <= alphabetic | numeric special <= !|%|^|&|*|(|)|-|+|=|{|}|||~|[|]||;|'|:|"|<|>|?|,|.|/|#|@|`|_ graphic <= alphanumeric | special
  3. 3. Keywords Keywords are words that have a specific predefined meaning in Java. They cannot be used as variable names. These are reserved for special purpose. They are also known as reserve words. abstract assert boolean break byte case catch char class const continue goto package switch default if private this do implements protected throw double import public throws else instanceof return transient extends int short try final interface static void finally long strictfp volatile float native super while for new synchronized
  4. 4. Identifiers : Identifiers are fundamental building blocks of a program and are used as the General terminology for the names given to differnent parts of the program i.e. Variables, objects, classes, functions, arrays, packages etc. Identifiers forming rules of java state the following 1. Identifier can have alphabets, digits and underscore and doller sign characters. 2. They must not be a keyboard or boolean literal or null literal. 3. They must not begin with a digit. 4. They can be of any length. 5. Java is case sensitive.
  5. 5. Literals: Items having fixed data values are referred to as Literals. They are also known as Constants. Various types of literals available in Java are :  Integer literals  Floating literals  Boolean literals  Character literals  String literals  Null literals
  6. 6. Literals Literals (often referred to as constants) are data items that never change their value during a program run. JAVA allows several kinds of literals: 1. Integer Constant 2. Floating Constant 3. Character Constant 4. String Constant Literals
  7. 7. Integer Constants Integer constants are whole numbers without any fractional part. The method of writing integer constants has been specified in the following rule: An integer constant must have at least one digit and must not contain any decimal point. It may contain either + or - sign. A number with no sign is assumed to be positive. Commas cannot appear in an integer constant.
  8. 8. JAVA allows three types of integer constants: 1. Decimal (base 10) 2. Octal (base 8) 3. Hexadecimal (base 16) 1. Decimal Integer Constants. An integer constant consisting of a sequence of digits is taken to be decimal integer constant unless it begins with a (digit zero). For instance, 1234,41, + 97, -17 are decimal integer constants. 2. Octal Integer Constants. A sequence of digits starting with 0 (digit zero) is taken to be an octal integer. For instance, decimal integer 8 will be written as 010 as octal integer. and decimal integer 12 will be written as 014 as octal integer 3. Hexadecimal Integer Constants. A sequence of digits preceded by Ox or OX is taken to be an hexadecimal integer. For instance, decimal 12 will be written as oxe as hexadecimal integer. Thus number 12 will be written either as 12 (as decimal), 014 (as octal) and oxe (as hexadecimal). The suffix I or Land u or U attached to any constant forces it to be represented as a long and unsigned respectively.
  9. 9. Character Constants A character constant is one character enclosed in single quotes. The rule for writing character constant is given below: A character constant in JAVA must contain one character and must be enclosed in single quotation marks. JAVA allows you to have certain nongraphic characters in character constants. Nongraphic characters are those characters that cannot be typed directly from keyboard e.g., backspace, tabs, carriage return etc. These nongraphic characters can be represented by using escape sequences. An escape sequence is represented by a backslash () followed by one or more characters.
  10. 10. Following table gives a listing of escape sequences: a b f n r t v ' " ? On xHn o Audible bell (alert) Backspace Formfeed Newline or !inefeed Carriage Return Horizontal tab Vertical tab Backslash Single quote Double quote Question mark Octal number (On represents the number in octal) Hexadecimal number (Hn represents the number in hexadecimal) Null
  11. 11. Floating Constants Floating constants are also called real constants. Real constants are numbers having fractional parts. These may be written in one of the two forms called fractional form or the exponent form. A real constant in fraction form consists of signed or unsigned digits including a decimal point between digits. The rule for writing a real constant in fractional form is given below: note :- A real constant in fractional form must have at least one digit before a decimal point and at least one digit after the decimal point. It may also have either + or - sign preceding it. A real constant with no sign is assumed to be positive. The following are valid real constants in fractional form : 2.0, 17.5, - 13.0, - 0.00625 The following are invalid real constants : 7 (No decimal point) 7. (No digit after decimal point) + 17/2 (I-illegal symbol) 17,250.26.2 (Two decimal points) 17,250.262 (comma not allowed)
  12. 12. A real constant in exponent form consists of two parts: mantissa and exponent. For instance, 5.8 can be written as 0.58 x 101 =0.58 an where mantissa part is 0.58 (the part appearing before E) and exponent part is 1 (the part appearing after E). E01 represents ~01. The rule for writing a real constant in exponent formis given below: A real constant in exponent form has two parts: a mantissa and an exponent. The mantissa must be either an integer or a proper real constant. The mantissa is followed by a letter E or e and the exponent. The exponent must be an integer. The following are the valid real constants in exponent form : 152E05, 1.52E07, 0.152E08, 152.0E08, 152E+8, 1520E04, -O.172E3 The following are invalid real constants in exponent form: (i) 172.E5 (ii) 1.7E (At least a digit must follow the decimal point) (No digit specified for exponent) (iii) 0.17E2.3 (Exponent can not have fractional part) (iv) 17,225E02 (No comma allowed) (v) .25E-7 (No preceding digits before decimal point)
  13. 13. terminator character String Literals 'Multiple Character' constants are treated as string-literals. The rule for writing string-literal is given below : A string literal is a sequence of characters surrounded by double quotes Each character may be represented by an escape sequence. A string literal is of class type String. And each character takes 2 bytes. For instance, "abc" size is 6 bytes. “ab”
  14. 14. Null Literal : The null type has one value, the null reference represented by the literal null, Which is formed from ASCII characters. A null literal is always of the null type. Separators : The following nine ASCII character are the separators (punctuators) () {} [] ; , .
  15. 15. Operators: Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Operators Precedence postfix expr++ expr unary ++exprexpr+exprexpr~ ! multiplicative * / % additive + shift <<>>>>> relational <><= >= instanceof equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || ternary ? : assignment = += =*= /= %= &= ^= |= <<= >>= >>>=
  16. 16. Data Types To Identify the type of data and associated operations of handling it. Java data types are of two types 1) Primitive data types 2) Reference Data Types
  17. 17. Primitive Data Types: A primitive type is predefined by the language and is named by a reserved keyword. Thus by primitive data types, we mean fundamental data types offered by JAVA. The eight primitive data types supported by the Java programming language are:  byte: The byte data type is an 8bit signed two's complement integer. It has a minimum value of -128 and a maximum value of +127 (inclusive).  short: The short data type is a 16bit signed two's complement integer. It has a minimum value of -32,768and a maximum value of +32,767 (inclusive).  int: The int data type is a 32bitsigned two's complement integer. It has a minimum value of2,147,483,648and a maximum value of 2,147,483,647 (inclusive).  long: The long data type is a 64bitsigned two's complement integer. It has a minimum value of 9,223,372,036,854,775,808and a maximum value of 9,223,372,036,854,775,807(inclusive).
  18. 18.  float: The float data type is a singleprecision32bitIEEE 754 floating point.  double: The double data type is a doubleprecision64bitIEEE 754 floating point.  boolean: The boolean data type has only two possible values: true and false. Use this data typefor simple flags that track true/false conditions.  char: The char data type is a single 16bitUnicode character. It has a minimum value of'u0000' (or 0) and a maximum value of 'uffff ' (or 65,535 inclusive). Boolean Type :- Boolean data type used to represent a single ture/false value. a Boolean value can have only one of two values : True or False. Value Datatype Value 178 26.34e2 87.363F 37.266 8864L 37.266D True 26.77e3 ‘c’ false Datatype
  19. 19. Reference Data Types : Reference data types store the memory address of an object. Class, Interface and Array are the example of Interface Reference Data types. A reference is called a pointer or a memory address in other language. An importance reference type that you are use in JAVA is String type. The String data type lets you create variables that can hold textual data. “RAM”, “House_No_68”, “500”, AB56”
  20. 20. Variables : Variable is a named storage locations, which holds a data value of a particular data Type. And whose value can be manipulated during program run. Declaration of a variable The Syntax is type variable_name; Example int age; double amount; float marks; When a more than one identifier of a same type double salary,wage; int month,day,year; Long dis,area;
  21. 21. Initialization of Variables : int salary; A simple definition does not provide a first value or initial value to the variable i.e. Variable is uninitialized and the variable’s value is said to be undefined. A variable with a declared first value is said to be initialised variable. int salary=30000; double price=200.50, discount=0.10; float a=0.20f; Dynamic initialization A call to a method, in which case the return value determines the initialization. For example int a=10,b=4; int c=Math.sqrt(a*a + b*b); System.out.println(“The Result is “ +c); Default initial value of variables
  22. 22. TEXT Interaction in GUI There are four types of methods 1) getText() 2) parse …..() , 3) setText() 4) JOptionPane.showMessageDialog() 1 ) getText() Method :- Obtaining text from a GUI Component A getText() method returns the text currently stored in a text based GUI component. The Swing components that support getText() method include : Text Field, Text Area, Button, Label,Check Box and Radio Button. To obtain text from nameTextField, you need to write : nameTextField.getText(); Complete statement to obtain text from nameTextField store in a variable :
  23. 23. Parse …. () Methods – Obtaining numbers from a GUI component Sometimes, you use text type components in a GUI but you intend to use it for Obtaining numeric values e.g. you may want to read age of a person through a text Field. So you need a method that helps you convert this textual data into a numeric type. There are many parse…..() methods that help you parse string into different numeric Types. 1) 2) 3) 4) 5) 6) Byte.parseByte(String s); Short.parseShort(String s); Integer.parseInt(String s); Long.parseLong(String s); Float.parseFloat(String s); Double.parseDouble(String s); First , you have to obtain text from nameTextField by typing a statement like String str=nameTextField.getText(); After that int a=Integer.parseInt(str);
  24. 24. You can combined code to obtain numeric input from a text field int a=Integer.parseInt(nameTextField.getText()); System.out.print – NON GUI Output Method If you write System.out.println(“Hello World”); If you write System.out.println(“Hello ”); System.out.println(“World”); But if you write System.out.print(“Hello ”); System.out.print(“World ”);
  25. 25. 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 : Text Field, Text Area, Button, Label,Check Box and Radio Button. If you want to change the nameTextField nameTextField.setText(“Rajeev Verma”); String str=“Rajeev Verma” nameTextField.setText(str);
  26. 26. JOptionPane.showMessageDialog() Method :- Displaying message in a dialog form You can produce a basic dialog displaying a message to the user. The user will see your message with only an “OK” button to close the dialog. To use this method, you need to perform it in two steps : 1) Firstly, in the source editor, where you type your code, at top most position type the following line. import javax.swing.JOptionPane; 2) Now display desired message as per following syntax ; JOptionPane.showMessageDialog(null, “<Desired message here>”); for example :
  27. 27. Variable Scope :Scope generally refers to the program-region within which a variable is accessible. The broad rule is : a variable is accessible within the set of braces it is declared in { int a; ……. ………….. } For example Public class ex4 { int x; x=10; if(x==10) { int y=20; x=y*2; } y=100; System.out.println(“x is “ +x); Sytem.out.println(“ y is “ +y);
  28. 28. Constants : If you do not want to change a value during a program run. With the final keyword final double pi=3.14; Advantages of Constants : 1) They make your program easier to read and check for correctness. 2) If a constant needs to be changed all you need to do is change the declaration.
  29. 29. Operators in JAVA :The operations are represented by operators and the objects of the operations are referred to as operands. Unary operators :Operators that act on one operand are referred to as Unary operators. 1. Unary + :- + precedes an operand. for example if a=5 then +a means +5 if a =-4 1. 2. Unary - :- - precedes an operand. for example if a=5 then –a means -5 if a =-4
  30. 30. Binary operators :Operators that act upon two operands are referred to as binary operators. For example :- These operators perform addition, subtraction, multiplication, and division. These symbols are similar to mathematical symbols. The only symbol that is different is "%", which divides one operand by another and returns the remainder as its result. + addition operator - subtraction operator * multiplication operator / division operator % remainder operator
  31. 31. Operator + with Strings For example 5+6=11 “5” + “6”=“56” “abc” + “123” = “abc123” “ “ +5 + “xyz”= “5xyz”
  32. 32. Increment/Decrement Operators (+ +, --) JAVA includes two useful operators not generally found in other computer languages (except C and C++). These are the increment and decrement operators, + + and - -. The C++ name itself is influenced by the increment operator + +. The operator + + adds 1 to its operand, and --subtracts one.
  33. 33. However, both the increment and decrement operators come in two varieties : they may either precede or follow the operand. The prefix version comes before the operand (as in ++a or --a) and the postfix version comes after the operand (as in a + + or a --). The two versions have the same effect upon the operand, but they differ when they take place in an expression.
  34. 34. Working with prefix version:- When an increment or decrement operator precedes its operand (i.e., in its prefix form), JAVA performs the increment or decrement operation before using the value of the operand. For example, the expression . The prefix increment or decrement operators follow change-then-use rule i.e., they first change (increment or decrement) the value of their operand. then use the new value in evaluating the expression sum = sum + (+ + count) ; The expression P = P * --N;
  35. 35. Working with postfix version:- When an increment or decrement operator follows its operand and (i.e., in its postfix form), C+ + first uses the value of the operand in evaluating the expression before incrementing or decrementing the operand's value. The postfix increment or decrement operators follow use-then-change rule i.e .• they first use the value of their operand in evaluating the expression , and then change (increment or decrement) the operand's value. For example, the exp sum = sum + count ++; The expression P = P * N--;
  36. 36. The increment operator + + and decrement operator - - are unary operators i.e., they operate upon single operand.
  37. 37. Evaluate x = + + Y + 2y if y = 6. Evaluate b= a + + + + + a if a is 10 initially. Evaluate z = + +x + x+ + if x = 15 initially.
  38. 38. Relational Operators In the term relational operator, relational refers to the relationships that values (or operands) can have with one another. Thus, the relational operators determine the relation among different operands. JAVA provides six relational operators for comparing numbers and characters, But they don't work with strings. If the comparison is true, the relational expression results into the value 1 and to 0, if the comparison is false.
  39. 39. The six relational operators are : < (less than) <= (less than or equal to) == (equal to) > (greater than) >= (greater than or equal to) ! = (not equal to)
  40. 40. Relational Operators Symbol == Name comparison (equality) Example Result 6==5 o i.e. false Comment returns boolean truth value (0 for false, 1 for true). < != greater than or equal to Not equal to 6<=5 0 1 6>5 1 0 6>=5 1 5>6 >= greater than 1 5>6 > 0 5<=6 less than or equal to 6<5 5<6 <= less than 0 6!=5 0 5!=6 0 returns boolean truth value. returns boolean truth value. returns boolean truth value. returns boolean truth value. returns boolean truth value.
  41. 41. The relational operators have a lower precedence than the arithmetic operators.e Some tips regarding relational operators. Do not confuse the = and the == operators. A very common mistake is to use the assignment operators = in place of the relational operator == . Do not confuse the testing the operator = = with the assignment operator (=). e
  42. 42. Predict the output of following code segment int chk = 6 ; cout « "chk = = 8 is" « chk = = 8 « "n" ; cout « "chk = 8 is" « chk = 8 « "n" ;
  43. 43. Tip :- Avoid equality comparison on floating-point numbers Floating-point arithmetic is not as exact and accurate as the integer arithmetic is. For instance, 3 * 5 is exactly 15, but 3.25 * 5.25 is nearly equal to 17.06 (if we are working with number with 2 decimal places). The exact number resulting from 3.25 * 5.25 is 17.0625.
  44. 44. Logical Operators Relational operators that establish relationships among the values. Logical operators that refer to the ways these relationships (among values) can be connected. C++ provides three logical operators to combine existing expressions. 1) || (logical OR) 2) && (logical AND) 3) ! (logical NOT)
  45. 45. The logical OR operator (||) The logical OR operator (||) combines two expressions which make its operands. The logical OR (||) operator evaluates to true i.e., 1 if either of its operands evaluate to true.
  46. 46. Following are some examples of logical OR operation: (4 = = 4) || (5 = = 8) 0 || 0 results into 1 (true) because first expression is true. results into 0 (false) because neither expression is true (both are 0 i.e., false). 5>8 || 5<2 results into 0 (false) because both expressions are false. 0 || 8 results into 1 (true) because second expression is true.
  47. 47. The logical AND operator (&&) The logical AND operators, written as &&, also combines two expressions into one. The resulting expression has the value 1 (true) only if both of the original expressions (its operands) are true.
  48. 48. some examples of AND operator (&&). (6 = = 3) && (4 = = 4) results into 0 (false) because first expression is false. (4 = = 4) && (8 = = 8) results into 1 (true) because both expressions are true. 6<9 && 4>2 results into 1 (true) because both expressions are true. 6>9 && 5<2 results into 0 (false) because both expressions are false.
  49. 49. The Logical NOT operator ( ! ) The logical NOT operator, written as !, works on single expression or operand i,e., it is a unary operator. The logical NOT operator (!) negates or reverses the truth value of the expression following it i.e., if the expression is true, then ! expression is false, and vice versa.
  50. 50. some examples of logical NOT operation: ! (5) results into 0 (false) because 5 is non zero (i.e., true) ! (0) results into 1 (true) because 0 is zero (i.e., false) ! (5 > 2) results into 0 (false) because the expression 5 > 2 is true i.e., 1. ! (5 > 9) results into 1 (true) because the expression 5 > 9 is false i.e., O.
  51. 51. Logical Operators Sym bol Name Example Result && And (6<=6)&&(5<3) 0 Comment returns boolean truth value (0 for false, (1 for true)) Both expressions must return 1 for && to return! II Or (6<=6)11(5<3) 1 one of the expressions must return 1 for || to return 1. ! Not ! (6 <= 6) 0 ! (5 > 9) 1 Negates the result of expression.
  52. 52. JAVA offers special shorthands that simplify the coding of a certain type of assignment statement. For example, a = a + 10 ; can be written as a + = 10 ; The operator pair + = tells the compiler to assign to a the value of a + 10. This shorthand works for all the binary operators in JAVA (those that require two operands).
  53. 53. The general form of JAVA shorthand is var = var operator expression Is same as var operator = expression Following are some examples of C+ + 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;
  54. 54. Conditional Operator ? : JAVA offers a conditional operator (?:) that stores a value depending upon a condition. operator is ternary operator i.e., it requires three operands. The general form of conditional operator ?: is as follows: expression1 ? expression2 : expression3 If expression1 evaluates to true i.e., 1, then the value of the whole expression is the value expression2, otherwise, the value of the whole expression is the value of expression3
  55. 55. For Example :result = marks >= 50 ? ' P' : ' F' ; The identifier result will have value 'P' if the test expression marks >= 50 evaluates to true (1) otherwise result will have value' F' A= 4==9 ? 10 : 25 int large = (( a > b ) ? (( a > c ) ? a : c ) : (( b > c ) ? b : c ));
  56. 56. An expression is composed of one or more operations. The objects of the operation(s) are referred to as operands. The operations are represented by operators. Therefore, operators, constants, and variables are the constituents of expressions. DEF. An expression in JAVA is any valid combination of operators, constants and variables. The expressions in JAVA can be of any type: arithmetic expression, relational (or logical expression, compound expression etc.
  57. 57. Type of operators used in an expression determine the expression type. For instance, if expression is formed using arithmetic operators, it is an arithmetic expression; if an expression relational and/or logical operators, it is a logical expression. An arithmetic expression always results in a number (integer or real) and a logical expression always results in a logical value either TRUE (1) or FALSE (0).
  58. 58. Arithmetic Expressions Arithmetic expressions can either be integer expressions or real expressions. Sometimes a mixed expression can also be formed which is a mixture 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: const count = 30 ; int I, J, K, X, Y, Z ; (a)I (b) -J (c) K-X (d) K + X - Y + count (e) -J + K * Y f) J/Z (g) Z % X
  59. 59. Real expressions are formed by connecting real constants and/or real variables using real arithmetic operators (e.g., % is not a real arithmetic operator). The following are valid real expressions : canst bal = 250.53 ; float qty, amount, value; double fin, inter ; (i) qty/amount (iii) (amount + qty * value) - bal (v) inter - (qty * value) + fin (ii) qty * value (iv) fin + qty * inter
  60. 60. The process of converting one predefined type into another is called Type conversion JAVA facilitates the type conversion in two forms 1. Implicit type conversion 2. Explicit type conversion
  61. 61. (i) Implicit type conversion. An implicit type conversion is a conversion performed by compiler without programmer's intervention. An implicit conversion is applied generally whenever differing data types are intermixed in an expression (mixed mode expression), so as not to lose information. The JAVA compiler converts all operands upto the type of the largest operand, which is type promotion.
  62. 62. This is done operation by operation, as described in the following type conversion algorithm: 1. Otherwise, if either operand is of type double, the other is converted to double 2.Otherwise, if either operand is float, the other is converted to float. 3 .Otherwise, the integral promotions are performed on both operands.
  63. 63. (ii) Explicit type conversion. An explicit type conversion is user-defined that forces an expression to be of specific type. The explicit conversion of an operand to a specific type is called type casting.
  64. 64. Type casting in JAVA is done as shown below: (type) expression where type is a valid JAVA data type to which the conversion is to be done. For example, to make sure that the expression (x + y /2) evaluates to type float, write it as : (float) (x + y / 2)
  65. 65. Assigning a value to a type with a greater range (e.g., from short to long) poses no problem, however, assigning a value of larger data type to a smaller data type (e.g., from double to float) may result in losing some precision.
  66. 66. There are some other similar potential conversion problems that are listed below Conversion Potential Problems Bigger floating-point type to smaller floating-point type (e.g., double to float) Loss of precision Floating point type to integer type Loss of fractional part. Bigger integer type to smaller integer type (e.g., long to short) Original value may be out of range for target type. Typically, just resulting in loss of information.
  67. 67. In JAVA, when a mixed expression is evaluated, it is first divided into component sub-expressions upto the level of two operands and an operator. Then the type of sub-expression is decided keeping in mind general conversion rules. Using the results of sub-expressions, the next higher level of expression is evaluated and its type is determined. This process is continued till you get the final result of the expression. Example Evaluate the following JAVA expression: int a, mb = 2. k = 4 ; a = mb * 3/4 + k /4 + 8 - mb + 5/ 8;
  68. 68. logical Expressions The expressions that result into 0 (false) or 1 (true) are called logical expressions. The logical expressions are combination of constants, variables and logical and relational operators The following are examples of some valid logical expressions : (i)x> y (ii) (y+ z>=(x/ z) (iii) (a + b>c && (c + d) > a (iv) (y >x)|| (z < y)
  69. 69. An expression is composed of one or more operations. An expression terminated ; semicolon) becomes a statement. Statements form the smallest executable unit within a JAVA program. Statements are terminated with a semicolon. An assignment statement assigns value to a variable. The value assigned may be a constant, variable or an expression. The general form of an assignment statement is as follows : a = eve; where a is the variable to whom the value is being assigned and eve can either be a constant or variable or an expression.
  70. 70. Following are some examples of assignment statements: x = 14; Y = 3.2; Z =x + y; Z = z * x; A =b + e - d; The symbol '=' is called the assignment operator.
  71. 71. Block A Block is a group of zero or more statement between balanced braces and can be used anywhere a single statement is allowed. If (Character.isUpperCase(aChar)) { Block label1.setText(“The Character “ + aChar + “is upper Case”); } else { Another label1.setText(“The Character “ + aChar + “is lower Case”); Block label1.setText(“Thank You”); }
  72. 72. Null or Empty Statement The Simplest statement of them all is the empty or null statement It takes in the following statement ; A null statement is useful in those instances where the syntax of the language Requires the presence of a statement but the logic of the program does not.
  73. 73. Q.No.1 Given the following code fragment int ch = 20 ; System.out.println(++ch); System.out.println(ch); i) What output does the above code fragment produce ? ii) What is the effect of replacing ++ch with ch+1 ? Q.No.2 What will be the result of following two expression if i = 10 initially ? I ) ++i <= 10 ii) i++ <= 10 Q.No. 3 Given the two following expressions : a) val = 3 b) val = = 3 i ) How are these two different ? Q.No. 4 What output will the following code fragment produce ? int val, res, n = 1000 ; res = n + val > 1750 ? 400 : 200 ; System.out.println(res); i) if the input is 2000 ii) if the input is 1000 iii) if the input is 500
  74. 74. Q. no. 5Given the following set of identifiers : byte b ; char ch; short sh; int intval; long longval ; float fl; Identify the datatype of the following expressions : a) ‘a’ -3 b) intval * langval - ch c) fl + longval / sh Q.No. 6 Will the value of y be the same for the two cases given below ? i) y = ++x ii) y = x++ Q.No.7 Consider the following code snippet int i = 10 ; int n = i++ % 5 ; What are the values of i and n after the code is executed ? Q.No. 8 Which of the following are valid identifiers why/ why not ? 1) Data_rec , _data, 1 data, data 1, my.file, switch, goto, break Q.No. 9 What would be the output of the following program ? int a =1 , b =2, c =4; a = +c + ++b / c; jTextField1.setText( “ a = “ +String.valueOf(a)); Q.No. 10 What would be the output of the following program ? int a,b =30; a = 30/2 * b; jTextField1.setText( “ a = “ +String.valueOf(a));
  75. 75. Q. no. 11 What would be the output of the following program ? float p = 10.45f; p= p++ + 1; jTextField1.setText( “ p = “ +String.valueOf(p)); Q. no. 12 What would be the output of the following program ? int p=10, k=20; k = k / ++p; jTextField1.setText( “ k = “ +String.valueOf(k)); Q. no. 13 What would be the output of the following program ? int z,x=5,y=-10, a=4,b=2; z= x++ - --y * b/a; What number will z in the sample code above contain ? a) 5 b) 6 c) 10 d) 11 e) 12
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×