KEMBAR78
UNIT 2 programming in java_operators.pptx
Features of Java
Data types; variables; operators and expressions;
programming structure; Operators and Expressions; ?:
operator;
Decision-Making and Branching: if; if..else; nested if;
switch;
Looping: while; do; for - Jumps in Loops - Labeled Loops;
Array - Types of array
Data types
❖ Defines the values that a variable can take, for example if a
variable has int data type, it can only take integer values.
❖ Data types specify the different sizes and values that can be
stored in the variable.
Data types
❖ int myNum = 5; // Integer (whole number)
❖ float myFloatNum = 5.99f; // Floating point number
❖ char myLetter = 'D'; // Character
❖ boolean myBool = true; // Boolean
❖ String myText = "Hello"; // String
Data types
❖ There are two types of data types in Java:
1. Primitive data types - includes byte, short, int, long, float,
double, boolean and char
2. Non-primitive data types - such as String, Arrays and Classes
Data types
variables
❖ Variable in Java is a data container that stores the data values
during Java program execution.
❖ Variable is a memory location name of the data.
❖ The value stored in a variable can be changed during program
execution.
variables
❖ In order to use a variable in a program we need to perform 2
steps
1. Variable Declaration
2. Variable Initialization
variables
❖ Variable Declaration
❖ Syntax: data_type variable_name ;
Eg: int a,b,c;
float pi;
double d;
variables
❖ Variable Initialization
❖ Syntax : data_type variable_name = value;
Eg: int a=2,b=4,c=6;
int num = 45.66;
float pi = 3.14f;
double val = 20.22d;
char a = ’v’;
variables
❖ Variable Initialization
❖ Syntax : data_type variable_name = value;
Eg: int a=2,b=4,c=6;
int num = 45.66;
float pi = 3.14f;
double val = 20.22d;
char a = ’v’;
variables
❖ Types of variables
1. Local variables - declared inside the method.
2. Instance Variable - declared inside the class but outside the
method.
3. Static variable - declared as with static keyword.
variables
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}}//end of class
Operators and expressions
❖ Operators in Java are the symbols used for performing specific
operations in Java.
❖ Operators make tasks like addition, multiplication, etc which
look easy although the implementation of these tasks is quite
complex.
Operators and expressions
❖ Java operators can be divided into following categories:
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Conditional operator (Ternary)
Arithmetic Operators
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Arithmetic Operators
import java.io.*;
class GFG {
public static void main (String[] args) {
int a = 10;
int b = 3;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
Relational Operators
❖ These operators are used to check for relations like equality,
greater than, and less than.
❖ They return boolean results after the comparison and are
extensively used in looping statements as well as conditional if-
else statements.
❖ The general format is,
variable relation_operator value
Relational Operators
❖ Some of the relational operators are-
==, Equal to returns true if the left-hand side is equal to the
right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to
the right-hand side.
Relational Operators
❖ Some of the relational operators are-
<, less than: returns true if the left-hand side is less than the
right-hand side.
<=, less than or equal to returns true if the left-hand side is less
than or equal to the right-hand side.
Relational Operators
❖ Some of the relational operators are-
>, Greater than: returns true if the left-hand side is greater than
the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is
greater than or equal to the right-hand side.
Relational Operators
import java.util.Scanner;
public class RelationalOperators {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num1 =1;
int num2 = 2;
System.out.println("num1 > num2 is " + (num1 > num2));
System.out.println("num1 < num2 is " + (num1 < num2));
System.out.println("num1 >= num2 is " + (num1 >= num2));
System.out.println("num1 <= num2 is " + (num1 <= num2));
System.out.println("num1 == num2 is " + (num1 == num2));
System.out.println("num1 != num2 is " + (num1 != num2));
}}
Relational Operators
Output:
num1 > num2 is false
num1 < num2 is true
num1 >= num2 is false
num1 <= num2 is true
num1 == num2 is false
num1 != num2 is true
B
i
t
w
i
s
e
Bitwise Operators
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
}}
Bitwise Operators
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
}}
Bitwise Operators
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
}}
Bitwise Operators
public class operators {
public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;
// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111 11111111
11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);
}}
Logical Operators
Logical Operators
import java.io.*;
class Logical {
public static void main(String[] args)
{
int a = 10, b = 20, c = 20, d = 0;
// using logical AND to verify two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}}
Assignment Operators
Assignment Operators
import java.io.*;
class Assignment {
public static void main(String[] args)
{ // Declaring variables
int num1, num2;
// Assigning values
num1 = 10;
num2 = 20;
// Adding & Assigning values
num1 += num2;
System.out.println("num1 = " + num1);
}
}
Conditional operator (Ternary) ( ? : )
Variable= Expression1 ? Expression2 : Expression3
Variable= Expression ? value if true : value if false
Conditional operator (Ternary) ( ? : )
import java.io.*;
class Ternary {
public static void main(String[] args)
{
int n1 = 5, n2 = 10, max;
// Largest among n1 and n2
max = (n1 > n2) ? n1 : n2;
// Print the largest number
System.out.println("Maximum is = " + max);
}
}
Expressions
❖ An expression is a combination of operators, constants and
variables.
❖ An expression may consist of one or more operands, and zero
or more operators to produce a value.
Expressions
Expressions
❖ An expression is a combination of operators, constants and
variables.
❖ An expression may consist of one or more operands, and zero
or more operators to produce a value.
Decision-Making and Branching
❖ If statement
❖ Use the if statement to specify a block of Java code to
be executed if a condition is true.
❖ Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
If statement
import java.util.*;
class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
{
System.out.println("Inside If block");
System.out.println("10 is less than 15");
}
System.out.println("I am Not in if");
}
}
Decision-Making and Branching
❖ If - else statement
❖ It also tests the condition. It executes the if block if
condition is true otherwise else block is executed.
❖ Syntax
if (condition)
{ // block of code to execute if condition is true}
else
{// block of code to be executed if the condition is false}
If - else statement
import java.util.*;
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Decision-Making and Branching
❖ Nested - If statement
❖ A nested if is an if statement that is the target of another if
or else.
❖ Nested if statements mean an if statement inside an if
statement.
Nested - If statement
Decision-Making and Branching
❖ Switch statement
❖ The switch statement is a multiway branch statement.
❖ It provides an easy way to dispatch execution to different
parts of code based on the value of the expression.
Decision-Making and Branching
❖ How to Java switch works:
➢ Matching each expression with case
➢ Once it match, execute all case from where it matched.
➢ Use break to exit from switch
➢ Use default when expression does not match with any
case
Decision-Making and Branching
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
.
case valueN: statementN;
break;
Default: statementDefault;
}
Switch statement
Looping
❖ Looping in programming languages is a feature which
facilitates the execution of a set of
instructions/functions repeatedly while some
condition evaluates to true.
Looping
While loop
❖ A while loop is a control flow statement that allows
code to be executed repeatedly based on a given
Boolean condition.
❖ The while loop can be thought of as a repeating if
statement.
Looping
While loop
❖ It starts with the checking of Boolean condition.
❖ If it evaluated to true, then the loop body statements
are executed otherwise first statement following the
loop is executed.
❖ For this reason it is also called Entry control loop
❖ When the condition becomes false, the loop
terminates which marks the end of its life cycle.
Looping
While loop
❖ Syntax :
while (boolean condition)
{
loop statements...
}
While loop
While loop
Looping
do while loop
❖ It is similar to while loop with only difference that it
checks for condition after executing the statements,
and therefore is an example of Exit Control Loop.
Looping
do while loop
❖ Syntax:
do
{
statements..
}while (condition);
do while loop
do while loop
Looping
For loop
❖ provides a concise way of writing the loop structure.
❖ Unlike a while loop, a for statement consumes the
initialization, condition and increment/decrement in
one line thereby providing a shorter, easy to debug
structure of looping.
Looping
For loop
❖ Syntax:
for (initialization; testing; increment/decrement)
{
statement(s)
}
For loop
For loop
Jumps in Loops
❖ Jumping statements are control statements that transfer
execution control from one point to another point in the
program.
❖ There are different Jump statements that are provided in
the Java programming language:
Break statement.
Continue statement.
Jumps in Loops
Break statement
❖ It is used to terminate the execution of the nearest
looping statement or switch statement.
❖ The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
❖ When a break statement is found inside a loop, the loop
is terminated, and the control reaches the statement
that follows the loop.
Break statement
Jumps in Loops
Continue statement
❖ It pushes the next repetition of the loop to take place,
hopping any code between itself and the conditional
expression that controls the loop.
Continue statement
Labeled Loops
❖ A label is a valid variable name that denotes the name of
the loop to where the control of execution should jump.
❖ To label a loop, place the label before the loop with a
colon at the end.
❖ Therefore, a loop with the label is called a labeled loop.
❖ We can also use labels with continue and break
statements.
Labeled Loops
Syntax:
labelname: Loop
Data Type Conversion and Casting
❖ When compatible types are mixed in an assignment,
the value of the right side is automatically converted
to the type of the left side.
❖ However, because of Java’s strict type checking, not all
types are compatible, and thus, not all type
conversions are implicitly allowed.
Data Type Conversion and Casting
❖ For example, boolean and int are not compatible.
❖ When one type of data is assigned to another type of
variable, an automatic type conversion will take place if
➢ The two types are compatible.
➢ The destination type is larger than source type.
❖ When these two conditions are met, a widening
conversion takes place.
Data Type Conversion and Casting
❖ For example, the int type is always large enough to
hold all valid byte values, and both int and byte are
integer types, so an automatic conversion from byte to
int can be applied.
Data Type Conversion and Casting
int a=10;
long b=a;
float c=a;
Data Type Conversion and Casting
❖ There are no automatic conversions from the numeric
types to char or boolean.
❖ Also, char and boolean are not compatible with each
other.
Data Type Conversion and Casting
❖ Although the automatic type conversions are helpful,
they will not fulfill all programming needs because
they apply only to widening conversions between
compatible types.
❖ For all other cases you must employ a cast.
❖ A cast is an instruction to the compiler to convert one
type into another.
Data Type Conversion and Casting
❖ A cast has this general form:
(target-type) expression
Ex: float x;
int a = (int)x + a;
❖ Here, target-type specifies the desired type to convert
the specified expression to.
Data Type Conversion and Casting
❖ For example,
if you want to convert the type of the expression x/y to int, you can
write
double x, y;
//…
(int)(x/y)
❖ The parentheses surrounding x/y are necessary. Otherwise, the cast to
int would apply only to the x and not to the outcome of the division.
Data Type Conversion and Casting
❖ The cast is necessary here because there is no
automatic conversion from double to int.
❖ When a cast involves a narrowing conversion,
information might be lost.
❖ For example, when casting a long into a short,
information will be lost if the long’s value is greater than
the range of a short because its high-order bits are
removed.
Data Type Conversion and Casting
❖ When a floating-point value is cast to an integer type,
the fractional component will also be lost due to
truncation.
Data Type Conversion and Casting
❖ To convert a string into an int value, you can use the
static parseInt method in the Integer
int value = Integer.parseInt(InputString);
❖ where InputString is a numeric string such as “123”.
Data Type Conversion and Casting
❖ Cast that results in no loss of information:
Array
❖ Array is a group of like-typed variables referred to by a
common name.

UNIT 2 programming in java_operators.pptx

  • 1.
  • 2.
    Data types; variables;operators and expressions; programming structure; Operators and Expressions; ?: operator; Decision-Making and Branching: if; if..else; nested if; switch; Looping: while; do; for - Jumps in Loops - Labeled Loops; Array - Types of array
  • 3.
    Data types ❖ Definesthe values that a variable can take, for example if a variable has int data type, it can only take integer values. ❖ Data types specify the different sizes and values that can be stored in the variable.
  • 4.
    Data types ❖ intmyNum = 5; // Integer (whole number) ❖ float myFloatNum = 5.99f; // Floating point number ❖ char myLetter = 'D'; // Character ❖ boolean myBool = true; // Boolean ❖ String myText = "Hello"; // String
  • 5.
    Data types ❖ Thereare two types of data types in Java: 1. Primitive data types - includes byte, short, int, long, float, double, boolean and char 2. Non-primitive data types - such as String, Arrays and Classes
  • 6.
  • 7.
    variables ❖ Variable inJava is a data container that stores the data values during Java program execution. ❖ Variable is a memory location name of the data. ❖ The value stored in a variable can be changed during program execution.
  • 8.
    variables ❖ In orderto use a variable in a program we need to perform 2 steps 1. Variable Declaration 2. Variable Initialization
  • 9.
    variables ❖ Variable Declaration ❖Syntax: data_type variable_name ; Eg: int a,b,c; float pi; double d;
  • 10.
    variables ❖ Variable Initialization ❖Syntax : data_type variable_name = value; Eg: int a=2,b=4,c=6; int num = 45.66; float pi = 3.14f; double val = 20.22d; char a = ’v’;
  • 11.
    variables ❖ Variable Initialization ❖Syntax : data_type variable_name = value; Eg: int a=2,b=4,c=6; int num = 45.66; float pi = 3.14f; double val = 20.22d; char a = ’v’;
  • 12.
    variables ❖ Types ofvariables 1. Local variables - declared inside the method. 2. Instance Variable - declared inside the class but outside the method. 3. Static variable - declared as with static keyword.
  • 13.
    variables class A{ int data=50;//instancevariable static int m=100;//static variable void method(){ int n=90;//local variable }}//end of class
  • 14.
    Operators and expressions ❖Operators in Java are the symbols used for performing specific operations in Java. ❖ Operators make tasks like addition, multiplication, etc which look easy although the implementation of these tasks is quite complex.
  • 15.
    Operators and expressions ❖Java operators can be divided into following categories: • Arithmetic Operators • Relational Operators • Bitwise Operators • Logical Operators • Assignment Operators • Conditional operator (Ternary)
  • 16.
    Arithmetic Operators * :Multiplication / : Division % : Modulo + : Addition – : Subtraction
  • 17.
    Arithmetic Operators import java.io.*; classGFG { public static void main (String[] args) { int a = 10; int b = 3; System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); } }
  • 18.
    Relational Operators ❖ Theseoperators are used to check for relations like equality, greater than, and less than. ❖ They return boolean results after the comparison and are extensively used in looping statements as well as conditional if- else statements. ❖ The general format is, variable relation_operator value
  • 19.
    Relational Operators ❖ Someof the relational operators are- ==, Equal to returns true if the left-hand side is equal to the right-hand side. !=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
  • 20.
    Relational Operators ❖ Someof the relational operators are- <, less than: returns true if the left-hand side is less than the right-hand side. <=, less than or equal to returns true if the left-hand side is less than or equal to the right-hand side.
  • 21.
    Relational Operators ❖ Someof the relational operators are- >, Greater than: returns true if the left-hand side is greater than the right-hand side. >=, Greater than or equal to returns true if the left-hand side is greater than or equal to the right-hand side.
  • 22.
    Relational Operators import java.util.Scanner; publicclass RelationalOperators { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int num1 =1; int num2 = 2; System.out.println("num1 > num2 is " + (num1 > num2)); System.out.println("num1 < num2 is " + (num1 < num2)); System.out.println("num1 >= num2 is " + (num1 >= num2)); System.out.println("num1 <= num2 is " + (num1 <= num2)); System.out.println("num1 == num2 is " + (num1 == num2)); System.out.println("num1 != num2 is " + (num1 != num2)); }}
  • 23.
    Relational Operators Output: num1 >num2 is false num1 < num2 is true num1 >= num2 is false num1 <= num2 is true num1 == num2 is false num1 != num2 is true
  • 24.
  • 25.
    Bitwise Operators public classoperators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 = 5 System.out.println("a&b = " + (a & b)); }}
  • 26.
    Bitwise Operators public classoperators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise or // 0101 | 0111=0111 = 7 System.out.println("a|b = " + (a | b)); }}
  • 27.
    Bitwise Operators public classoperators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise xor // 0101 ^ 0111=0010 = 2 System.out.println("a^b = " + (a ^ b)); }}
  • 28.
    Bitwise Operators public classoperators { public static void main(String[] args) { // Initial values int a = 5; int b = 7; // bitwise not // ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010 // will give 2's complement (32 bit) of 5 = -6 System.out.println("~a = " + ~a); }}
  • 29.
  • 30.
    Logical Operators import java.io.*; classLogical { public static void main(String[] args) { int a = 10, b = 20, c = 20, d = 0; // using logical AND to verify two constraints if ((a < b) && (b == c)) { d = a + b + c; System.out.println("The sum is: " + d); } else System.out.println("False conditions"); }}
  • 31.
  • 32.
    Assignment Operators import java.io.*; classAssignment { public static void main(String[] args) { // Declaring variables int num1, num2; // Assigning values num1 = 10; num2 = 20; // Adding & Assigning values num1 += num2; System.out.println("num1 = " + num1); } }
  • 33.
    Conditional operator (Ternary)( ? : ) Variable= Expression1 ? Expression2 : Expression3 Variable= Expression ? value if true : value if false
  • 34.
    Conditional operator (Ternary)( ? : ) import java.io.*; class Ternary { public static void main(String[] args) { int n1 = 5, n2 = 10, max; // Largest among n1 and n2 max = (n1 > n2) ? n1 : n2; // Print the largest number System.out.println("Maximum is = " + max); } }
  • 35.
    Expressions ❖ An expressionis a combination of operators, constants and variables. ❖ An expression may consist of one or more operands, and zero or more operators to produce a value.
  • 36.
  • 37.
    Expressions ❖ An expressionis a combination of operators, constants and variables. ❖ An expression may consist of one or more operands, and zero or more operators to produce a value.
  • 38.
    Decision-Making and Branching ❖If statement ❖ Use the if statement to specify a block of Java code to be executed if a condition is true. ❖ Syntax if (condition) { // block of code to be executed if the condition is true }
  • 39.
  • 40.
    import java.util.*; class IfDemo { publicstatic void main(String args[]) { int i = 10; if (i < 15) { System.out.println("Inside If block"); System.out.println("10 is less than 15"); } System.out.println("I am Not in if"); } }
  • 41.
    Decision-Making and Branching ❖If - else statement ❖ It also tests the condition. It executes the if block if condition is true otherwise else block is executed. ❖ Syntax if (condition) { // block of code to execute if condition is true} else {// block of code to be executed if the condition is false}
  • 42.
    If - elsestatement
  • 43.
    import java.util.*; class IfElseDemo{ public static void main(String args[]) { int i = 10; if (i < 15) System.out.println("i is smaller than 15"); else System.out.println("i is greater than 15"); } }
  • 44.
    Decision-Making and Branching ❖Nested - If statement ❖ A nested if is an if statement that is the target of another if or else. ❖ Nested if statements mean an if statement inside an if statement.
  • 45.
    Nested - Ifstatement
  • 48.
    Decision-Making and Branching ❖Switch statement ❖ The switch statement is a multiway branch statement. ❖ It provides an easy way to dispatch execution to different parts of code based on the value of the expression.
  • 49.
    Decision-Making and Branching ❖How to Java switch works: ➢ Matching each expression with case ➢ Once it match, execute all case from where it matched. ➢ Use break to exit from switch ➢ Use default when expression does not match with any case
  • 50.
    Decision-Making and Branching switch(expression) { case value1: statement1; break; case value2: statement2; break; . case valueN: statementN; break; Default: statementDefault; }
  • 51.
  • 52.
    Looping ❖ Looping inprogramming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true.
  • 53.
    Looping While loop ❖ Awhile loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. ❖ The while loop can be thought of as a repeating if statement.
  • 54.
    Looping While loop ❖ Itstarts with the checking of Boolean condition. ❖ If it evaluated to true, then the loop body statements are executed otherwise first statement following the loop is executed. ❖ For this reason it is also called Entry control loop ❖ When the condition becomes false, the loop terminates which marks the end of its life cycle.
  • 55.
    Looping While loop ❖ Syntax: while (boolean condition) { loop statements... }
  • 56.
  • 57.
  • 58.
    Looping do while loop ❖It is similar to while loop with only difference that it checks for condition after executing the statements, and therefore is an example of Exit Control Loop.
  • 59.
    Looping do while loop ❖Syntax: do { statements.. }while (condition);
  • 60.
  • 61.
  • 62.
    Looping For loop ❖ providesa concise way of writing the loop structure. ❖ Unlike a while loop, a for statement consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to debug structure of looping.
  • 63.
    Looping For loop ❖ Syntax: for(initialization; testing; increment/decrement) { statement(s) }
  • 64.
  • 65.
  • 66.
    Jumps in Loops ❖Jumping statements are control statements that transfer execution control from one point to another point in the program. ❖ There are different Jump statements that are provided in the Java programming language: Break statement. Continue statement.
  • 67.
    Jumps in Loops Breakstatement ❖ It is used to terminate the execution of the nearest looping statement or switch statement. ❖ The break statement is widely used with the switch statement, for loop, while loop, do-while loop. ❖ When a break statement is found inside a loop, the loop is terminated, and the control reaches the statement that follows the loop.
  • 68.
  • 69.
    Jumps in Loops Continuestatement ❖ It pushes the next repetition of the loop to take place, hopping any code between itself and the conditional expression that controls the loop.
  • 70.
  • 71.
    Labeled Loops ❖ Alabel is a valid variable name that denotes the name of the loop to where the control of execution should jump. ❖ To label a loop, place the label before the loop with a colon at the end. ❖ Therefore, a loop with the label is called a labeled loop. ❖ We can also use labels with continue and break statements.
  • 72.
  • 73.
    Data Type Conversionand Casting ❖ When compatible types are mixed in an assignment, the value of the right side is automatically converted to the type of the left side. ❖ However, because of Java’s strict type checking, not all types are compatible, and thus, not all type conversions are implicitly allowed.
  • 74.
    Data Type Conversionand Casting ❖ For example, boolean and int are not compatible. ❖ When one type of data is assigned to another type of variable, an automatic type conversion will take place if ➢ The two types are compatible. ➢ The destination type is larger than source type. ❖ When these two conditions are met, a widening conversion takes place.
  • 75.
    Data Type Conversionand Casting ❖ For example, the int type is always large enough to hold all valid byte values, and both int and byte are integer types, so an automatic conversion from byte to int can be applied.
  • 76.
    Data Type Conversionand Casting int a=10; long b=a; float c=a;
  • 77.
    Data Type Conversionand Casting ❖ There are no automatic conversions from the numeric types to char or boolean. ❖ Also, char and boolean are not compatible with each other.
  • 78.
    Data Type Conversionand Casting ❖ Although the automatic type conversions are helpful, they will not fulfill all programming needs because they apply only to widening conversions between compatible types. ❖ For all other cases you must employ a cast. ❖ A cast is an instruction to the compiler to convert one type into another.
  • 79.
    Data Type Conversionand Casting ❖ A cast has this general form: (target-type) expression Ex: float x; int a = (int)x + a; ❖ Here, target-type specifies the desired type to convert the specified expression to.
  • 80.
    Data Type Conversionand Casting ❖ For example, if you want to convert the type of the expression x/y to int, you can write double x, y; //… (int)(x/y) ❖ The parentheses surrounding x/y are necessary. Otherwise, the cast to int would apply only to the x and not to the outcome of the division.
  • 81.
    Data Type Conversionand Casting ❖ The cast is necessary here because there is no automatic conversion from double to int. ❖ When a cast involves a narrowing conversion, information might be lost. ❖ For example, when casting a long into a short, information will be lost if the long’s value is greater than the range of a short because its high-order bits are removed.
  • 82.
    Data Type Conversionand Casting ❖ When a floating-point value is cast to an integer type, the fractional component will also be lost due to truncation.
  • 83.
    Data Type Conversionand Casting ❖ To convert a string into an int value, you can use the static parseInt method in the Integer int value = Integer.parseInt(InputString); ❖ where InputString is a numeric string such as “123”.
  • 84.
    Data Type Conversionand Casting ❖ Cast that results in no loss of information:
  • 85.
    Array ❖ Array isa group of like-typed variables referred to by a common name.