JAVA 2nd UNIt(Chapter-1)
JAVA 2nd UNIt(Chapter-1)
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.
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.
🡪 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.
Data Types:
● Primitive data types - includes byte, short, int, long, float, double, boolean and char
● Non-primitive data types - such as String, Arrays and Classes
A primitive data type specifies the size and type of variable values, and it has no additional
methods.
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Examples:
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.
❖ 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.
🡪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,
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.
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.
● 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:
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.
● aaa
● sales_tax
● _circleArea
● box100width
● $directory
● ab1234$$
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.
All the classes, interfaces, packages, methods and fields of java programming language are
given according to java naming convention.
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.
Keywords:
Literals:
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:
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:
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
\d Octal
\xd Hexadecimal
'\
Digit 0
u0030'
'\
Punctuation ;
u003b'
'\
Space
u0020'
'\ Horizontal
u0009' Tab
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.
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
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.
1. Unary Operator:
● negating an expression
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
% remainder of division
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
Operator Description
> Check if operand on the left is greater than operand on the right
Example:
class Relational_operators1{
public static void main(String as[])
{
int a, b;
a=40;
b=30;
|| Logical OR (a || b) is true
5. Bitwise Operators:
6. Ternary Operator:
The conditional operator or ternary operator ?: is shorthand for the if-then-else statement.
The syntax of the conditional operator is:
Example:
import java.util.*;
class ternary
{
public static void main(String arg[])
{
Output:
Before discussing individual classes of operators, below table presents all Java operators
from highest to lowest precedence along with their associativity.
* 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
|=
<<=
>>=
>>>=
🡪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:
🡪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.
a) if else statement
b) nested if statement
c) if else if ladder
a) while loop
b) do while loop
c) for loop
a) break
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)
else
b) Nested if statement:
Syntax: if(condition1)
{
if(condition2)
//Statements;
if(condition3)
//Statements;
else
//Statements;
else
//Statements;
{
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
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.
e) switch:
// 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.");
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.
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.
Eg: for(i=1;i<=n;i++)
{
a=b;
b=c;
c=a+b;
}
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.
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));
}