SlideShare a Scribd company logo
Unit-2
Data Types,Variables,Operators,Conditionals,Loops
and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 A primitive data type specifies the size and type of
variable values, and it has no additional methods.
 1)byte – 8-bit integer type
 2)short – 16-bit integer type
 3)int – 32-bit integer type
 4)long – 64-bit integer type
 5)float – 32-bit floating-point type
 6)double – 64-bit floating-point type
 7)char – symbols in a character set
 8)boolean – logical values true and false
Primitive Data Types
 byte: 8-bit integer type. Range: -128 to 127.
 Example: byte b = -15; Usage: particularly when working with
data streams.
 short: 16-bit integer type. Range: -32768 to 32767. Example:
short c = 1000;
 Usage: probably the least used simple type.
 int: 32-bit integer type. Range: -2147483648 to 2147483647.
 Example: int b = -50000; Usage:
 1) Most common integer type.
 2) Typically used to control loops and to index arrays.
 3) Expressions involving the byte, short and int values are
promoted to int before calculation.
 long: 64-bit integer type. Range: -9223372036854775808 to
9223372036854775807.
 Example: long l = 10000000000000000;
 Usage: 1) useful when int type is not large enough to hold the
desired value
 float: 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038.
 Example: float f = 1.5;
 Usage: 1) fractional part is needed
 2) large degree of precision is not required
 double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308.
 Example: double pi = 3.1416;
 Usage: 1) accuracy over many iterative calculations
 2) manipulation of large-valued numbers
 char: 16-bit data type used to store characters. Range: 0 to
65536.
 Example: char c = ‘a’;
 Usage: 1) Represents both ASCII and Unicode character
sets; Unicode defines a character set with characters found
in (almost) all human languages.
 2) Not the same as in C/C++ where char is 8-bit and
represents ASCII only.
 boolean: Two-valued type of logical values. Range: values
true and false.
 Example: boolean b = (1<2);
 Usage: 1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for
 Java uses variables to store data.
 To allocate memory space for a variable JVM requires:
1) to specify the data type of the variable
2) optionally, the variable may be assigned an initial
value
All done as part of variable declaration.
Eg: int a=10;
Variables
 Types of Variables -There are three types of variables in java:
 1) Local Variable- A variable declared inside the body of the
method is called local variable. You can use this variable only
within that method and the other methods in the class aren't
even aware that the variable exists. A local variable cannot be
defined with "static" keyword.
 2) Instance Variable- A variable declared inside the class but
outside the body of the method, is called instance variable. It
is not declared as static.
 It is called instance variable because its value is instance
specific and is not shared among instances.
 3) Static Variable - A variable which is declared as static is
called static variable. It cannot be local. You can create a single
copy of static variable and share among all the instances of
the class. Memory allocation for static variable happens only
once when the class is loaded in the memory.
class A
{
int a=10,b=20; //instance variable
static int m=100; //static variable
void add()
{
int c; //local variable
c=a+b;
System.out.println(“Sum:”+c);
}
}
 a = 9;
 b = 8.99f;
 c = 'A';
 x = false;
 y = "Hello World";
Excercise
 Operators are used to perform operations on
variables and values.
 Java divides the operators into the following groups:
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Bitwise operators
Operators
Operator Name Description Example
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from
another
x - y
* Multiplicatio
n
Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a
variable by 1
++x
-- Decrement Decreases the value of a
variable by 1
--x
Arithmetic operator
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Assignment operators
Operator Name Example
== Equal to x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Comparison operators: returns true
or false
Operato
r
Name Description Example
&& Logical and Returns true if both
statements are true
x < 5 && x <
10
|| Logical or Returns true if one of
the statements is true
x < 5 || x < 4
! Logical not Reverse the result,
returns false if the
result is true
!(x < 5 && x
< 10)
Logical operators
Operator Description Example Same as Result Decimal
& AND - Sets each bit to 1 if both bits
are 1
5 & 1 0101 &
0001
0001 1
| OR - Sets each bit to 1 if any of the
two bits is 1
5 | 1 0101 |
0001
0101 5
~ NOT - Inverts all the bits ~ 5 ~0101 1010 10
^ XOR - Sets each bit to 1 if only one of
the two bits is 1
5 ^ 1 0101 ^
0001
0100 4
<< Zero-fill left shift - Shift left by
pushing zeroes in from the right and
letting the leftmost bits fall off
9 << 1 1001 << 1 0010 2
>> Signed right shift - Shift right by
pushing copies of the leftmost bit in
from the left and letting the
rightmost bits fall off
9 >> 1 1001 >> 1 1100 12
>>> Zero-fill right shift - Shift right by
pushing zeroes in from the left and
letting the rightmost bits fall off
9 >>> 1 1001 >>> 1 0100 4
Bitwise operator
Syntax:
 variable = Expression1 ? Expression2: Expression
 If operates similar to that of the if-else statement as
in Exression2 is executed if Expression1 is true
else Expression3 is executed.
if(Expression1)
{
variable = Expression2;
}
else
{ variable = Expression3; }
Ternary operator
 Java has the following conditional statements:
 Use if to specify a block of code to be executed, if a
specified condition is true
 Use else to specify a block of code to be executed, if the
same condition is false
 Use else if to specify a new condition to test, if the first
condition is false
 Use switch to specify many alternative blocks of code to
be executed
Conditionals
 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
}
Example:
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
If statement
 The else Statement
 Use the else statement to specify a block of code to be
executed if the condition is false.
 Syntax
if (condition)
{ // block of code to be executed if the condition is true }
else
{ // block of code to be executed if the condition is false }
 Example
int time = 20;
if (time < 18)
{ System.out.println("Good day."); }
else { System.out.println("Good evening.");
} // Outputs "Good evening."
 The else if Statement
 Use the else if statement to specify a new condition if
the first condition is false.
 Syntax
if (condition1)
{ // block of code to be executed if condition1 is true }
else if (condition2)
{ // block of code to be executed if the condition1 is false
and condition2 is true }
else
{ // block of code to be executed if the condition1 is false
and condition2 is false }
 Demo.java
Public class Demo{
public static void main(String[] args){
int time = 22;
if (time < 10)
{ System.out.println("Good morning."); }
else if (time < 20)
{ System.out.println("Good day."); }
else
{ System.out.println("Good evening."); }
}
}
// Outputs "Good evening."
 Syntax:
switch(expression)
{
case x: // code block
break;
case y: // code block
break;
default: // code block
}
Switch Statements
Use the switch statement to select one of many code blocks
to be executed.
 The switch expression is evaluated once.
 The value of the expression is compared with the values of
each case.
 If there is a match, the associated block of code is
executed.
 The break and default keywords are optional,
 When Java reaches a break keyword, it breaks out of the
switch block.
 This will stop the execution of more code and case testing
inside the block.
public class Demo1{
public static void main(String[] args){
int day = 4;
switch (day)
{
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
}
}
}
// Outputs "Thursday" (day 4)
 When you know exactly how many times you want to
loop through a block of code, use the for loop
 Syntax
for (initialization; condition; incr/decr)
{ // code block to be executed }
Initialization: is executed (one time) before the execution
of the code block.
Condition: defines the condition for executing the code
block.
Increment/decrement: is executed (every time) after the
code block has been executed.
Simple For Loop
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
If we have a for loop inside the another loop, it is known as nested
for loop. The inner loop executes completely whenever outer loop
executes.
public class NestedForExample {
public static void main(String[] args) {
//loop of i
for(int i=1;i<=3;i++){
//loop of j
for(int j=1;j<=3;j++){
System.out.println(i+" "+j);
}//end of i
}//end of j
}
}
Nested For Loop
Java for-each Loop
The for-each loop is used to traverse array or collection
in java. It is easier to use than simple for loop because
we don't need to increment value and use subscript
notation.
It works on elements basis not index. It returns element
one by one in the defined variable.
Syntax:
for(Type var:array){
//code to be executed
}
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Java Labeled For Loop
• We can have a name of each Java for loop.
• use label before the for loop.
• It is useful if we have nested for loop so that we can
break/continue specific for loop.
• Usually, break and continue keywords
breaks/continues the innermost for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
outer:
for(int i=1;i<=3;i++){
inner:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break outer;
}
System.out.println(i+" "+j);
}
}
}
}
Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be
infinitive for loop.
Syntax:
for(;;){
//code to be executed
}
While Loop
The java while loop is used to iterate a part of
the program several times.
If the number of iteration is not fixed, it is
recommended to use while loop.
Syntax:
while(condition){
//code to be executed
}
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Infinite While Loop
If you pass true in the while loop, it will be infinite while loop.
Syntax:
while(true){
//code to be executed
}
Example:
public class WhileExample2 {
public static void main(String[] args) {
while(true){
System.out.println("infinitive while loop");
}
}
}
Java do-while Loop
 The Java do-while loop is used to iterate a
part of the program several times.
• If the number of iteration is not fixed and
you must have to execute the loop at least
once, it is recommended to use do-while
loop.
• The Java do-while loop is executed at least
once because condition is checked after loop
body.
Syntax:
do{
//code to be executed
}while(condition);
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Infinite do-while Loop
If you pass true in the do-while loop, it will be infinite
do-while loop.
Syntax:
do{
//code to be executed
}while(true);
 Break Statement
 When a break statement is encountered inside a loop,
the loop is immediately terminated and the program
control resumes at the next statement following the
loop.
 The Java break statement is used to break loop
or switch statement. It breaks the current flow of the
program at specified condition.
 In case of inner loop, it breaks only inner loop.
 We can use Java break statement in all types of loops
such as for loop, while loop and do-while loop.
public class BreakWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}
}
}
public class BreakDoWhileExample {
public static void main(String[] args) {
//declaring variable
int i=1;
//do-while loop
do{
if(i==5){
//using break statement
i++;
break;//it will break the loop
}
System.out.println(i);
i++;
}while(i<=10);
}
}
Java Continue Statement
 The continue statement breaks one iteration (in the
loop), if a specified condition occurs, and continues
with the next iteration in the loop.
 The Java continue statement is used to continue the
loop. It continues the current flow of the program
and skips the current iteration at the specified
condition.
 In case of an inner loop, it continues the inner loop
only.
 We can use Java continue statement in all types of
loops such as for loop, while loop and do-while loop.
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++){
if(i==5){
//using continue statement
continue;//it skips current iteration
}
System.out.println(i);
}
}
}
//Java Program to illustrate the use of continue statement
//inside an inner loop
public class ContinueExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement inside inner loop
continue;
}
System.out.println(i+" "+j);
}
}
}
}
public class ContinueWhileExample {
public static void main(String[] args) {
//while loop
int i=1;
while(i<=10){
if(i==5){
//using continue statement
i++;
continue;//it will skip the rest statement
}
System.out.println(i);
i++;
}
}
}
 An array is a container object that holds a fixed number of
values of a single type. The length of an array is established
when the array is created.
// declares an array of integers
int[] anArray;
// allocates memory for 10 integers
anArray = new int[10];
• An array declaration has two components: the array's type
and the array's name
• the declaration does not actually create an array; it simply
tells the compiler that this variable will hold an array of the
specified type.
• dataType[] arrayRefVar = {value0, value1, ..., valuek};
Arrays
 boolean[] anArrayOfBooleans;
 char[] anArrayOfChars;
 String[] anArrayOfStrings;
 Arrays can be initialized when they are declared:
 int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified
elements
Array Initialization
public class TestArray {
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements
for (int i = 0; i < myList.length; i++)
{ System.out.println(myList[i] + " "); } // Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++)
{ total += myList[i]; }
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max)
max = myList[i];
}
System.out.println("Max is " + max); } }
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the
array elements
for (double element: myList)
{ System.out.println(element); }
}
}
 A multidimensional array is an array containing one or
more arrays.
 To create a two-dimensional array, add each array
within its own set of curly braces:
 Example
 int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
 To access the elements of the myNumbers array,
specify two indexes: one for the array, and one for
the element inside that array. Example
 int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
 int x = myNumbers[1][2];
 System.out.println(x);
Multidimensional Arrays
 declaration: int array[][];
• creation: int array = new int[2][3];
• initialization int array[][] = { {1, 2, 3}, {4, 5, 6} };
public class MyClass
{
public static void main(String[] args)
{
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
}
}
}
}

More Related Content

PPTX
Built in function
MD. Rayhanul Islam Sayket
 
DOCX
Inline function(oops)
Jay Patel
 
PDF
Functions-Computer programming
nmahi96
 
PPT
friend function(c++)
Ritika Sharma
 
PPTX
Procedural programming
Ankit92Chitnavis
 
PPTX
Inheritance in c++
Vineeta Garg
 
PDF
Understanding Implicits in Scala
datamantra
 
PPTX
System software - macro expansion,nested macro calls
SARASWATHI S
 
Built in function
MD. Rayhanul Islam Sayket
 
Inline function(oops)
Jay Patel
 
Functions-Computer programming
nmahi96
 
friend function(c++)
Ritika Sharma
 
Procedural programming
Ankit92Chitnavis
 
Inheritance in c++
Vineeta Garg
 
Understanding Implicits in Scala
datamantra
 
System software - macro expansion,nested macro calls
SARASWATHI S
 

What's hot (20)

PPT
Function overloading(c++)
Ritika Sharma
 
PPTX
Operator Overloading & Function Overloading
Meghaj Mallick
 
PPT
Data types and Operators
raksharao
 
PPTX
CS304PC:Computer Organization and Architecture Session 23 Decimal Arithmetic ...
Guru Nanak Technical Institutions
 
PPT
Class and object in C++
rprajat007
 
PPTX
OOP - Benefits and advantages of OOP
Mudasir Qazi
 
PPTX
Memory organization in computer architecture
Faisal Hussain
 
PPT
Array in c
Ravi Gelani
 
PPTX
Constructors and destructors
Vineeta Garg
 
PDF
Data Structures Practical File
Harjinder Singh
 
PPTX
data types in C programming
Harshita Yadav
 
PPTX
Storage class in C Language
Nitesh Kumar Pandey
 
PPTX
Infix to postfix conversion
Then Murugeshwari
 
PPTX
pipelining
sudhir saurav
 
PDF
Programed I/O Modul..
Myster Rius
 
PDF
Object oriented programming c++
Ankur Pandey
 
PDF
Operator overloading
Pranali Chaudhari
 
PPTX
Function in c program
umesh patil
 
PPTX
Chapter 03 arithmetic for computers
Bảo Hoang
 
PPTX
Sap 1
Syed Ahmed
 
Function overloading(c++)
Ritika Sharma
 
Operator Overloading & Function Overloading
Meghaj Mallick
 
Data types and Operators
raksharao
 
CS304PC:Computer Organization and Architecture Session 23 Decimal Arithmetic ...
Guru Nanak Technical Institutions
 
Class and object in C++
rprajat007
 
OOP - Benefits and advantages of OOP
Mudasir Qazi
 
Memory organization in computer architecture
Faisal Hussain
 
Array in c
Ravi Gelani
 
Constructors and destructors
Vineeta Garg
 
Data Structures Practical File
Harjinder Singh
 
data types in C programming
Harshita Yadav
 
Storage class in C Language
Nitesh Kumar Pandey
 
Infix to postfix conversion
Then Murugeshwari
 
pipelining
sudhir saurav
 
Programed I/O Modul..
Myster Rius
 
Object oriented programming c++
Ankur Pandey
 
Operator overloading
Pranali Chaudhari
 
Function in c program
umesh patil
 
Chapter 03 arithmetic for computers
Bảo Hoang
 
Sap 1
Syed Ahmed
 
Ad

Similar to Unit 2-data types,Variables,Operators,Conitionals,loops and arrays (20)

PPTX
UNIT 2 programming in java_operators.pptx
jijinamt
 
PPTX
Introduction to Java
Ashita Agrawal
 
PPTX
Basic_Java_02.pptx
Kajal Kashyap
 
PPTX
Java
Aashish Jain
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
PPT
Chapter 2&3 (java fundamentals and Control Structures).ppt
henokmetaferia1
 
PDF
data types.pdf
HarshithaGowda914171
 
PPTX
MODULE_2_Operators.pptx
VeerannaKotagi1
 
PPSX
DITEC - Programming with Java
Rasan Samarasinghe
 
PPTX
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
PPTX
Java Basic Elements Lecture on Computer Science
AnezkaJaved
 
PPTX
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
PPTX
Operators in java
Madishetty Prathibha
 
PPTX
Java fundamentals
HCMUTE
 
PPTX
ChapterTwoandThreefnfgncvdjhgjshgjdlahgjlhglj.pptx
berihun18
 
PDF
BIT211_2.pdf
Sameer607695
 
PPSX
Java session4
Jigarthacker
 
PPTX
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PDF
KeyJavaConcepts to EnhanceYour AutomationTesting Skills
digitaljignect
 
UNIT 2 programming in java_operators.pptx
jijinamt
 
Introduction to Java
Ashita Agrawal
 
Basic_Java_02.pptx
Kajal Kashyap
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Chapter 2&3 (java fundamentals and Control Structures).ppt
henokmetaferia1
 
data types.pdf
HarshithaGowda914171
 
MODULE_2_Operators.pptx
VeerannaKotagi1
 
DITEC - Programming with Java
Rasan Samarasinghe
 
JPC#8 Introduction to Java Programming
Pathomchon Sriwilairit
 
Java Basic Elements Lecture on Computer Science
AnezkaJaved
 
UNIT – 2 Features of java- (Shilpa R).pptx
shilpar780389
 
Operators in java
Madishetty Prathibha
 
Java fundamentals
HCMUTE
 
ChapterTwoandThreefnfgncvdjhgjshgjdlahgjlhglj.pptx
berihun18
 
BIT211_2.pdf
Sameer607695
 
Java session4
Jigarthacker
 
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
KeyJavaConcepts to EnhanceYour AutomationTesting Skills
digitaljignect
 
Ad

More from DevaKumari Vijay (20)

PPTX
Unit 1 computer architecture (1)
DevaKumari Vijay
 
PPTX
Os ch1
DevaKumari Vijay
 
PPTX
Unit2
DevaKumari Vijay
 
PPTX
Unit 1
DevaKumari Vijay
 
PPTX
Unit 2 monte carlo simulation
DevaKumari Vijay
 
PPTX
Decisiontree&amp;game theory
DevaKumari Vijay
 
PPTX
Unit2 network optimization
DevaKumari Vijay
 
PPTX
Unit 4 simulation and queing theory(m/m/1)
DevaKumari Vijay
 
PPTX
Unit4 systemdynamics
DevaKumari Vijay
 
PPTX
Unit 3 des
DevaKumari Vijay
 
PPTX
Unit 1 introduction to simulation
DevaKumari Vijay
 
PPTX
Unit2 montecarlosimulation
DevaKumari Vijay
 
PPT
Unit 3-Greedy Method
DevaKumari Vijay
 
PPTX
Unit 5 java-awt (1)
DevaKumari Vijay
 
PPTX
Unit 4 exceptions and threads
DevaKumari Vijay
 
PPTX
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
PPTX
Unit3 part2-inheritance
DevaKumari Vijay
 
PPTX
Unit3 part1-class
DevaKumari Vijay
 
PPTX
Unit1 introduction to Java
DevaKumari Vijay
 
PPT
Introduction to design and analysis of algorithm
DevaKumari Vijay
 
Unit 1 computer architecture (1)
DevaKumari Vijay
 
Unit 2 monte carlo simulation
DevaKumari Vijay
 
Decisiontree&amp;game theory
DevaKumari Vijay
 
Unit2 network optimization
DevaKumari Vijay
 
Unit 4 simulation and queing theory(m/m/1)
DevaKumari Vijay
 
Unit4 systemdynamics
DevaKumari Vijay
 
Unit 3 des
DevaKumari Vijay
 
Unit 1 introduction to simulation
DevaKumari Vijay
 
Unit2 montecarlosimulation
DevaKumari Vijay
 
Unit 3-Greedy Method
DevaKumari Vijay
 
Unit 5 java-awt (1)
DevaKumari Vijay
 
Unit 4 exceptions and threads
DevaKumari Vijay
 
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Unit3 part2-inheritance
DevaKumari Vijay
 
Unit3 part1-class
DevaKumari Vijay
 
Unit1 introduction to Java
DevaKumari Vijay
 
Introduction to design and analysis of algorithm
DevaKumari Vijay
 

Recently uploaded (20)

PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
PDF
Landforms and landscapes data surprise preview
jpinnuck
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PPTX
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
Understanding operators in c language.pptx
auteharshil95
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
Sandeep Swamy
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
ACUTE NASOPHARYNGITIS. pptx
AneetaSharma15
 
Landforms and landscapes data surprise preview
jpinnuck
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
An introduction to Dialogue writing.pptx
drsiddhantnagine
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Understanding operators in c language.pptx
auteharshil95
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 

Unit 2-data types,Variables,Operators,Conitionals,loops and arrays

  • 3.  A primitive data type specifies the size and type of variable values, and it has no additional methods.  1)byte – 8-bit integer type  2)short – 16-bit integer type  3)int – 32-bit integer type  4)long – 64-bit integer type  5)float – 32-bit floating-point type  6)double – 64-bit floating-point type  7)char – symbols in a character set  8)boolean – logical values true and false Primitive Data Types
  • 4.  byte: 8-bit integer type. Range: -128 to 127.  Example: byte b = -15; Usage: particularly when working with data streams.  short: 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000;  Usage: probably the least used simple type.  int: 32-bit integer type. Range: -2147483648 to 2147483647.  Example: int b = -50000; Usage:  1) Most common integer type.  2) Typically used to control loops and to index arrays.  3) Expressions involving the byte, short and int values are promoted to int before calculation.
  • 5.  long: 64-bit integer type. Range: -9223372036854775808 to 9223372036854775807.  Example: long l = 10000000000000000;  Usage: 1) useful when int type is not large enough to hold the desired value  float: 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038.  Example: float f = 1.5;  Usage: 1) fractional part is needed  2) large degree of precision is not required  double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308.  Example: double pi = 3.1416;  Usage: 1) accuracy over many iterative calculations  2) manipulation of large-valued numbers
  • 6.  char: 16-bit data type used to store characters. Range: 0 to 65536.  Example: char c = ‘a’;  Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages.  2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.  boolean: Two-valued type of logical values. Range: values true and false.  Example: boolean b = (1<2);  Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for
  • 7.  Java uses variables to store data.  To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) optionally, the variable may be assigned an initial value All done as part of variable declaration. Eg: int a=10; Variables
  • 8.  Types of Variables -There are three types of variables in java:  1) Local Variable- A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword.  2) Instance Variable- A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.  It is called instance variable because its value is instance specific and is not shared among instances.  3) Static Variable - A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.
  • 9. class A { int a=10,b=20; //instance variable static int m=100; //static variable void add() { int c; //local variable c=a+b; System.out.println(“Sum:”+c); } }
  • 10.  a = 9;  b = 8.99f;  c = 'A';  x = false;  y = "Hello World"; Excercise
  • 11.  Operators are used to perform operations on variables and values.  Java divides the operators into the following groups: 1. Arithmetic operators 2. Assignment operators 3. Comparison operators 4. Logical operators 5. Bitwise operators Operators
  • 12. Operator Name Description Example + Addition Adds together two values x + y - Subtraction Subtracts one value from another x - y * Multiplicatio n Multiplies two values x * y / Division Divides one value by another x / y % Modulus Returns the division remainder x % y ++ Increment Increases the value of a variable by 1 ++x -- Decrement Decreases the value of a variable by 1 --x Arithmetic operator
  • 13. Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 Assignment operators
  • 14. Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y Comparison operators: returns true or false
  • 15. Operato r Name Description Example && Logical and Returns true if both statements are true x < 5 && x < 10 || Logical or Returns true if one of the statements is true x < 5 || x < 4 ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10) Logical operators
  • 16. Operator Description Example Same as Result Decimal & AND - Sets each bit to 1 if both bits are 1 5 & 1 0101 & 0001 0001 1 | OR - Sets each bit to 1 if any of the two bits is 1 5 | 1 0101 | 0001 0101 5 ~ NOT - Inverts all the bits ~ 5 ~0101 1010 10 ^ XOR - Sets each bit to 1 if only one of the two bits is 1 5 ^ 1 0101 ^ 0001 0100 4 << Zero-fill left shift - Shift left by pushing zeroes in from the right and letting the leftmost bits fall off 9 << 1 1001 << 1 0010 2 >> Signed right shift - Shift right by pushing copies of the leftmost bit in from the left and letting the rightmost bits fall off 9 >> 1 1001 >> 1 1100 12 >>> Zero-fill right shift - Shift right by pushing zeroes in from the left and letting the rightmost bits fall off 9 >>> 1 1001 >>> 1 0100 4 Bitwise operator
  • 17. Syntax:  variable = Expression1 ? Expression2: Expression  If operates similar to that of the if-else statement as in Exression2 is executed if Expression1 is true else Expression3 is executed. if(Expression1) { variable = Expression2; } else { variable = Expression3; } Ternary operator
  • 18.  Java has the following conditional statements:  Use if to specify a block of code to be executed, if a specified condition is true  Use else to specify a block of code to be executed, if the same condition is false  Use else if to specify a new condition to test, if the first condition is false  Use switch to specify many alternative blocks of code to be executed Conditionals
  • 19.  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 } Example: if (20 > 18) { System.out.println("20 is greater than 18"); } If statement
  • 20.  The else Statement  Use the else statement to specify a block of code to be executed if the condition is false.  Syntax if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }  Example int time = 20; if (time < 18) { System.out.println("Good day."); } else { System.out.println("Good evening."); } // Outputs "Good evening."
  • 21.  The else if Statement  Use the else if statement to specify a new condition if the first condition is false.  Syntax if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }
  • 22.  Demo.java Public class Demo{ public static void main(String[] args){ int time = 22; if (time < 10) { System.out.println("Good morning."); } else if (time < 20) { System.out.println("Good day."); } else { System.out.println("Good evening."); } } } // Outputs "Good evening."
  • 23.  Syntax: switch(expression) { case x: // code block break; case y: // code block break; default: // code block } Switch Statements Use the switch statement to select one of many code blocks to be executed.
  • 24.  The switch expression is evaluated once.  The value of the expression is compared with the values of each case.  If there is a match, the associated block of code is executed.  The break and default keywords are optional,  When Java reaches a break keyword, it breaks out of the switch block.  This will stop the execution of more code and case testing inside the block.
  • 25. public class Demo1{ public static void main(String[] args){ int day = 4; switch (day) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; case 3: System.out.println("Wednesday"); break; case 4: System.out.println("Thursday"); break; case 5: System.out.println("Friday"); break; case 6: System.out.println("Saturday"); break; case 7: System.out.println("Sunday"); break; } } } // Outputs "Thursday" (day 4)
  • 26.  When you know exactly how many times you want to loop through a block of code, use the for loop  Syntax for (initialization; condition; incr/decr) { // code block to be executed } Initialization: is executed (one time) before the execution of the code block. Condition: defines the condition for executing the code block. Increment/decrement: is executed (every time) after the code block has been executed. Simple For Loop
  • 27. public class ForExample { public static void main(String[] args) { //Code of Java for loop for(int i=1;i<=10;i++){ System.out.println(i); } } }
  • 28. If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes completely whenever outer loop executes. public class NestedForExample { public static void main(String[] args) { //loop of i for(int i=1;i<=3;i++){ //loop of j for(int j=1;j<=3;j++){ System.out.println(i+" "+j); }//end of i }//end of j } } Nested For Loop
  • 29. Java for-each Loop The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation. It works on elements basis not index. It returns element one by one in the defined variable. Syntax: for(Type var:array){ //code to be executed }
  • 30. public class ForEachExample { public static void main(String[] args) { //Declaring an array int arr[]={12,23,44,56,78}; //Printing array using for-each loop for(int i:arr){ System.out.println(i); } } }
  • 31. Java Labeled For Loop • We can have a name of each Java for loop. • use label before the for loop. • It is useful if we have nested for loop so that we can break/continue specific for loop. • Usually, break and continue keywords breaks/continues the innermost for loop only. Syntax: labelname: for(initialization;condition;incr/decr){ //code to be executed }
  • 32. public class LabeledForExample { public static void main(String[] args) { //Using Label for outer and for loop outer: for(int i=1;i<=3;i++){ inner: for(int j=1;j<=3;j++){ if(i==2&&j==2){ break outer; } System.out.println(i+" "+j); } } } }
  • 33. Infinitive For Loop If you use two semicolons ;; in the for loop, it will be infinitive for loop. Syntax: for(;;){ //code to be executed }
  • 34. While Loop The java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop. Syntax: while(condition){ //code to be executed }
  • 35. public class WhileExample { public static void main(String[] args) { int i=1; while(i<=10){ System.out.println(i); i++; } } }
  • 36. Infinite While Loop If you pass true in the while loop, it will be infinite while loop. Syntax: while(true){ //code to be executed } Example: public class WhileExample2 { public static void main(String[] args) { while(true){ System.out.println("infinitive while loop"); } } }
  • 37. Java do-while Loop  The Java do-while loop is used to iterate a part of the program several times. • If the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do-while loop. • The Java do-while loop is executed at least once because condition is checked after loop body. Syntax: do{ //code to be executed }while(condition);
  • 38. public class DoWhileExample { public static void main(String[] args) { int i=1; do{ System.out.println(i); i++; }while(i<=10); } }
  • 39. Infinite do-while Loop If you pass true in the do-while loop, it will be infinite do-while loop. Syntax: do{ //code to be executed }while(true);
  • 40.  Break Statement  When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.  The Java break statement is used to break loop or switch statement. It breaks the current flow of the program at specified condition.  In case of inner loop, it breaks only inner loop.  We can use Java break statement in all types of loops such as for loop, while loop and do-while loop.
  • 41. public class BreakWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using break statement i++; break;//it will break the loop } System.out.println(i); i++; } } }
  • 42. public class BreakDoWhileExample { public static void main(String[] args) { //declaring variable int i=1; //do-while loop do{ if(i==5){ //using break statement i++; break;//it will break the loop } System.out.println(i); i++; }while(i<=10); } }
  • 43. Java Continue Statement  The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.  The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the current iteration at the specified condition.  In case of an inner loop, it continues the inner loop only.  We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
  • 44. public static void main(String[] args) { //for loop for(int i=1;i<=10;i++){ if(i==5){ //using continue statement continue;//it skips current iteration } System.out.println(i); } } }
  • 45. //Java Program to illustrate the use of continue statement //inside an inner loop public class ContinueExample2 { public static void main(String[] args) { //outer loop for(int i=1;i<=3;i++){ //inner loop for(int j=1;j<=3;j++){ if(i==2&&j==2){ //using continue statement inside inner loop continue; } System.out.println(i+" "+j); } } } }
  • 46. public class ContinueWhileExample { public static void main(String[] args) { //while loop int i=1; while(i<=10){ if(i==5){ //using continue statement i++; continue;//it will skip the rest statement } System.out.println(i); i++; } } }
  • 47.  An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. // declares an array of integers int[] anArray; // allocates memory for 10 integers anArray = new int[10]; • An array declaration has two components: the array's type and the array's name • the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type. • dataType[] arrayRefVar = {value0, value1, ..., valuek}; Arrays
  • 48.  boolean[] anArrayOfBooleans;  char[] anArrayOfChars;  String[] anArrayOfStrings;
  • 49.  Arrays can be initialized when they are declared:  int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31}; Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements Array Initialization
  • 50. public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
  • 51. public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } }
  • 52.  A multidimensional array is an array containing one or more arrays.  To create a two-dimensional array, add each array within its own set of curly braces:  Example  int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };  To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. Example  int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };  int x = myNumbers[1][2];  System.out.println(x); Multidimensional Arrays
  • 53.  declaration: int array[][]; • creation: int array = new int[2][3]; • initialization int array[][] = { {1, 2, 3}, {4, 5, 6} };
  • 54. public class MyClass { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } } }