Professional Documents
Culture Documents
Short
16 bit signed integer
Range -32,768 to 32,767
Used in larger arrays to save memory space
Long
64 bit signed integer
Minimum value is -9,223,372,036,854,775,808 and Maximum value is
9,223,372,036,854,775,807
This data type is used if there is a need of higher range than Int.
Default value for Long data type is 0L
Float
Single precision 32bit IEEE 754 floating point.
Float is used to deal with larger array of floating point numbers to save the
memory.
Default value for Float data type is 0.0f.
Double
Double precision 64 bit IEEE 754 floating point.
Default data type / choice for decimal values
Default value for Double data type is 0.0d.
Boolean
Boolean data types represent 1 bit information
There are only two possible values for Boolean data types i.e true and false
Boolean data types are mainly used in condition checking.
Default value for Boolean data type is false.
Char
Single 16 bit Unicode Character
Range is '\u0000' - '\uffff'
Used to store a character
Range
Data Type
Arithmetic operators
These operators are used in constructing mathematical expressions. Java provides all the common
arithmetic operators used algebra including +,-,/,*,% . All these operators have the same
functionalities as in other languages.
Operator Meaning
+ Unary plus or addition operator
- Unary minus or subtraction
operator
/ Division operator
* Multiplication
% Modulo Division (Remainder
Operator)
Relational Operator
When there is a need to compare two quantities, relational operators are used. An expression like
p>q or p>=30 having a relational is known as relational expression. The output of a relational
expression is either TRUE or FALSE. There are 6 relational operators in Java which are given in the
following table.
Operator Meaning
== Is equal to
!= Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
These relational operators are used in Decision making and Branching to decide the execution
control in a program.
Logical Operators
There are three logical operators in Java. These operators are logical AND, logical OR and logical
NOT. The logical operators logical AND ,logical OR are used when there is a need to form a
compound condition with a combination of two or more relational expressions.
Assignment Operator
Assignment operators come in existence when there is a need of assigning value of a specified
expression to a given variable.
Instead of assignment operator, java also provides shorthand assignment operators with the following
syntax:
Variable operator = expression;
The above expression is equivalent to variable=variable operator (expression)
a1 = 4;
a2 = 8;
a2 *= a1;
System. out .println( "a1 is " +a1);
System. out .println( "a2 is " +a2);
value is 10
a1 is 4
a2 is 12
a1 is 4
a2 is 4
a1 is 4
a2 is 32
a1 is 4
a2 is 2
a1 is 4
a2 is 0
Pre-increment operator
Preincrement operator “++” is applied to a Variable by writing it
before the variable’s name.
Preincrement operator firstly increases the value of variable by 1 and
then that incremented value is used in that expression.
We can’t apply this operator with final variables or constants.
Post-increment operator
Postincrement operator “++” is applied to a Variable by writing it after
the variable’s name.
Postincremnt operator firstly use the same non-incremented value in
that expression and after that increases that variable by 1.
We can’t apply this operator with final variables or constants.
Example:
class Increment {
public static void main (String args[]) {
int p = 1;
int q = 2;
int r;
int s;
r = ++q;
s =p++;
r++;
System.out.println(“p = “ + p);
System.out.println(“q= “ + q);
System.out.println(“r = “ + r);
System.out.println(“s = “ +s);
}
}
p=2
q=3
r= 4
s=1
If you are well understood with the above program,, then you please try decrement
operator yourself. It works in the same way as increment with a single difference that
it decreases value by 1 instead of increasing.
Conditional Operator
Ternary operator is a very important conditional operator provided by Java. It has the conditional
statements of following form:
Expression 1 ? expression 2 : expression 3
In the above conditional statement, firstly expression 1 is calculated and the result of the conditional
expression depends on its result whether it is true or false.
If expression 1 is true then expression 2 is evaluated and it becomes the resultant or final value of the
above given conditional statement.
If expression 1 is false then expression 3 is evaluated and it becomes the resultant or final value of
the above given conditional statement. Always remember, only one of the both expression 2 and
expression 3 is calculated depending of expression1’s result.
p = 10;
q = 15;
r= ( p > q ) ? p : q ;
In the above given example, r is assigned the same value as q.
This operator behaves same as if-else. Above program in if-else
if(p>q)
r=p;
else
r=q;
Bitwise operators
Java provides a rich set of bitwise operators which operate on individual bits of an integer. In case,
operand is shorter than int then before applying bitwise operations that is converted into int. These
operators can’t be applied to double or float.
Firstly an integer is represented in binary form and after that bitwise operators are applied on the
individual bits of the binary forms of the corresponding operands. For example 6 is represented in
binary as 110 . 2’s complement is used for storing negative numbers.
Precedence with
Operator Type Associativity
Rank
() Parentheses
1 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
2 Right to left
-- Unary post-decrement
Unary pre-increment
++
Unary pre-decrement
--
Unary plus
3 + Unary minus Right to left
- Unary logical negation
! Unary bitwise
~ complement
( type ) Unary type cast
* Multiplication
4 / Division Left to right
% Modulus
+ Addition
5 Left to right
- Subtraction
Bitwise left shift
<< Bitwise right shift with
6 >> sign extension Left to right
>>> Bitwise right shift with
zero extension
Relational less than
Relational less than or
<
equal
<=
Relational greater than
7 > Left to right
Relational greater than
>=
or equal
instanceof
Type comparison
(objects only)
Relational is equal to
==
8 Relational is not equal Left to right
!=
to
9 & Bitwise AND Left to right
10 ^ Bitwise exclusive OR Left to right
11 | Bitwise inclusive OR Left to right
12 && Logical AND Left to right
13 || Logical OR Left to right
14 ?: Ternary conditional Right to left
Assignment
=
Addition assignment
+=
Subtraction assignment
-=
15 Multiplication Right to left
*=
assignment
/=
Division assignment
%=
Modulus assignment
Chapter 3:
Decision Making Statements in Java
Sometimes there is a need to take decisions on the basis of given condition. Based on the given
conditions, it is the decided that which condition is satisfied and statements corresponding to
that conditions is executed.
There are mainly three types of decision making statements in Java
1. If statement
2. switch statement
3. conditional operator statement
Program
int test1=10;
if (test1>10)
system.out.println(“you are wrong”);
if(test1>5)
{
System.out.println("good");
}
}
}
Result of this program is “good”.
2. if else statement
In case the if condition is true then the statements inside curly brackets of if block is executed
otherwise statements of the else block are executed.
If(condition)
{
if condition is true, these statements will be executed.
}
else
{
in case the condition given in if statement is false , these statements will be executed.
}
these statements are executed always.
Program
if (test1>10)
{
system.out.println(“you are wrong”);}
else
{
System.out.println("good");
}
}
}
Output
good
3. if–else-if ladder
Syntax with meaning
If(condition1)
{
Statements // executed only if condition1 is true.}
else if (condition2)
{
Statements // executed only if condition1 is true
}
.
.
.
else if (condition-n)
{
Statements // execute only when condition-n is true}
else
{
Statements // executes when all above given conditions are false.
}
Statements // these statements are always executed.
4. Nested if…else statement
When there are a series of decision, then we have to use a number of if-else statements in nested
form.
if( condition1){
//Executes when the condition 1 is true
if( condition2){
//Executes when the condition 2 is true
}
}
public class Test1 {
if( a >10 ){
if(a== 30)
system.out.println(” a is equal to 30”);
else
system.out.println(“ a is not equal to 30”);
}
else System.out.print("a is less than 10");
}
}
}
}
Output : 30
The switch Statement
As we studied, if statements are useful in deciding the sequence control of program. But in case when
there a number of alternatives to be tested against a variable, then the complexity of the program with
a number of IF statements increase. Switch statements solves this problem by allowing a variable to
be tested against a list of values. These values are called cases. When the variable is matched with a
particular case then the statements of that particular case is executed.
Syntax:
Switch (expression ){
case value1 :
block1
break; //optional
case value2 :
block2
break; //optional
…………………………………………..
……………………………………………….
………………………………………………………
default : //Optional
//default block
}
Rules for switch statement
The switch statement can have a variable of type short,int,byte or char.
A Switch block can have any number of case statements with the following syntax
Case value :
any The value specified in case should be of same data type as variable in the switch
statement. Also this value must be any constant or literal.
When the variable of switch statement is matched with nay case value then the
statements following that case will be executed until Break statement is reached.
As the execurion reaches to a break statement, the switch terminates, and the execution
is transferred to the next line following the switch block.
Putting Break in each case is not necessary. In case no Break appears, the execution falls
through the subsequent given cases until a Break is executed or the switch terminates.
There may be an optional default case in a switch at the end of switch. Default case is
executed when value of a variable is unmatched with all given cases.
Example:
public class Test1 {
switch(letter)
{
case 'P' :
System.out.println("Duffer");
break;
case 'Q' :
case 'S' :
System.out.println("Excellent");
break;
case 'R' :
System.out.println("You failed");
Case 'F' :
System.out.println("try again");
break;
default :
System.out.println("Invalid input");
}
}
}
Output:
Excellent
Sometimes there is a need to execute a block of statements several times depending on any condition.
This type of situation is handled by Loops in java.
Java allows these loops mechanisms with three types of loops:
for Loop
while Loop
do...while Loop
while( a < 20 ) {
System.out.print("value of a : " + a);
a++;
}
}
}
The do...while Loop
This loop is similar to other loops with a major difference that this loop is always executed at least
once while the other for and While loops are executed only when condition or Boolean expression is
true. For and while loop may be executed for Zero times if the condition is false.
Syntax:
do
{
//body for the loop
}while ( Boolean_expression);
Since this loop has the testing condition at the end of loop , the loop is executed at least once always.
The execution of this loop is otherwise very similar to While loop. Firstly loop is executed and then
boolen_expression is evaluated. If expression is true then loop is executed again and again until the
Boolean expression is false.
Example:
Similar program for printing value of a from 10 to 19 using do….. while loop is given below.
public class demo2 {
public static void main(String args[]){
int a = 10;
do{
System.out.print("value of a : " + a );
a++;
}while( a< 20 );
}
}
Enhanced for loop
Enhanced for loop is mainly used in case of arrays.
Syntax:
for (declaration : expression)
{
// Body for enhanced for loop
}
Expression in the above given syntax generally represents the array which is nneeded to lop through.
This expression is either an array variable or a method call returning array.
Declaration is a block variable with the same type as the array we are accessing. This variable has
its scope within this for block with a value equal to current array element.
Example:
public class Demo {
public static void main(String args[]){
int [] values = {10, 20, 30, 40, 50};
for(int a : values ){
System.out.print( a );
System.out.print(" ");
}
System.out.print("\n");
String [] students ={"James", "Anil", "Tom", "Aman"};
for( String name : students ) {
System.out.print( name );
System.out.print(" ");
}
}
}
Result:
10 20 30 40 50
James Anil Tom Aman
break Keyword
Java provides break keyword which is used to terminate the entire loop. This keyword can be used
inside a loop or switch statement to terminate that lop or switch.
Keep in mind that in case of nested loops, break keyword only terminates the execution of innermost
loop transferring the execution to the first statement following that loop.
Example:
public class Demo {
public static void main(String args[]) {
int [] values = {10, 20, 30, 40, 50};
for(int a : values) {
if( a == 40 ) {
break;
}
System.out.print( a );
System.out.print("\n");
}
}
}
Output:
10
20
30
As the value of a is equal to 40 , the break statement executes and terminates the loop.
Continue Keyword
Continue keyword can be used in any loop structure for deciding the execution control.
When continue is used in for loop then the control is immediately transferred to the
update statement without executing the statements after continue.
In case of while or do-while, control is immediately transferred to the Boolean
expression without executing the statements after continue.
Example:
public class Continue {
public static void main(String args[]) {
int [] values = {10, 20, 30, 40, 50};
Class: A class is a user-defined data type which acts as a blueprint to represent the states and
behaviors for the corresponding objects.
Object: Objects are instances of a class and have their own states and behaviors. For example an
object dog for an animal class has state as name, color, breed and behaviors as eating, barking and
wagging.
There are a number of objects in our surroundings which include dog, human, table, bird, mobile , etc.
All these objects have their specific states and behaviors.
In case of a person as object, corresponding states are name, color, height, age and behaviors are
eating, walking, running, etc.
Defining a class
Class is a user defined data type serving as a blueprint. A simple class is defined with the following
form:
Class classname
{
Data members or fields declaration; // optional
Methods or member functions declaration; // optional
}
As data members and member functions are optional, so Java allows even an empty class.
Fields and Methods declaration
As we know, data is encapsulated in Java by placing its data members and member functions inside a
class. These variables are known as instance variables as they are created as an object is instantiated.
The method of declaring instance variables is same as local variables.
Class Person
{
Int age;
String name;
String color;
}
This class has three instance variables one age of integer type and other two name and color of string
type.
Declaring Methods
A method declaration generally has the following things:
Name for the method
Return type of that method
List of arguments or parameters
Body for that method which actually defines the operations to be performed on data.
The general form for method declaration is
returnType MethodName ( argument-list)
{
Body for the method;
}
A class can have following types of variables:
Instance variables: The variables defined inside a class but outside any method are
known as instance variables. As a class is loaded, these variables are instantiated. These
variables can be accessed from any method or block including constructor of that particular
class.
Local variables: The variables defined inside any method, constructor or blocks are
known as local variables. The variable are declared and initialized within a particular
method and destroyed with the completion of that method.
Class variables: These variables are defined inside a class but outside any method with
a single difference that they are declared using Static keyword.
In the above given example name, color, age are data member and eating, hungry, walking, running,
sleeping all these are functions.
Example for a class
public class Person {
String Name;
String color;
int age;
void eating(){
}
void hungry(){
}
void Walking (){
}
void Running (){
}
void sleeping(){
}
}
Constructors
Constructor is the most important topic which comes into the mind as there is a discussion about a
class. Every class has at least one constructor. If a programmer does not explicitly specify any
constructor, there is always a default constructor for that class. As a object is created, a constructor is
invoked.
Important points for a constructor
Constructor has the same name as class.
There is no return type for a constructor even not void.
There can be multiple constructors for a single class.
If constructors are explicitly defined by the programmer then default constructor not
comes in existence.