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

JAVA 2nd UNIt(Chapter-1)

JAVA 2nd UNIt(Chapter-1)
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

JAVA 2nd UNIt(Chapter-1)

JAVA 2nd UNIt(Chapter-1)
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

PA

JAVA PROGRAMMING GE
\*

UNIT-2(Chapter-1)
Programming Constructs
Chapter-1:
Programming Constructs: Variables, Primitive Data types, Identifiers (Naming
Conventions, Keywords), Literals, Operators (Binary, Unary and ternary), Expressions,
Precedence rules and Associativity, Primitive Type Conversion and Casting, Flow of
control (Branching, Conditional, loops).

Variables:

🡪The variable is the basic unit of storage. A variable is defined by the combination of an
identifier, a type, and an optional initializer.
🡪In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used.
Syntax: type identifier [= value] [, identifier [= value] ...];
● The type is one of Java’s atomic types, or the name of a class or interface.
● The identifier is the name of the variable.
● You can initialize the variable by specifying an equal sign and a value. That the
initialization expression must result in a value of the same (or compatible) type as that
specified for the variable. To declare more than one variable of the specified type, use
comma separated list.
Examples:
int a, b, c;
int a = 3, b = 5 , c;
byte d = 22;
double pi = 3.14159;
char s= 's';

Dynamic Initialization:
🡪Although the preceding examples have used only constants as initializers, Java allows
variables to be initialized dynamically, using any expression valid at the time the
variable is declared.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Example: //Dynamic Initialization
import java.util.*;
class DynInit
{
public static void main(String args[])
{
int a,b,c;
Scanner s=new Scanner(System.in);
System.out.println(“Enter a value”);
a=s.nextInt();
System.out.println(“Enter b value”);
b=s.nextInt();
c=a+b;
System.out.println("Addition of a and b is: " + c);
}
}

Output:
Enter a value
4
Enter b value
5
Addition of a and b is:9
Scope and Lifetime of Variables:

🡪 All of the variables used have been declared at the start of the main( ) method. Java
allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. Thus, each time you
start a new block, you are creating a new scope.
🡪 A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
🡪 Many other computer languages define two general categories of scopes: global and
local. But these are not must for OOP.
🡪In Java, the two major scopes are those defined by a class and those defined by a
method.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
🡪 Class scope has several unique properties and attributes that do not apply to the scope
defined by a method.

🡪 The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method’s scope. They work the
same as any other method variable.
🡪 Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope. Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized access and/or modification.
🡪 The scope rules provide the foundation for encapsulation.
🡪 Scopes can be nested. For example, each time you create a block of code, you are
creating a new, nested scope. When this occurs, the outer scope encloses the inner scope.
This means that objects declared in the outer scope will be visible to code within the inner
scope. However, Objects declared within the inner scope will not be visible outside it.

Example:
class Scope
{
public static void main(String args[])
{ // start scope
int a; // known to all code within main
a = 5;
if(a == 5)
{ // start new scope
int b, s = 20; // known only to this block
b=s-a; // a,b and s both known here.
System.out.println("b value:"+ b);
}// end new scope
}// end scope
}

🡪 Finally to remember one thing: Variables are created when their scope is entered, &
destroyed when their scope is left. This means that a variable will not hold its value once
it has gone out of scope. Variable declared within a block will lose its value when the
block is left. Thus the life time of variable is confined to its scope.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

Data Types:

Data types are divided into two groups:

● Primitive data types - includes byte, short, int, long, float, double, boolean and char
● Non-primitive data types - such as String, Arrays and Classes

Primitive Data Types

A primitive data type specifies the size and type of variable values, and it has no additional
methods.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal


digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Examples:

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

Again these can be divided into 4 groups:

1. Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers, positive & negative numbers.
2. Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
3. Characters: This group includes char, which represents symbols in a character set,
like letters and numbers.
4. Boolean: This group includes boolean, which is a special type for representing
true/false values.
1. Integers:

🡪Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values.
🡪Java does not support unsigned, positive-only integers.
🡪Many other computer languages support both signed and unsigned integers.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
🡪Java manages the meaning of the high-order bit differently, by adding a special
“unsigned right shift” operator. Thus, the need for an unsigned integer type was
eliminated.
🡪The Java run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them.

❖ byte:

🡪The smallest integer type is byte. This is a signed 8-bit type that has a range from –128
to 127.
Variables of type byte are especially useful when you’re working with a stream of data
from a network or file. They are also useful when you’re working with raw binary data
that may not be directly compatible with Java’s other built-in types. Byte variables are
declared by use of the byte keyword.
Eg: byte b, c;
❖ short:

🡪 short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the
least-used in Java.
Eg: short s;
short t;

❖ int:
🡪 The most commonly used integer type is int. It is a signed 32-bit type that has a
range from
–2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are
commonly employed to control loops and to index arrays. Therefore, int is often the
best choice when an integer is needed.
Eg: int a, b, c;

❖ long:

🡪 long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. The range of a long is quite large. This
makes it useful when big, whole numbers are needed.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
2. Floating point numbers:
🡪 Floating point numbers are also known as real numbers. These are used for
representing the fractional numbers.
🡪 There are two types
● float
● double
● float:
� float specifies a single precision value that uses 32 bits of storage. Float is useful
when you need a fractional component.
Eg: float a, b;
● double:
🡪 Its representation is faster than the float representation. It can be used for high speed
calculations.
Eg: double a, b, c;
3. Characters:

🡪In Java, the data type used to store characters is char. char in Java is not same as char
in C or C++.
🡪In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode
to represent characters.
🡪It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more.
🡪 For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of
a char is 0 to 65,536. There are no negative chars.
🡪The standard set of characters known as ASCII still ranges from 0 to 127 as always,
and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Eg: char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';

4. boolean:

🡪Java has a primitive type, called boolean, for logical values. It can have only one of
two possible values, true or false. This is the type returned by all relational operators,

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
as in the case of a < b. boolean is also the type required by the conditional expressions
that govern the control statements such as if and for.

Identifiers

In Java (as in many programming languages), the names of the boxes are called variable
names. The word "variable" means changing, because we can change the value inside the
box. We can't change its name, however.

Variable names fall in the category of something known as identifiers. Identifiers are
names given to things in Java. This includes variables, methods, classes, etc.

An identifier refers to names of "things" in Java.

Java has strict rules about valid identifiers. Make sure you understand them (they aren't
difficult to master) so you don't make errors when you use them.

But first, let's define a few sets.

● alpha This is the set of alphabetic characters { a, b, ..., z, A, B, ... Z }. It contains the 26
uppercase letters and the 26 lowercase letters. We call this set alpha.
● digit This is the set of digits { 0, 1, ..., 9 }. It contains the 10 digits from 0 to 9.

We also have underscore, which is the character '_' (the single quotes are used to make it
easier to see), and dollar sign, '$'.

Identifiers contain characters from any of: alpha, digit, underscore, and dollar sign. You
can't use spaces or tabs or symbols like #, @, !, and so forth in an identifier.

Syntax of an Identifier

Syntax is a grammatical rule. Here is the syntax for valid Java identifiers:

● Each identifier must have at least one character.


● The first character must be picked from: alpha, underscore, or dollar sign.
The first character cannot be a digit.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
● The rest of the characters (besides the first) can be from: alpha, digit,
underscore, or dollar sign. In other words, it can be any valid identifier
character.

Put simply, an identifier is one or more characters selected from alpha, digit,
underscore, or dollar sign. The only restriction is the first character can't be a
digit.

Examples of Valid Identifiers

Here are some valid identifiers:

● aaa
● sales_tax
● _circleArea
● box100width
● $directory
● ab1234$$

Examples of Invalid Identifiers

It's easy to make a mistake and use a bad identifier.

● 1ab (ERROR: first character starts with a digit)


● num-oranges (ERROR: dash is not permitted in identifiers)
● num oranges (ERROR: space is not permitted in identifiers)

Naming Conventions

Java naming convention is like as a rule (but, not rule) to follow as you decide what to
name your identifiers such as class, package, variable, constant, method etc.

But, it is not forced to follow. So, it is known as convention not rule.

All the classes, interfaces, packages, methods and fields of java programming language are
given according to java naming convention.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Advantage of naming conventions in java

By using standard Java naming conventions, you make your code easier to read for
yourself and for other programmers. Readability of Java program is very important. It
indicates that less time is spent to figure out what the code does.

Name Convention

class name should start with uppercase letter and be a noun e.g. String, Color, Button,
System, Thread etc.

interface should start with uppercase letter and be an adjective e.g. Runnable, Remote,
name ActionListener etc.

method name should start with lowercase letter and be a verb e.g. actionPerformed(),
main(), print(), println() etc.

variable name should start with lowercase letter e.g. firstName, orderNumber etc.

package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.


name

Keywords:

abstract boolean break byte case catch


char class const * continue default do
double else extends final finally float
for goto * if implements import instanceof
int interface long native new package
private protected public return short static
strictfp super switch synchronized this throw
throws transient try void volatile while

Literals:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
A literal is the source code representation of a fixed value.

Literals in Java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. Java language specifies five major types
of literals. Literals can be any number, text, or other information that represents a value.
This means what you type is what you get. We will use literals in addition to variables in
Java statement. While writing a source code as a character sequence, we can specify any
value as a literal such as an integer.

They are:

● Integer literals

● Floating literals

● Character literals

● String literals

● Boolean literals

Each of them has a type associated with it. The type describes how the values behave and
how they are stored.

Integer literals:

Integer data types consist of the following primitive data types: int,long, byte, and short.
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal (base 16) or
octal(base 8) number systems as well.

Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these
number systems for literals.

Examples:

int decimal = 100;

int octal = 0fff;

int hexa = 0x186;

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Floating-point literals:

Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -
0.000001. Java has two kinds of floating-point numbers: float and double. The default type
when you write a floating-point literal is double, but you can designate it explicitly by
appending the D (or d) suffix. However, the suffix F (or f) is appended to designate the
data type of a floating-point literal as float. We can also specify a floating-point literal in
scientific notation using Exponent (short E ore), for instance: the double literal 0.0314E2 is
interpreted as:

0.0314 *10² (i.e 3.14).


6.5E+32 (or 6.5E32) Double-precision floating-point literal
7D Double-precision floating-point literal
.01f Floating-point literal

Character literals:

char data type is a single 16-bit Unicode character. We can specify a character literal as a
single printable character in a pair of single quote characters such as 'a', '#', and '3'. You
must know about the ASCII character set. The ASCII character set includes 128 characters
including letters, numerals, punctuation etc. Below table shows a set of these special
characters.

Esca
Meaning
pe

\n New line

\t Tab

\b Backspace

\r Carriage return

\f Formfeed

\\ Backslash

\' Single quotation mark

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

\" Double quotation mark

\d Octal

\xd Hexadecimal

\ud Unicode character

If we want to specify a single quote, a backslash, or a non-printable character as a


character literal use an escape sequence. An escape sequence uses a special syntax to
represents a character. The syntax begins with a single backslash character. You can see
the below table to view the character literals use Unicode escape sequence to represent
printable and non-printablecharacters.

'u0041 Capital letter


' A

'\
Digit 0
u0030'

'\ Double quote


u0022' "

'\
Punctuation ;
u003b'

'\
Space
u0020'

'\ Horizontal
u0009' Tab

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
String Literals:

The set of characters in represented as String literals in Java. Always use "double quotes"
for String literals. There are few methods provided in Java to combine strings, modify
strings and to know whether to strings have the same values.

"" The empty string

"\"" A string containing

"This is a string" A string containing 16 characters

actually a string-valued constant expression, formed


"This is a " + "two-line string"
from two string literals

Null Literals

The final literal that we can use in Java programming is a Null literal. We specify the Null
literal in the source code as 'null'. To reduce the number of references to an object, use null
literal. The type of the null literal is always null. We typically assign null literals to object
referencevariables.Forinstance
s = null;

Boolean Literals:

The values true and false are treated as literals in Java programming. When we assign a
value to a boolean variable, we can only use these two values. Unlike C, we can't presume
that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use
the values true and false to represent a Boolean value.

Example

boolean chosen = true;

Operators:

🡪 A Java operator is a special symbol that performs specific operation on one, two, or
three operands depending upon the type of the operator, and then returns a result.

🡪Java operators are classified on two bases.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
First, on the basis of number of operands an operator performs upon.

Second, on the type or nature of operation an operator performs.

By first classification, Java operators can be unary, binary, or ternary.


Unary operators take one operand to perform upon e.g., ++, and -- both prefix and postfix.
Binary operators take two operands to perform their assigned task. All arithmetic
operators are example of binary operators.
Third, and of special type operator is ternary operator, it takes three operands to perform
its job. Java has only one ternary operator, which is also called conditional operator. It is a
combination of two symbols? and:. Another classification is based on the type of operation
they perform.
Operators on basis of the nature of job they do can be classified in following categories:
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators

1. Unary Operator:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

● incrementing/decrementing a value by one

● negating an expression

● inverting the value of a Boolean

Example:

class Unaryexample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output:

10
12
12
10

2. Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denumerator

% remainder of division

++ Increment operator increases integer value by one

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

-- Decrement operator decreases integer value by one

Example:
class Arithmetic_operators1{
public static void main(String as[])
{
int a, b, c;
a=10;
b=2;
c=a+b;
System.out.println("Addtion: "+c);
c=a-b;
System.out.println("Substraction: "+c);
c=a*b;
System.out.println("Multiplication: "+c);
c=a/b;
System.out.println("Division: "+c);
b=3;
c=a%b;
System.out.println("Remainder: "+c);
a=++a;
System.out.println("Increment Operator: "+a);
a=--a;
System.out.println("decrement Operator: "+a);

}
}

Output:
F:\JAVA Programs for ECE>javac Arithmetic_operators1.java
F:\JAVA Programs for ECE>java Arithmetic_operators1
Addtion: 12
Substraction: 8
Multiplication: 20

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Division: 5
Remainder: 1
Increment Operator: 11
decrement Operator: 10
3. Relational Operators:
Relational operators are used to test comparison between operands or values. It can be use
to test whether two values are equal or not equal or less than or greater than etc.
The following table shows all relation operators supported by Java.

Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Example:
class Relational_operators1{
public static void main(String as[])
{
int a, b;
a=40;
b=30;

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
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("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
F:\JAVA Programs for ECE>javac Relational_operators1.java
F:\JAVA Programs for ECE>java Relational_operators1
a == b = false
a != b = true
a > b = true
a < b = false
b >= a = false
b <= a = true
4. Logical Operators:
Logical Operators are used to check conditional expression. For example, we can use
logical operators in if statement to evaluate conditional based expression. We can use them
into loop as well to evaluate a condition.
Java supports following 3 logical operator. Suppose we have two variables whose values
are: a=true and b=false.

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Example:
class LogicalOperator {
public static void main(String[] args) {

int number1 = 1, number2 = 2, number3 = 9;


boolean result;

// At least one expression needs to be true for the


result to be true
result = (number1 > number2) || (number3 > number1);

// result will be true because (number1 > number2)


is true
System.out.println(result);

// All expression must be true from result to be


true
result = (number1 > number2) && (number3 > number1);

// result will be false because (number3 > number1)


is false
System.out.println(result);
}
}
Output:
F:\JAVA Programs for ECE>javac LogicalOperator.java

F:\JAVA Programs for ECE>java LogicalOperator


true
false

5. Bitwise Operators:

Operato Description Example Same Result Decimal


r as

& AND - Sets each bit to 1 if 5&1 0101 0001 1


both bits are 1 &
0001

| OR - Sets each bit to 1 if any 5|1 0101 | 0101 5


of the two bits is 1 0001

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

~ NOT - Inverts all the bits ~5 ~0101 1010 10

^ XOR - Sets each bit to 1 if 5^1 0101 ^ 0100 4


only one of the two bits is 1 0001

<< Zero-fill left shift - Shift left by 9 << 1 1001 0010 2


pushing zeroes in from the << 1
right and letting the leftmost
bits fall off

>> Signed right shift - Shift right 9 >> 1 1001 1100 12


by pushing copies of the >> 1
leftmost bit in from the left and
letting the rightmost bits fall
off

>>> Zero-fill right shift - Shift right 9 >>> 1 1001 0100 4


by pushing zeroes in from the >>> 1
left and letting the rightmost
bits fall off

6. Ternary Operator:
The conditional operator or ternary operator ?: is shorthand for the if-then-else statement.
The syntax of the conditional operator is:

variable = Expression ? expression1 : expression2

Here's how it works.

● If the Expression is true, expression1 is assigned to the variable.


● If the Expression is false, expression2 is assigned to the variable.

Example:
import java.util.*;
class ternary
{
public static void main(String arg[])
{

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
int a, b,result;
Scanner s=new Scanner(System.in);
System.out.println("Enter Value for a:");
a=s.nextInt();
System.out.println("Enter Value for b:");
b=s.nextInt();
result=(a<b)?a:b;
System.out.println("Resulting value of ternary
verification:"+result);
}
}

Output:

F:\JAVA Programs for ECE>javac ternary.java

F:\JAVA Programs for ECE>java ternary


Enter Value for a:
4
Enter Value for b:
6
Resulting value of ternary verification:4

Automatic Type Promotion Rules in Expressions:


🡪An expression is nothing but combination of operands and operators.
🡪 In an expression, the precision required of an intermediate value will sometimes exceed
the range of either operand.
🡪Java defines several type promotion rules that apply to expressions. They are as fallows.
❖ First, all byte and short values are promoted to int. Then if one operand is long, then
whole expression is promoted to long.
❖ If one operand is float, then whole expression is promoted to float.
❖ If one operand is double, then whole expression is promoted to double.

Eg: byte b=60;


short s=50;
int a=b*s; // byte and short values are promoted to int
float f=1.37;
float p=a*f; // whole expression is promoted to float
double d=(b+s)*(a+f+p); // whole expression is promoted to double
Java Operators Precedence Rules and Associativity

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Java operators have two properties those are precedence, and associativity. Precedence is
the priority order of an operator, if there are two or more operators in an expression then
the operator of highest priority will be executed first then higher, and then high. For
example, in expression 1 + 2 * 5, multiplication (*) operator will be processed first and
then addition. It's because multiplication has higher priority or precedence than addition.
Alternatively, you can say that when an operand is shared by two operators (2 in above
example is shared by + and *) then higher priority operator picks the shared operand for
processing. From above example you would have understood the role of precedence or
priority in execution of operators. But, the situation may not be as straightforward every
time as it is shown in above example. What if all operators in an expression have same
priority? In that case the second property associated with an operator comes into play,
which is associativity. Associativity tells the direction of execution of operators that can be
either left to right or right to left. For example, in expression a = b = c = 8 the assignment
operator is executed from right to left that means c will be assigned by 8, then b will be
assigned by c, and finally a will be assigned by b. You can parenthesize this expression
as (a = (b = (c = 8))).
Note that, you can change the priority of a Java operator by enclosing the lower order
priority operator in parentheses but not the associativity. For example, in expression (1 +
2) * 3 addition will be done first because parentheses has higher priority than
multiplication operator.

Before discussing individual classes of operators, below table presents all Java operators
from highest to lowest precedence along with their associativity.

Table 1: Java operators - precedence rules highest to lowest

Precedence Operator Description Associativity


[] array index
1 () method call Left -> Right
. member access
++ pre or postfix increment
-- pre or postfix decrement
2 +- unary plus, minus Right -> Left
~ bitwise NOT
! logical NOT
(type cast) type cast
3 Right -> Left
new object creation

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

* multiplication
4 / division Left -> Right
% modulus (remainder)
+- addition, subtraction
5 Left -> Right
+ string concatenation
<< left shift
6 >> signed right shift Left -> Right
>>> unsigned or zero-fill right shift
< less than
<= less than or equal to
7 > greater than Left -> Right
>= greater than or equal to
instanceof reference test
== equal to
8 Left -> Right
!= not equal to
9 & bitwise AND Left -> Right
10 ^ bitwise XOR Left -> Right
11 | bitwise OR Left -> Right
12 && logical AND Left -> Right
13 || logical OR Left -> Right
14 ?: conditional (ternary) Right -> Left
=
+=
-=
*=
/= assignment
%= and short hand
15
&= assignment
^= operators
|=
<<=
>>=
>>>=

Type Conversion and Casting

🡪When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
❖ The two types are compatible.
❖ The destination type is larger than the source type.
🡪When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement
is required.
🡪For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other. However, there are no automatic conversions from the
numeric types to char or boolean. Also, char and boolean are not compatible with
each other. Java also performs an automatic type conversion when storing a literal
integer constant into variables of type byte, short, long, or char.
Casting Incompatible Types
🡪Although the automatic type conversions are helpful, they will not fulfill all needs. For
example, what if you want to assign an int value to a byte variable? This conversion
will not be performed automatically, because a byte is smaller than an int. This kind
of conversion is sometimes called a narrowing conversion, since you are explicitly
making the value narrower so that it will fit into the target type.
🡪To create a conversion between two incompatible types, you must use a cast. A
cast is simply an explicit type conversion.
Syntax: (target-type) value
🡪Here, target-type specifies the desired type to convert the specified value to.
int a;
byte b;
// ...
b = (byte) a;
Example:
class Conversion
{
public static void main(String args[])
{
double f=78.2;
int result;
result=(int)f;
System.out.println(" Conversion of float to int is:
"+result);

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
}
}Output:

F:\JAVA Programs for ECE>javac Conversion.java

F:\JAVA Programs for ECE>java Conversion

Conversion of float to int is: 78

Flow of Control statements

🡪Control statements are the statements. Which alter the flow of execution and provide
better control to the programmer. They are useful to write better and complex
programs.

The following control statements are available in java.

1. Conditional or decision making or selection statements

2. Loop control or Iteration statements

3. Branching or Unconditional or Jump statements

1. Conditional Statements: these conditional statements include the following

a) if else statement

b) nested if statement

c) if else if ladder

d) switch case statement

2. Loop Statements: these iteration statements include the following

a) while loop

b) do while loop

c) for loop

3. Branching Statements: these jump statements include the following

a) break

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
b) continue

c) return

1. Conditional Statements:

a) if else statement:

🡪This statement is used to perform a task depending upon whether the given condition is
true or false. Here a task represents single statement or group of statements.

Syntax: if(condition)

{ //true block

//statements;

else

{ //false block

//Statements;

Here if condition is true then statement1 will be executed. if condition is false then
statement2 will be executed. Statement1 and statement2 represent either a single
statements or more than one statement. If more than one statement is used then they should
be enclosed in angular bracket {}.

Eg: if(a>b)

System.out.println(“the value of a=” +a);

else

System.out.println(“the value of b=” +b);

b) Nested if statement:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
🡪A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the
else and that is not already associated with an else.

Syntax: if(condition1)
{
if(condition2)
//Statements;

if(condition3)
//Statements;

else

//Statements;

else

//Statements;

Eg: if(i == 10)

{
if(j < 20)
a = b;
if(k > 100)
c = d; // this if is
else
a = c; // associated with this else
}
else
a = d; // this else refers to if(i == 10)
🡪As the comments indicate, the final else is not associated with if(j<20) because it is not in
the same block (even though it is the nearest if without an else). Rather, the final else is

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
associated with if(i==10). The inner else refers to if(k>100) because it is the closest if
within the same block.

d) if-else-if Ladder:
🡪A common programming construct that is based upon a sequence of nested ifs is the if-
else-if ladder.
Syntax: if(condition)
// statement;
else if(condition)
// statement;
else if(condition)
// statement;
else
//statement;
🡪The if statements are executed from the top down. As soon as one of the conditions
controllingthe if is true, the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else statement will
be executed. The final else acts as a default condition; that is, if all other conditional
tests fail, then thelast else statement is performed. If there is no final else and all other
conditions are false,then no action will take place.

Eg: int fib(int m)


{
if(m==1)
return 1;
else if(m==2)
return 1;
else
return (fib(m-1)+fib(m-2));
}

e) switch:

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
🡪The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an expression.
As such, it often provides a better alternative than a large series of if-else-if statements.
Syntax: switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:

// statement sequence
break;
default:
// default statement sequence}

🡪The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the expression.
🡪Each case value must be a unique literal (that is, it must be a constant, not a
variable). 🡪Duplicate case values are not allowed.

Eg: switch(i)
{
case 0: System.out.println("i is zero.");
break;
case 1: System.out.println("i is one.");
break;
case 2: System.out.println("i is two.");
break;
case 3: System.out.println("i is three.");

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
break;
default: System.out.println("i is greater than 3.");
}
2. Loop Statements:
🡪Java’s iteration statements are for, while, and do-while. These statements create
what we commonly call loops. As you probably know, a loop repeatedly executes
the same set of instructions until a termination condition is met.
a)while loop:
🡪The while loop is Java’s most fundamental loop statement. It repeats a statement
or block
while its controlling expression is true.

Syntax: while(condition)
{
// body of loop
}
🡪The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true. When condition becomes
false, control passes to the next line of code immediately following the loop. The
curly braces are unnecessary if only a single statement is being repeated.
Eg: while(c<n)
{
a=b;
b=c;
c=a+b;
}

b) do-while loop:
🡪If the conditional expression controlling a while loop is initially false, then the
body of the loop will not be executed at all. However, sometimes it is desirable to
execute the body of a loop at least once, even if the conditional expression is false
to begin with. In other words, there are times when you would like to test the
termination expression at the end of the loop rather than at the beginning.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
Fortunately, Java supplies a loop that does just that: the do-while. The do-while
loop always executes its body at least once, because its conditional expression is at
the bottom of the loop.
Syntax: do
{
// body of loop
} while (condition);
🡪Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates. As with all of Java’s loops, condition must be a
Boolean expression.
🡪The do-while loop is especially useful when you process a menu selection,
because you will usually want the body of a menu loop to execute at least once.
Consider the following program, which implements a very simple help system for
Java’s selection and iteration statements:

Eg: int n=10;


do
{
System.out.println(n);
n--;
}while(n>0);

c) for loop:
🡪Beginning with JDK 5, there are two forms of the for loop.
● The traditional form that has been in use since the original version of Java.
● The new “for-each” form.
🡪 When the loop starts, the initialization portion of the loop is executed.
Initialization expression executed only once and then condition is evaluated. This
must be a Boolean expression.
🡪 Check the condition; if the condition is true, then the body of the loop is
executed. If it is fail, the loop terminates.

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
🡪 Next, the iteration portion of the loop is executed and goes to increment or
decrement the loop control variable and again checks the condition if it is true, then
the body of the loop is executed. This process is repeated up to the condition is fail.
Syntax: traditional for statement:
for(initialization; condition; iteration)
{
// body
}

Eg: for(i=1;i<=n;i++)
{
a=b;
b=c;
c=a+b;
}

Declaring Loop Control Variables Inside the for Loop


for(datatype initialization; condition; iteration)
{
// body

Eg: for(int i=1;i<=n;i++)


{
a=b;
b=c;
c=a+b;
}

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*

3. Branching Statements:
🡪Java supports three jump statements: break, continue, and return. These
statements transfer
control to another part of your program.
a) break:
🡪In Java, the break statement has three uses.
● it terminates a statement sequence in a switch statement.
● it can be used to exit a loop.
● it can be used as a “civilized” form of goto.
🡪 The last two uses are explained here.

Using break to Exit a Loop


🡪By using break, you can force immediate termination of a loop, bypassing the
conditional expression and any remaining code in the body of the loop. When a
break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.
Eg: for(int i=0; i<100; i++)
{
if(i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}

Using break as a Form of Goto


🡪In addition to its uses with the switch statement and loops, the break statement
can also be employed by itself to provide a “civilized” form of the goto statement.
🡪 Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. This usually makes goto-ridden code hard to
understand and hard to maintain. It also prohibits certain compiler optimizations.
🡪For example, the goto can be useful when you are exiting from a deeply nested
set of loops. To handle such situations, Java defines an expanded form of the break
statement. By using this form of break. For example, break out of one or more
blocks of code. These blocks need not be part of a loop or a switch. They can be

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE


PA
JAVA PROGRAMMING GE
\*
any block. Further, you can specify precisely where execution will resume, because
this form of break works with a label. break gives you the benefits of a goto
without its problems.
Syntax: break label;
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break.");
if(t)
break second; // break out of second block
System.out.println("This won't execute");
}
}
System.out.println("This is after second block.");
}
Output:
Before the break.
This is after second block.

b) continue:
🡪 The continue statement performs such an action. In while and do-while loops, a
continue statement causes control to be transferred directly to the conditional
expression that controls the loop.
🡪In a for loop, control goes first to the iteration portion of the for statement and
then to the conditional expression. For all three loops, any intermediate code is
bypassed.
Eg: for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0) continue;
Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE
PA
JAVA PROGRAMMING GE
\*
System.out.println("");
}

c) return:
🡪The last control statement is return. The return statement is used to explicitly
return from a method. That is, it causes program control to transfer back to the
caller of the method. As such, it is categorized as a jump statement.
🡪At any time in a method the return statement can be used to cause execution to
branch back to the caller of the method. Thus, the return statement immediately
terminates the method in which it is executed.
Here, return causes execution to return to the Java run-time system, since it is the
run-time system that calls main( ).
Eg: int fib(int m)
{
if(m==1)
return 1;
else if(m==2)
return 1;
else
return (fib(m-1)+fib(m-2));
}

Prepared by O.Aruna Sri, Asst. Professor, Dept. of CSE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy