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