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]);
}
}
}
}
Ad

More Related Content

What's hot (20)

Php operators
Php operatorsPhp operators
Php operators
Aashiq Kuchey
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
VB Script
VB ScriptVB Script
VB Script
Satish Sukumaran
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
Secure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injectionSecure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injection
Secure Code Warrior
 
Unsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST APIUnsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST API
Mikhail Egorov
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 
Php variables (english)
Php variables (english)Php variables (english)
Php variables (english)
Mahmoud Masih Tehrani
 
Java Notes
Java NotesJava Notes
Java Notes
Abhishek Khune
 
C language industrial training report
C language industrial training reportC language industrial training report
C language industrial training report
Raushan Pandey
 
Basic calculator
Basic calculatorBasic calculator
Basic calculator
luvMahajan3
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
React JS part 1
React JS part 1React JS part 1
React JS part 1
Diluka Wittahachchige
 
Java exception-handling
Java exception-handlingJava exception-handling
Java exception-handling
Suresh Kumar Reddy V
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development Fundamentals
Mohammed Makhlouf
 
Algorithmic Notations
Algorithmic NotationsAlgorithmic Notations
Algorithmic Notations
Muhammad Muzammal
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
Type Casting in C++
Type Casting in C++Type Casting in C++
Type Casting in C++
Sachin Sharma
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 
C presentation
C presentationC presentation
C presentation
APSMIND TECHNOLOGY PVT LTD.
 
Understanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree TechnologiesUnderstanding React hooks | Walkingtree Technologies
Understanding React hooks | Walkingtree Technologies
Walking Tree Technologies
 
Secure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injectionSecure Code Warrior - CRLF injection
Secure Code Warrior - CRLF injection
Secure Code Warrior
 
Unsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST APIUnsafe JAX-RS: Breaking REST API
Unsafe JAX-RS: Breaking REST API
Mikhail Egorov
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
Ajit Jadhav
 
C language industrial training report
C language industrial training reportC language industrial training report
C language industrial training report
Raushan Pandey
 
Basic calculator
Basic calculatorBasic calculator
Basic calculator
luvMahajan3
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
Mindfire Solutions
 
Web Application Development Fundamentals
Web Application Development FundamentalsWeb Application Development Fundamentals
Web Application Development Fundamentals
Mohammed Makhlouf
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
Sowmya Jyothi
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
Muhammad Hammad Waseem
 

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

Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Computer Programmer
 
C Programming with oops Concept and Pointer
C Programming with oops Concept and PointerC Programming with oops Concept and Pointer
C Programming with oops Concept and Pointer
Jeyarajs7
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
Rakesh Madugula
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
Niket Chandrawanshi
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
JAVA programming language made easy.pptx
JAVA programming language made easy.pptxJAVA programming language made easy.pptx
JAVA programming language made easy.pptx
Sunila31
 
Java teaching ppt for the freshers in colleeg.ppt
Java teaching ppt for the freshers in colleeg.pptJava teaching ppt for the freshers in colleeg.ppt
Java teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
ArnaldoCanelas
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Javatut1
Javatut1 Javatut1
Javatut1
desaigeeta
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
rnkhan
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Computer Programmer
 
C Programming with oops Concept and Pointer
C Programming with oops Concept and PointerC Programming with oops Concept and Pointer
C Programming with oops Concept and Pointer
Jeyarajs7
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
 
JAVA programming language made easy.pptx
JAVA programming language made easy.pptxJAVA programming language made easy.pptx
JAVA programming language made easy.pptx
Sunila31
 
Java teaching ppt for the freshers in colleeg.ppt
Java teaching ppt for the freshers in colleeg.pptJava teaching ppt for the freshers in colleeg.ppt
Java teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
rnkhan
 
Ad

More from DevaKumari Vijay (20)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
DevaKumari Vijay
 
Os ch1
Os ch1Os ch1
Os ch1
DevaKumari Vijay
 
Unit2
Unit2Unit2
Unit2
DevaKumari Vijay
 
Unit 1
Unit 1Unit 1
Unit 1
DevaKumari Vijay
 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
DevaKumari Vijay
 
Decisiontree&amp;game theory
Decisiontree&amp;game theoryDecisiontree&amp;game theory
Decisiontree&amp;game theory
DevaKumari Vijay
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
DevaKumari Vijay
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
DevaKumari Vijay
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
DevaKumari Vijay
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
DevaKumari Vijay
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
DevaKumari Vijay
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
DevaKumari Vijay
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
DevaKumari Vijay
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
DevaKumari Vijay
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
DevaKumari Vijay
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
DevaKumari Vijay
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
DevaKumari Vijay
 
Ad

Recently uploaded (20)

puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
The History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptxThe History of Kashmir Karkota Dynasty NEP.pptx
The History of Kashmir Karkota Dynasty NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast BrooklynBridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
Bridging the Transit Gap: Equity Drive Feeder Bus Design for Southeast Brooklyn
i4jd41bk
 
Cultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptxCultivation Practice of Garlic in Nepal.pptx
Cultivation Practice of Garlic in Nepal.pptx
UmeshTimilsina1
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
MCQ PHYSIOLOGY II (DR. NASIR MUSTAFA) MCQS)
Dr. Nasir Mustafa
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 

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]); } } } }
  翻译: