0% found this document useful (0 votes)
5 views57 pages

chap_2

The document provides an overview of Java comments, tokens, variables, and constants. It details the types of comments (single line, multi line, and documentation), various tokens (keywords, identifiers, literals, operators, and separators), and the different types of variables (local, instance, and static). Additionally, it explains the concept of constants in Java as fixed values that do not change during program execution.

Uploaded by

adinathgire2645
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views57 pages

chap_2

The document provides an overview of Java comments, tokens, variables, and constants. It details the types of comments (single line, multi line, and documentation), various tokens (keywords, identifiers, literals, operators, and separators), and the different types of variables (local, instance, and static). Additionally, it explains the concept of constants in Java as fixed values that do not change during program execution.

Uploaded by

adinathgire2645
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Java Comments :

- The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about the
variable, method, class or any statement. It can also be used to hide program code for
specific time.

Types of Java Comments

There are 3 types of comments in java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Single Line Comment

- The single line comment is used to comment only one line.

Syntax:

//This is single line comment

Example:

class CommentExample1 {
public static void main(String[] args) {
int id=10; // Here, id is a variable
System.out.println(id);
}
}

Output:
10

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


2) Multi Line Comment
- The multiline comment is used to comment multiple lines of code.
Syntax:

/*
This
is
multi line
comment
*/

Example:

class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int id=10;
System.out.println(id); // 10
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


3) Documentation Comment
- The documentation comment is used to create documentation API. To create documentation
API, you need to use javadoc tool.

Syntax:

/**
* This
* is
* documentation
* comment
*/

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b) {
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b) {
return a-b;
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Java Tokens :
- The smallest individual unit of a program which are identified by the compiler.
- It can be any symbol, punctuation mark etc.
- Following are the types of token used in java
1) Keyword
2) Identifier
3) Literal
4) Operators
5) Separator

1) Keywords

- Java keywords are also known as reserved words. Keywords are particular words which acts
as a key to a code. These are predefined words by Java so it cannot be used as a variable or
object name.

- Keywords are words that have already been defined for Java compiler. They have special
meaning for the compiler. Java Keywords must be in your information because you cannot use
them as a variable, class or a method name.

- You can't use keyword as identifier in your Java programs, its reserved words in Java library
and used to perform an internal operation. A list of Java keywords or reserved words are given
below:

true, false and null are not reserved words but cannot be used as identifiers, because it is
literals of built-in types.
B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]
2) identifiers

- In programming languages, identifiers are used for identification purpose. In Java, an


identifier can be a class name, method name, variable name or a label.
- It is a user given name to an variable class and methods.
For Example :

class Test

public static void main(String[] args)

int a = 20;

}
In the above java code, we have 5 identifiers name :
 Test : class name.
 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for Identifiers in Java

There are certain rules for declaring an identifier. We need to follow these rules otherwise we
will get a compile-time error.
1. A valid identifier has characters [A-Z],[a-z] or numbers [0-9], $ (dollar sign)
and _ (underscore). For example, @dataflair is not a valid identifier, because it contains @
which is a special character.
2. We can’t declare a variable with space. For example, data flair is invalid.
3. We can’t start an identifier with a number. For example, 222dataflair is not a valid
identifier.
4. As there is no limit on the length of an identifier but it is 4 – 15 letters only appropriate to
use.
5. It is not recommended to use Reserved words as an identifier. For example, int float=5; is
not a valid statement.
6. The variable name should be meaningful which easily depicts the logic.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


3) Literals :

- Literals are constant in java program and their value does not change throughout the
program.

int id=10;

String name="Ravi";

float salary=10000.50;

Types of Literals :

1. Integer Literals

2. Real Literals

3. Character Literals

4. String Literals

5. Boolean Literals

6. Null Literals

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


4) Operators
- Operators are symbols that perform operations on variables and values. For example,
+ is an operator used for addition, while * is also an operator used for multiplication.
- Following are the list of some important Operators are present in Java:

a) Arithmetic Operators
b) Assignment Operators
c) Relational Operators
d) Logical Operators
e) Unary Operators

a) Arithmetic Operators

- Arithmetic operators are used to perform arithmetic operations on variables and data.
For example,

c=a+b;

- Here, the + operator is used to addition of two variables a and b. Similarly, there are
various other arithmetic operators in Java.

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

class ArithmeticOperators {

public static void main(String[] args) {

int a = 12, b = 5;

System.out.println("a + b = " + (a + b));

System.out.println("a - b = " + (a - b));

System.out.println("a * b = " + (a * b));

System.out.println("a / b = " + (a / b));

System.out.println("a % b = " + (a % b));

- In the above example, we have used +, -, and * operators to compute addition,


subtraction, and multiplication operations.

b) Assignment Operators

- Assignment operators are used in Java to assign values to variables. For example,

int age;

age = 5;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.

Let's see some more assignment operators available in Java.

Operator Example Equivalent to Operator Example


= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

class AssignmentOperatorExample {

public static void main(String[] args) {

int id=10;

System.out.println("id is: " + id);

id+=5;

System.out.println("new id is: " + id);

Example:

class AssignmentOperators {

public static void main(String[] args) {

int a = 4;

int var;

var = a;

System.out.println("var using =: " + var);

var += a;

System.out.println("var using +=: " + var);

var *= a;

System.out.println("var using *=: " + var);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


c) Relational Operators

- Relational operators are used to check the relationship between two operands. For example,

// check if a is less than b

a < b;

Here, < operator is the relational operator. It checks if a is less than b or not.

It returns either true or false.

Operator Description Example


== Is Equal To 3 == 5 returns false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
>= Greater Than or Equal To 3 >= 5 returns false
<= Less Than or Equal To 3 <= 5 returns true

Example:

class RelationalOperators {

public static void main(String[] args) {

int a = 7, b = 11;

System.out.println("a is " + a + " and b is " + b);

System.out.println(a == b); // false

System.out.println(a != b); // true

System.out.println(a > b); // false

System.out.println(a < b); // true

System.out.println(a >= b); // false

System.out.println(a <= b); // true

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


d) Logical Operators

- Logical operators are used to check whether an expression is true or false. They are used in
decision making.

Operator Example Meaning


&& (Logical AND) expression1 && expression2 true only if both expression1
and expression2 are true
|| (Logical OR) expression1 || expression2 true if either expression1 or
expression2 is true
! (Logical NOT) !expression true if expression is false and
vice versa

Example:

class LogicalOperators {

public static void main(String[] args) {

// && operator

System.out.println((5 > 3) && (8 > 5)); // true

System.out.println((5 > 3) && (8 < 5)); // false

// || operator

System.out.println((5 < 3) || (8 > 5)); // true

System.out.println((5 > 3) || (8 < 5)); // true

System.out.println((5 < 3) || (8 < 5)); // false

// ! operator

System.out.println(!(5 == 3)); // true

System.out.println(!(5 > 3)); // false

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


e) Unary Increment and Decrement Operators

- Java also provides increment and decrement operators: ++ and -- respectively. ++ increases
the value of the operand by 1, while -- decrease it by 1. For example,

int num = 5;

// increase num by 1

num++;

Here, the value of num gets increased to 6 from its initial value of 5.

Example

class UnaryOperator {

public static void main(String[] args) {

int num = 5;

System.out.println("num value is = " + num);

num++;

System.out.println("incremented value is = " + num);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

class Main {

public static void main(String[] args) {

// declare variables

int a = 10, b = 10;

int result1, result2;

// original value

System.out.println("Value of a: " + a);

// increment operator

result1 = ++a;

System.out.println("After increment: " + result1);

System.out.println("Value of b: " + b);

// decrement operator

result2 = --b;

System.out.println("After decrement: " + result2);

In the above program, we have used the ++ and -- operator as prefixes (++a, --b). We can also
use these operators as postfix (a++, b++).

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


5) Separators :

- They are the special characters in java, which are used to separate variables or the
characters.

Example:

parenthesis( ), brackets[ ], braces { }, period . , semicolon ; etc.

Separator Name Use


. Period It is used to separate the
package name from sub-
package name and class.
, Comma It is used to separate the
consecutive variables of same
type while declaration.
; Semicolon It is used to terminate the
statement in java
() Parenthesis This holds the list of
parameters in method
definition. Also used in
control statement and type
casting.
{} Braces This is used to define the
block of code, class, methods
[] Brackets It is used in array declaration

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Java Variables

- Variables are containers for storing data values.


- A variable is a container which holds the value while the java program is executed.
- A variable is assigned with a data type.
- Variable is a name of memory location.

- in Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. char values are surrounded by single
quotes
 boolean - stores values with two states: true or false

Variable Declaration:

- To declare a variable, you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are :

int a, b, c ;

float pi ;

double d ;

char a;

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Variable initialization:

- To initialize a variable, you must assign it a valid value.

You can combine variable declaration and initialization.

Example:

int a=2, b=4, c=6;

float pi=3.14f;

double do=20.22d;

char a= 'V';

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Types of variables

- in Java, there are three types of variables:

1. Local Variables
2. Instance Variables
3. Static Variables

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.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance
variable

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. Memory
allocation for static variable happens only once when the class is loaded in the memory.

Example: Types of Variables in Java

class Demo {

int data = 100; //instance variable

static int a = 1; //static variable

void method() {

int b = 90; //local variable

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


- Here’s a program that uses all types of variables:

class Test {

static int b=200; //static variable

int c=300; // instance variable

public static void main(String[] args) {

Test obj=new Test();

int a=100; //local variable

System.out.println (a); // 100

System.out.println (Test.b); // 200

System.out.println (obj.c); // 300

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Constant :

- Constants in java are fixed values those are not changed during the execution of
program. A literal is a constant value that can be classified as integer literals, string
literals and boolean literals. To make a static field constant in Java, make a variable as
both static and final. java supports several types of Constants those are

Integer Constants 3

Real Constants: 234.890

Character Constants: 'S' , '1' etc.

String Constants: "Hello" , "12345" etc.

- A constant in Java is used to map an exact and unchanging value to a variable name.
- If you make any variable as final, you cannot change the value of final variable(It will be
constant).
- What the final keyword means is that once the value has been assigned, it cannot be re-
assigned.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Data Types in Java

- Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before
its use. That is why we need to declare variable's type and name.

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


boolean Data Type

It occupies 1 bit of memory. The Boolean data type is used to store only two possible values:
true and false. The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.

Example: boolean one = false;

byte Data Type

It occupies 1 byte of memory .Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

Example: byte value = 10;

short Data Type

It occupies 2 bytes of memory. Its value-range lies between -32,768 to 32,767 (inclusive). Its
minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

Example: short value = 10000;

int Data Type

It Occupies 4 bytes of memory. its value-range lies between - 2,147,483,648 to 2,147,483,647 (.


Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

Example: int value = 100000;

long Data Type

It occupies 8 bytes of memory. Its value-range lies between -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.

Example: long value = 100000L;

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


float Data Type

It Occupies 4 bytes of memory. its value range is unlimited. It is recommended to use a float
(instead of double) if you need to save memory in large arrays of floating point numbers. The
float data type should never be used for precise values, such as currency. Its default value is
0.0F.

Example: float num = 234.5f;

double Data Type

It occupies 8 bytes of memory. Its value range is unlimited. The double data type is generally
used for decimal values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.

Example: double data = 12.3;

char Data Type

It occupies 2 bytes of memory. The char data type is used to store characters.

Example: char letter = 'A';

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Java Arrays

- An array is an 'n' number of fixed collection of homogeneous data elements storing into
the single variable is called an array.
- In array we can store multiple values into the single variable, data type must be same.
- The main advantage of array is we can represent huge number of variables by using
single variable so that readability of code will be improved but the main disadvantage of
array is fixed in size that is once we create an array there is no chance of increasing or
decreasing the size based on our requirement hence to use array concept compulsory
we should know the size in advance which may not possible always.
- Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically

Types of Array in java

- There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


1) Single Dimensional Array

- A single dimensional array, also known as one-dimensional array.


- It is a collection of elements of the same type, stored in contiguous memory.
- It has a fixed size, with elements accessed using indices starting from zero (0).

Syntax to Declare an Array in Java

int[] x; (or)
int []x; (or)
int x[];

Instantiation of an Array in Java

int[] x=new int[5];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.

class TestArray {
public static void main(String args[]) {
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for (int i=0; i<a.length; i++) //length is the property of array
System.out.println (a[i]);
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int[] a={10,20,30,40}; //declaration, instantiation and initialization

Let's see the simple example to print this array.

class Testarray1 {
public static void main(String[] args) {
int array[]={10,20,30,40}; // declaration, instantiation and initialization
for(int i=0;i<array.length;i++) // length is the property of array
System.out.println(array[i]);
}
}

Output:

10

20

30

40

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Multidimensional Array

- A multidimensional array in java is a data structure that stores data in multiple


dimensions, such as rows and columns.
- It is also known as an "array of arrays ".

Syntax to Declare Multidimensional Array in Java

int[][] x; (or)
int [][]x; (or)
int x[][];

Example to instantiate Multidimensional Array in Java

int[][] x=new int[2][2]; // 2 row and 2 column

- Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

//Java Program to illustrate the use of multidimensional array

class MultiDiArray {
public static void main(String args[]) {
//declaring and initializing 2D array
int arr[][]={{10,20},{30,40}};
//printing 2D array
for (int i=0; i<2; i++) {
for (int j=0; j<2; j++) {
System.out.print (arr[i][j]+" ");
}
System.out.println();
}
}
}

Output:

10 20

30 40

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example :

class MultiDiArray2 {

public static void main(String[] args) {

int arr[][] = {{10,20,30}, {40,50,60}, {70,80,90}};

for (int i=0; i<3; i++){

for(int j=0; j<3; j++){

System.out.print(arr[i][j] + " ");

System.out.println();

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Java Type Casting

- Type casting is when you assign a value of one primitive data type to another type.
- In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger size type.

byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type.

double -> float -> long -> int -> char -> short -> byte

Widening Casting

- Widening casting is done automatically when passing a smaller size type to a larger size
type.

Example

public class Test {

public static void main(String[] args) {

int i = 100;

long l = i; //no explicit type casting required

float f = l; //no explicit type casting required

System.out.println ("Int value "+i); // 100

System.out.println ("Long value "+l); // 100

System.out.println ("Float value "+f); // 100.0

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example :

public class MyClass {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the
value:

Example :

public class MyClass {

public static void main(String[] args) {

double myDouble = 9.78;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Scanner class in java :

- The Scanner class is used to get user input, and it is found in the java.util package.

- To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:

Example 1:

import java.util.Scanner; // Import the Scanner class

class ScannerExample {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input

System.out.println("Username is: " + userName); // Output user input

Example 2:

import java.util.Scanner; // Import the Scanner class

class ScannerExample {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.print("Enter Number");

int no=myObj.nextInt();

System.out.println("Square is =" + (no*no));

} }

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


input Types

- In the example above, we used the nextLine() method, which is used to read Strings. To
read other types, look at the table below:

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various types:

Example:

import java.util.Scanner;
class ScannerExample {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter Name: " age and salary:");


// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
System.out.println("Enter Age : ");

System.out.println("Enter Salary: ");


double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name is : " + name);
System.out.println("Age is : " + age);
System.out.println("Salary is : " + salary);

}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Control flow Statement in java
- The control flow statement describes the order in which statement will be execute.
- Following are the list of control flow statements.

Decision Making Statements

- Java decision-making statements allow you to make a decision, based upon the result of
a condition. All the programs in Java have set of statements, which are executed
sequentially in the order in which they appear.
- Following are Decision Making Statements in Java -

 if statement
 if-else statement
 if-else-if ladder statement
 nested if statement
 switch statement

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


if Statement

- if statements in Java is used to control the program flow based on some condition.
- The Java if statement test the condition. It executes the if block if condition is true.
otherwise, it will get skipped.

Syntax:

if (condition) {
//code to be executed
}
Figure - Flowchart of if Statement:

Example 1:
public class IfExample {
public static void main(String[] args) {
int age=20;
if(age>=18) {
System.out.print("Age is greater than 18");
}
System.out.println("This statement is out of if block");
}
}

Output:

Age is greater than 18

This statement is outof if block

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example 2:

public class IfExample {

public static void main(String args[]) {


int a=20, b=30;

if (b>a)
System.out.println("b is greater");
}
}

Example 3:

public class IfExample {


public static void main(String[] args) {
int num=20;
if(num>0) {
System.out.println("Positive Number");
}
System.out.println("This statement is out of if block");
}
}

Example 4:
import java.util.Scanner;
public class IfExample
{
public static void main(String []args)
{
//Take input from the user
//Create an instance of the Scanner class
Scanner sc=new Scanner(System.in);
System.out.println("Enter the age: ");
int age=sc.nextInt();
//Determine whether the person is eligible to vote or not
if (age>=18)
{
System.out.println("The person is eligible for vote");
}
System.out.println("This statement is outof if block");

}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


if - else Statement

- The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.

Syntax:
if (condition) {
//code if condition is true
}
else {
//code if condition is false
}

Figure - Flowchart of if-else Statement:

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example1:

// program of odd and even number.

public class IfElseExample {

public static void main(String[] args) {

int number=15;

if(number%2==0) {

System.out.println("even number");

else {

System.out.println("odd number");

Output:

odd number

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example 2:

import java.util.Scanner;

public class IfElseExample {

public static void main(String []args) {

//Take input from the user

//Create an instance of the Scanner class

Scanner sc=new Scanner(System.in);

System.out.println("Enter the age: ");

int age=sc.nextInt();

//Determine whether the person is eligible to vote or not

if (age>=18)

System.out.println("The person is eligible for vote");

else {

System.out.println("The person is Not eligible for vote");

System.out.println("This statement is outof if else block");

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


if – else - if statement (ladder if Statement)

- In this statement based upon the condition corresponding statement block will be
execute .

Syntax:

if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example 1:

public class Number {

public static void main(String args[]) {


int a = 30, b = 30;

if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}

Example 2:

// Program to check POSITIVE, NEGATIVE or ZERO:

public class NumberIsPNZ {


public static void main(String[] args) {
int number=-15;
if(number>0) {
System.out.println("POSITIVE");
}
else if(number<0) {
System.out.println("NEGATIVE");
}
else {
System.out.println("ZERO");
}
}
}

Output:
NEGATIVE

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Nested if statement

- The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.

Syntax:

if (condition) {
//code to be executed
if (condition) {
//code to be executed
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}

Output:

You are eligible to donate blood

Example 2:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
} } }

Output:

You are not eligible to donate blood

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Ternary Operator

- We can also use ternary operator (? :) to perform the task of if...else statement. It is a
shorthand way to check the condition. If the condition is true, the result of ? is returned.
But, if the condition is false, the result of : is returned.

Example:

class Operator {

public static void main(String[] args) {

Double number = 5.5;

String result;

result = (number > 0.0) ? "positive" : "not positive";

System.out.println(result);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Switch Statement :

- The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement. The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and Long.
- In other words, the switch statement tests the equality of a variable against multiple
values.

- Following are some Points to Remember

o There can be one or N number of case values for a switch expression.


o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-time
error.
o Each case statement can have a break statement which is optional. When control
reaches to the break statement, it jumps the control after the switch expression. If a
break statement is not found, it executes the next case.

Syntax:

switch(expression) {
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]
Example

public class SwitchExample {


public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}

Output:

20

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Program to check Vowel or Consonant:

- If the character is A, E, I, O, or U, it is vowel otherwise consonant. It is not case-sensitive.

public class SwitchVowelExample {


public static void main(String[] args) {
char ch='O';
switch(ch)
{
case 'a':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
case 'A':
System.out.println("Vowel");
break;
case 'E':
System.out.println("Vowel");
break;
case 'I':
System.out.println("Vowel");
break;
case 'O':
System.out.println("Vowel");
break;
case 'U':
System.out.println("Vowel");
break;
default:
System.out.println("Consonant");

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


}
}
}

Example:

import java.util.Scanner; // Needed for the Scanner class

public class WeekDay

public static void main(String[] args)

int day; // to hold day value

// Create a Scanner object for keyboard input.

Scanner sc = new Scanner(System.in);

// Get day.

System.out.print("Enter number 1-7 : ");

day = sc.nextInt();

// Determine the corresponding week's day

switch (day)

case 1 :

System.out.println("Sunday");

break;

case 2 :

System.out.println("Monday");

break;

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


case 3 :

System.out.println("Tuesday");

break;

case 4 :

System.out.println("Wednesday");

break;

case 5 :

System.out.println("Thursday");

break;

case 6 :

System.out.println("Friday");

break;

case 7 :

System.out.println("Saturday");

break;

default :

System.out.println("Invalid input");

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Looping Statement :

- In programming languages, loops are used to execute a set of instructions/functions


repeatedly when some conditions become true. There are three types of loops in java.

o for loop
o while loop
o do-while loop

for loop

- A simple for loop is the same as C/C++. We can initialize the variable, check condition
and increment/decrement value. It consists of four parts:

1. initialization: It is the initial condition which is executed once when the loop starts.
Here, we can initialize the variable, or we can use an already initialized variable.
2. Condition: It is the condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value
either true or false.
3. Statement: The statement of the loop is executed each time until the condition is false.
4. Increment/Decrement: It increments or decrements the variable value.

Syntax:

for (initialization; condition; incr/decr) {


//statement or code to be executed
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Flowchart:

Example:

//Java Program to demonstrate the example of for loop


//which prints table of 1
public class ForExample {
public static void main(String[] args) {
for (int i=1;i<=10;i++){
System.out.println(i);
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Output:

1
2
3
4
5
6
7
8
9
10

while loop :

- The Java while loop is used to iterate a part of the program repeatedly until the
specified Boolean condition is true. As soon as the Boolean condition becomes false, the
loop automatically stops.
- 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
Increment / decrement statement
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

public class WhileExample {


public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Example:

public class WhileExample2 {


public static void main(String[] args) {
while(true){
System.out.println("infinitive while loop");
}
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


do - while loop

- The Java do-while loop is used to iterate a part of the program repeatedly, until the
specified condition is true. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use a do-while loop.
- Java do-while loop is called an exit control loop. Therefore, unlike while loop and for
loop, the do-while check the condition at the end of loop body. 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);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Example:

public class DoWhileExample {

public static void main(String[] args) {


int i=1;
do{
System.out.println(i);
i++;
} while(i<=10);
}
}

Output:

1
2
3
4
5
6
7
8
9
10

Example :

public class DoWhileExample2 {


public static void main(String[] args) {
do{
System.out.println("infinitive do while loop");
} while(true);
}
}

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


Jumping Statement in java

- The jumping statements are the control statements which transfer the program
execution control to a specific statements.
- Java has three types of jumping statements they are break, continue, and return. These
statements transfer execution control to another part of the program.

break statement (to exit a loop) :

- The break statement can also be used to jump out of a loop


- We can use break statement in the following cases
- Inside the switch case to come out of the switch block.
- Within the loops to break the loop execution based on some condition.

This example jumps out of the loop when i is equal to 4:

public class MyClass {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 4) {

break;

System.out.println(i);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


continue statement :

- The continue statement is used when you need to jump to the next iteration of the loop
immediately. (in the loop), if a specified condition occurs, and continues with the next
iteration in the loop.

This example skips the value of 4:

public class MyClass {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

System.out.println(i);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]


return statement :

- The return statement is used to explicitly return from a method. That is, it causes a
program control to transfer back to the caller of the method.

Example:

public class MyClass1 {

public static void main(String[] args) {

for (int i = 0; i < 10; i++) {

if (i == 5) {

return;

System.out.println(i);

B.Sc[Comp. Sci] Notes By- Sandeep Chavan [RGC]

You might also like