0% found this document useful (0 votes)
36 views87 pages

Java Unit 2

The document discusses Java primitive and non-primitive data types. It describes the 8 primitive data types including boolean, byte, char, short, int, long, float, and double. It also explains non-primitive data types such as classes, objects, strings, arrays, and interfaces.
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)
36 views87 pages

Java Unit 2

The document discusses Java primitive and non-primitive data types. It describes the 8 primitive data types including boolean, byte, char, short, int, long, float, and double. It also explains non-primitive data types such as classes, objects, strings, arrays, and interfaces.
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/ 87

PROGRAMMING

WITH JAVA
PRESENTATION
MITALI PANCHAL
UNIT 2
DATA TYPES, OPERATORS AND
CONTROL STATEMENT
PRIMITIVE AND NON-PRIMITIVE DATA TYPES

• Primitive data types: The primitive data types


include boolean, char, byte, short, int, long,
float and double.
• Non-primitive data types: The non-primitive data
types include Classes, Interfaces, and Arrays.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
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.
There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Boolean Data Type
The Boolean data type is used to store only two
possible values: true and false. This data type is
used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of


information.
Example:
Boolean one = false
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Byte Data Type
The byte data type is an example of primitive data type. It
isan 8-bit signed two's complement integer. Its value-range
lies between -128 to 127 (inclusive). Its minimum value is -
128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays


where the memory savings is most required. It saves space
because a byte is 4 times smaller than an integer. It can
also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Short Data Type
The short data type is a 16-bit signed two's complement
integer. 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.
The short data type can also be used to save memory
just like byte data type. A short data type is 2 times
smaller than an integer.

Example:

short s = 10000, short r = -5000


PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Int Data Type
The int data type is a 32-bit signed two's complement integer.
Its value-range lies between - 2,147,483,648 (-2^31) to
2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default
value is 0.
The int data type is generally used as a default data type for
integral values unless if there is no problem about memory.
Example:

int a = 100000, int b = -200000


PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Long Data Type
The long data type is a 64-bit two's complement integer. Its
value-range lies between -9,223,372,036,854,775,808(-2^63)
to 9,223,372,036,854,775,807(2^63 -1)(inclusive).

Its minimum value is - 9,223,372,036,854,775,808and


maximum value is 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 a = 100000L, long b = -200000L


PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Float Data Type
The float data type is a single-precision 32-bit IEEE 754
floating point.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 f1 = 234.5f
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Double Data Type
The double data type is a double-precision 64-bit IEEE 754
floating point. 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 d1 = 12.3
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Char Data Type

The char data type is a single 16-bit Unicode character. Its


value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535
inclusive).The char data type is used to store characters.
Example:

char letterA = 'A'


It is because java uses Unicode system not ASCII code
system. The \u0000 is the lowest range of Unicode system. To
get detail explanation about Unicode visit next page.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Non-primitive data types

Unlike primitive data types, these are not predefined.


These are user-defined data types created by
programmers. These data types are used to store multiple
values.
Whenever a non-primitive data type is defined, it refers a
memory location where the data is stored in heap memory
i.e., it refers to the memory location where an object is
placed. Therefore, a non-primitive data type variable is
also called referenced data type or simply object
reference variable.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Non-primitive data types

In Java programming, all non-primitive data types are


simply called objects that are created by instantiating a
class.
Key points:
• The default value of any reference variable is null.
• Whenever we are passing a non-primitive data type to a
method, we are passing the address of that object
where the data is stored.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Types of Non-primitive data types
There are five types of non-primitive data types in
Java. They are as follows:
• Class
• Object
• String
• Array
• Interface
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Class and objects:
A class in Java is a user defined data type i.e. it is
created by the user. It acts a template to the data
which consists of member variables and methods.

An object is the variable of the class, which can


access the elements of class i.e. methods and
variables.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• public class ClassExample {

• // defining the variables of class
• int a = 20;
• int b = 10;
• int c;

• // defining the methods of class
• public void add () {
• int c = a + b;
• System.out.println("Addition of numbers is: " + c);
• }

• public void sub () {
• int c = a - b;
• System.out.println("Subtraction of numbers is: " + c);
• }
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• // main method
• public static void main (String[] args) {
• // creating the object of class
• ClassExample obj = new ClassExample();

• // calling the methods
• obj.add();
• obj.sub();
• }
• }
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• Interface:
An interface is similar to a class however the only difference
is that its methods are abstract by default.
i.e. they do not have body. An interface has only the final
variables and method declarations. It is also called a fully
abstract class.
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• interface CalcInterface {
• void multiply();
• void divide();
• }
• public class InterfaceExample implements CalcInterface {

• // defining the variables of class
• int a = 10;
• int b = 20;
• int c;

• // implementing the interface methods
• public void multiply() {
• int c = a * b;
• System.out.println("Multiplication of numbers is: " + c);
• }
• public void divide() {
• int c = a / b;
• System.out.println("Division of numbers is: " + c);
• }

PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• // main method
• public static void main (String[] args) throws IOException {
• InterfaceExample obj = new InterfaceExample();
• // calling the methods
• obj.multiply();
• obj.divide();
• }
• }
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• String:
A string represents a sequence of characters for example "Javatpoint",
"Hello world", etc. String is the class of Java.

• String str = "You're the best";

• public class StringExample {


• public static void main(String[] args) {

• // creating a string and initializing it
• String str = "Hello! This is example of String type";

• // applying substring() on above string
• String subStr = str.substring(0,14);

• // printing the string
• System.out.println(subStr);
• }
• }
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
• Array:
An array is a data type which can store multiple homogenous
variables i.e., variables of same type in a sequence. They are stored
in an indexed manner starting with index 0. The variables can be
either primitive or non-primitive data types.

• int [ ] marks;
IDENTIFIERS & LITERALS
Identifiers in Java are symbolic names used for
identification. They can be a class name, variable name,
method name, package name, constant name, and more.

However, In Java, There are some reserved words that can


not be used as an identifier.

• public class HelloJava {


• public static void main(String[] args) {
• System.out.println("Hello JavaTpoint");
• }
• }
IDENTIFIERS & LITERALS
From the above example, we have the following Java
identifiers:
• HelloJava (Class name)
• main (main method)
• String (Predefined Class name)
• args (String variables)
• System (Predefined class)
• out (Variable name)
• println (method)
IDENTIFIERS & LITERALS
Rules for Identifiers:
• A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9],
and underscore(_) or a dollar sign ($). for example, @javatpoint is not
a valid identifier because it contains a special character which is @.
• There should not be any space in an identifier. For example, java
tpoint is an invalid identifier.
• An identifier should not contain a number at the starting. For
example, 123javatpoint is an invalid identifier.
• An identifier should be of length 4-15 letters only. However, there is
no limit on its length. But, it is good to follow the standard
conventions.
• We can't use the Java reserved keywords as an identifier such as int,
float, double, char, etc. For example, int double is an invalid identifier
in Java.
• An identifier should not be any query language keywords such as
SELECT, FROM, COUNT, DELETE, etc.
IDENTIFIERS & LITERALS
Literals
In Java, literals are the constant values that appear directly
in the program. It can be assigned directly to a variable.
IDENTIFIERS & LITERALS
Types of Literals in Java
There are the majorly four types of literals in Java:
• Integer Literal
• Character Literal
• Boolean Literal
• String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of
integer literals:
• Decimal Integer: These are the set of numbers that consist of digits from 0 to 9.
It may have a positive (+) or negative (-) Note that between numbers commas
and non-digit characters are not permitted. For example, 5678, +657, -89, etc.

• int decVal = 26;


IDENTIFIERS & LITERALS
• Octal Integer: It is a combination of number have digits
from 0 to 7 with a leading 0. For example, 045, 026,

• int octVal = 067;


• Hexa-Decimal: The sequence of digits preceded by 0x or
0X is considered as hexadecimal integers. It may also
include a character from a to f or A to F that represents
numbers from 10 to 15, respectively. For example, 0xd,
0xf,

• int hexVal = 0x1a;


IDENTIFIERS & LITERALS
• Binary Integer: Base 2, whose digits consists of the numbers
0 and 1 (you can create binary literals in Java SE 7 and later).
Prefix 0b represents the Binary system. For example,
0b11010.

• int binVal = 0b11010;


Backslash Literals
Java supports some special backslash character literals known
as backslash literals. They are used in formatted output. For
example:
\n: It is used for a new line
\t: It is used for horizontal tab
\b: It is used for blank space
\v: It is used for vertical tab
IDENTIFIERS & LITERALS
• \a: It is used for a small beep
• \r: It is used for carriage return
• \': It is used for a single quote
• \": It is used for double quotes
Character Literals
A character literal is expressed as a character or an escape
sequence, enclosed in a single quote ('') mark. It is always a
type of char. For example, 'a', '%', '\u000d', etc.

String Literals
String literal is a sequence of characters that is enclosed
between double quotes ("") marks. It may be alphabet, numbers,
special characters, blank space, etc. For example, "Jack",
"12345", "\n", etc.
IDENTIFIERS & LITERALS
Boolean Literals
• Boolean literals are the value that is either true or false. It
may also have values 0 and 1. For example, true, 0, etc.

• boolean isEven = true;

Null Literals
Null literal is often used in programs as a marker to indicate
that reference type object is unavailable. The value null may be
assigned to any variable, except variables of primitive types.

• String stuName = null;


• Student age = null;
IDENTIFIERS & LITERALS
Class Literals
Class literal formed by taking a type name and appending .class
extension. For example, Scanner.class. It refers to the object (of
type Class) that represents the type itself.

• class classType = Scanner.class;


DECLARATIONS OF CONSTANTS & VARIABLES
As the name suggests, a constant is an entity in programming
that is immutable. In other words, the value that cannot be
changed. In this section, we will learn about Java constant and
how to declare a constant in Java.

What is constant?
Constant is a value that cannot be changed after assigning it.
Java does not directly support the constants. There is an
alternative way to define the constants in Java by using the non-
access modifiers static and final.

In Java, to declare any variable as constant, we use static and


final modifiers. It is also known as non-access modifiers.
According to the Java naming convention the identifier name
must be in capital letters.
DECLARATIONS OF CONSTANTS & VARIABLES
Static and Final Modifiers

• The purpose to use the static modifier is to manage the


memory.
• It also allows the variable to be available without loading any
instance of the class in which it is defined.
• The final modifier represents that the value of the variable
cannot be changed. It also makes the primitive data type
immutable or unchangeable.

static final datatype identifier_name=value;


• static final double PRICE=432.78;
DECLARATIONS OF CONSTANTS & VARIABLES
• Write the identifier name in capital letters that we want to
declare as constant. For example, MAX=12.
• If we use the private access-specifier before the constant
name, the value of the constant cannot be changed in that
particular class.
• If we use the public access-specifier before the constant
name, the value of the constant can be changed in the
program.
DECLARATIONS OF CONSTANTS & VARIABLES
• import java.util.Scanner;
• public class ConstantExample1
• {
• //declaring constant
• private static final double PRICE=234.90;
• public static void main(String[] args)
• {
• int unit;
• double total_bill;
• System.out.print("Enter the number of units you have used: ");
• Scanner sc=new Scanner(System.in);
• unit=sc.nextInt();
• total_bill=PRICE*unit;
• System.out.println("The total amount you have to deposit is:
"+total_bill);
• }
• }
DECLARATIONS OF CONSTANTS & VARIABLES
• import java.util.Scanner;
• public class ConstantExample1
• {
• //declaring constant
• private static final double PRICE=234.90;
• public static void main(String[] args)
• {
• int unit;
• double total_bill;
• System.out.print("Enter the number of units you have used: ");
• Scanner sc=new Scanner(System.in);
• unit=sc.nextInt();
• total_bill=PRICE*unit;
• System.out.println("The total amount you have to deposit is:
"+total_bill);
• }
• }
DECLARATIONS OF CONSTANTS & VARIABLES
• public class ConstantExample3
• {
• //declaring PI as constant
• public static final double PI= 3.14;
• public static void main(String[] args)
• {
• printValue();
• //trying to assign 3.15 in the constant PI
• PI = 3.15;
• printValue();
• }
• void printValue()
• {
• System.out.print("The value of PI cannot be changed to " + PI);
• }
• }
DECLARATIONS OF CONSTANTS & VARIABLES
• Using Enumeration (Enum) as Constant
• It is the same as the final variables.
• It is a list of constants.
• Java provides the enum keyword to define the enumeration.
• It defines a class type by making enumeration in the class that may
contain instance variables, methods, and constructors.

• public class EnumExample


• {
• //defining the enum
• public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray}
• public static void main(String[] args)
• {
• //traversing the enum
• for (Color c : Color.values())
• System.out.println(c);
• }
• }
VARIABLE
Variable:
• A variable is the name of a reserved area allocated in memory. In
other words, it is a name of the memory location. It is a
combination of "vary + able" which means its value can be
changed.
• int data=50;//Here data is variable
• There are three types of variables in Java:
• local variable
• instance variable
• static variable
TYPES OF VARIABLE
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.

Instance Variable
• A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.
• It is called an instance variable because its value is instance-
specific and is not shared among instances.

Static variable
• A variable that is declared as static is called a static variable. It
cannot be local. You can create a single copy of the static variable
and share it among all the instances of the class.
EXAMPLE
• public class A
• {
• static int m=100;//static variable
• void method()
• {
• int n=90;//local variable
• }
• public static void main(String args[])
• {
• int data=50;//instance variable
• }
• }//end of class
EXAMPLE: ADD TWO NUMBERS
• public class Simple{
• public static void main(String[] args){
• int a=10;
• int b=10;
• int c=a+b;
• System.out.println(c);
• }
• }
TYPE CONVERSION AND CASTING
Type conversion in Java is the process of converting one data
type to another. It is important when performing operations that
involve data of different types, as Java requires operands of the
same type to perform most operations.

Types of Type Conversion


• Widening Type Conversion
• Narrowing Type Conversion

Widening Type Conversion


• It is the process of converting a value of one data type to another data type.
Widening type conversion also known as an implicit conversion occurs when a
value of a smaller data type is assigned to a variable of a larger data type.
TYPE CONVERSION AND CASTING

Syntax of Widening Type Conversion:


largerDataType variableName = smallerDataTypeVariable;

EXAMPLE
public class Main {
public static void main(String[] args) {
int a = 5;
float b = 3.5f;
float sum = a + b; // Widening type conversion from int to float
System.out.println("The value of a is: " + a);
System.out.println("The value of b is: " + b);
System.out.println("The sum of a and b is: " + sum);
}
TYPE CONVERSION AND CASTING
Narrowing Type Conversion
It is also known as an explicit conversion that occurs when a value of a larger data
type is assigned to a variable of a smaller data type.

Syntax of Narrowing Type Conversion:


(target_type) value

Example of Narrowing Type Conversion:


public class Main {
public static void main(String[] args) {
float a = 5.7f;
int b = (int) a; // Narrowing type conversion from float to int
System.out.println("The value of a is: " + a);
System.out.println("The value of b is: " + b);
}
}
CREATION, CONCATENATION AND CONVERSION
OF A STRING
The Java String class concat() method combines specified string at the end of this string. It returns a
combined string. It is like appending another string.

SYNTAX: public String concat(String anotherString)

• public class ConcatExample{


• public static void main(String args[]){
• String s1="java string";
• // The string s1 does not get changed, even though it is invoking the method
• // concat(), as it is immutable. Therefore, the explicit assignment is required here.
• s1.concat("is immutable");
• System.out.println(s1);
• s1=s1.concat(" is immutable so assign it explicitly");
• System.out.println(s1);
• }}
CHANGING CASE OF STRING
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}

Output
HELLO WORLD
hello world
CHARACTER EXTRACTION
charAt()
charAt() method is used to extract a single character at an index. It has following syntax.

Syntax
char charAt(int index)

Example: Output: l
class temp
{
public static void main(String...s)
{
String str="Hello";
char ch=str.charAt(2);
System.out.println(ch);
}
}
STRING COMPARISON
It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare String in Java:

• By Using equals() Method


The String class equals() method compares the original content of the string. It compares values of
string for equality.

• class Teststringcomparison1{
• public static void main(String args[]){
• String s1="Sachin";
• String s2="Sachin"; Output: true,true,false
• String s3=new String("Sachin");
• String s4="Saurav";
• System.out.println(s1.equals(s2));//true
• System.out.println(s1.equals(s3));//true
• System.out.println(s1.equals(s4));//false
• }
• }
STRING COMPARISON
• By Using == Operator
The == operator compares references not values.

• By compareTo() Method
The String class compareTo() method compares values lexicographically and returns an integer value
that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two String objects. If:
• s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
STRING BUFFER
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class
in Java is the same as String class except it is mutable i.e. it can be changed.

ConstructorDescription
StringBuffer()
It creates an empty String buffer with the initial capacity of 16.

StringBuffer(String str)
It creates a String buffer with the specified string..

StringBuffer(int capacity)
It creates an empty String buffer with the specified capacity as length.
STRING BUFFER
Important methods of String Buffer class
capacity()
It is used to return the current capacity.

class Main {
public static void main(String args[])
{
StringBuffer str = new StringBuffer(); output: 16
System.out.println( str.capacity() );
}
}

charAt(int index)
It is used to return the character at the specified position.
STRING BUFFER
insert(int offset, String s)
It is used to insert the specified string with this string at the specified position.

class Main {
public static void main(String args[])
{
StringBuffer str = new StringBuffer("Bytes ");
str.insert(1, "Java");
// Now original string is changed
System.out.println(str);
}

output:’
BJavaytes
STRING BUFFER
append(String s)
It is used to append the specified string with this string.
class Main {
public static void main(String args[])
{
StringBuffer str = new StringBuffer("Prep "); Output: PrepBytes
str.append("Bytes"); // now original string is changed
System.out.println(str); }}

reverse()
is used to reverse the string.

class Main {
public static void main(String args[])
{
StringBuffer str = new StringBuffer("PrepBytes"); output: setyBperP
str.reverse();
System.out.println(str);
}
}
WRAPPER CLASSES
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.

Java supports only call by value. So, if we pass a primitive value, it will not change the
original value. But, if we convert the primitive value in an object, it will change the original
value.
WRAPPER CLASSES
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known
as unboxing. It is the reverse process of autoboxing.

Comment Syntax:
• Single Line Comment
• Multi Line Comment
• Documentation Comment
DIFFERENT OPERATORS: ARITHMETIC
PUBLIC CLASS TEST {

PUBLIC STATIC VOID MAIN(STRING ARGS[])


{
INT A = 10;
INT B = 20;

SYSTEM.OUT.PRINTLN("A + B = " + (A + B) );
SYSTEM.OUT.PRINTLN("A - B = " + (A - B) );
SYSTEM.OUT.PRINTLN("A * B = " + (A * B) );
SYSTEM.OUT.PRINTLN("B / A = " + (B / A) );
}
}
DIFFERENT OPERATORS: BITWISE
DIFFERENT OPERATORS:RATIONAL
DIFFERENT OPERATORS:LOGICAL
DIFFERENT OPERATORS:ASSIGNMENT
DIFFERENT OPERATORS:CONDITIONAL
LOGICAL AND (&&): THIS OPERATOR RETURNS TRUE IF BOTH CONDITIONS ON
THE LEFT AND RIGHT SIDE OF THE OPERATOR ARE TRUE.

LOGICAL OR (||): THIS OPERATOR RETURNS TRUE IF AT LEAST ONE OF THE


CONDITIONS ON THE LEFT OR RIGHT SIDE OF THE OPERATOR IS TRUE.

LOGICAL NOT (!): THIS OPERATOR NEGATES THE RESULT OF A CONDITION. IF


THE CONDITION IS TRUE, THE OPERATOR RETURNS FALSE, AND VICE VERSA.
DIFFERENT OPERATORS:TERNARY
JAVA, THE TERNARY OPERATOR IS A TYPE OF JAVA CONDITIONAL
OPERATOR.

SYNTAX:

• VARIABLE = (CONDITION) ? EXPRESSION1 : EXPRESSION2

INCREMENT:
THE INCREMENT (++) OPERATOR (ALSO KNOWN AS INCREMENT UNARY
OPERATOR) IN JAVA IS USED TO INCREASE THE VALUE OF A VARIABLE BY 1.
SINCE IT IS A TYPE OF A UNARY OPERATOR, IT CAN BE USED WITH A SINGLE
OPERAND.

SYNTAX:
++X;
X++;
DIFFERENT OPERATORS:
DECREMENT:
DECREMENT AS THE NAME IMPLIES IS USED TO REDUCE THE VALUE OF A
VARIABLE BY 1. IT IS ALSO ONE OF THE UNARY OPERATOR TYPES, SO IT CAN
BE USED WITH A SINGLE OPERAND.

SYNTAX:
--X;
X--;
SELECTION STATEMENT (IF, IF...ELSE,switch)
IF STATEMENT:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition.

Syntax
• if(condition) {
• statement 1; //executes when condition is true
• }

• public class Student {


• public static void main(String[] args) {
• int x = 10; Output: x + y is greater than 20

• int y = 12;
• if(x+y > 20) {
• System.out.println("x + y is greater than 20");
• }
• }
• }
SELECTION STATEMENT (IF, IF...ELSE,switch)
if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block.

Syntax:

• if(condition) {
• statement 1; //executes when condition is true
• }
• else{
• statement 2; //executes when condition is false
• }
SELECTION STATEMENT (IF, IF...ELSE,switch)
• public class Student {
• public static void main(String[] args) {
• int x = 10;
• int y = 12;
• if(x+y < 10) {
• System.out.println("x + y is less than 10");
• } else {
• System.out.println("x + y is greater than 20");
• }
• }
• }

Output:
x + y is greater than 20
SELECTION STATEMENT (IF, IF...ELSE,switch)
• if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true.

Syntax of if-else-if statement is given below.

• if(condition 1) {
• statement 1; //executes when condition 1 is true
• }
• else if(condition 2) {
• statement 2; //executes when condition 2 is true
• }
• else {
• statement 2; //executes when all the conditions are false
• }
SELECTION STATEMENT (IF, IF...ELSE,switch)
• public class Student {
• public static void main(String[] args) {
• String city = "Delhi";
• if(city == "Meerut") {
• System.out.println("city is meerut");
• }else if (city == "Noida") {
• System.out.println("city is noida");
• }else if(city == "Agra") {
• System.out.println("city is agra");
• }else {
• System.out.println(city);
• }
• }
• }

Output:
Delhi
SELECTION STATEMENT (IF, IF...ELSE,switch)
• Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.

Syntax of Nested if-statement

• if(condition 1) {
• statement 1; //executes when condition 1 is true
• if(condition 2) {
• statement 2; //executes when condition 2 is true
• }
• else{
• statement 2; //executes when condition 2 is false
• }
• }
SELECTION STATEMENT (IF, IF...ELSE,switch)
• public class Student {
• public static void main(String[] args) {
• String address = "Delhi, India";

• if(address.endsWith("India")) {
• if(address.contains("Meerut")) {
• System.out.println("Your city is Meerut");
• }else if(address.contains("Noida")) {
• System.out.println("Your city is Noida");
• }else {
• System.out.println(address.split(",")[0]);
• }
• }else {
• System.out.println("You are not living in India");
• }
• }
• }
Output:Delhi
SELECTION STATEMENT (IF, IF...ELSE,switch)
• Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched.

The syntax to use the switch statement is given below.


• switch (expression){
• case value1:
• statement1;
• break;
• .
• .
• .
• case valueN:
• statementN;
• break;
• default:
• default statement;
• }
SELECTION STATEMENT (IF, IF...ELSE,switch)
• public class Student implements Cloneable {
• public static void main(String[] args) {
• int num = 2;
• switch (num){
• case 0:
• System.out.println("number is 0");
• break;
• case 1:
• System.out.println("number is 1");
• break;
• default:
• System.out.println(num);
• }
• }
• }

Output:
2
LOOPS (WHILE, DO-WHILE, FOR)
• Java 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.

Syntax:

• while (condition){
• //code to be executed
• I ncrement / decrement statement
• }
LOOPS (WHILE, DO-WHILE, FOR)
• 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
LOOPS (WHILE, DO-WHILE, FOR)
• Java 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.

Syntax:

• do{
• //code to be executed / loop body
• //update statement
• }while (condition);
LOOPS (WHILE, DO-WHILE, FOR)
• 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
LOOPS (WHILE, DO-WHILE, FOR)
For Loop:

The for statement consumes the initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.

Syntax:

for (initialization expr; test expr; update exp)


{
// body of the loop
// statements we want to execute
}

Initialization Expression
In this expression, we have to initialize the loop counter to some value.

Example:
int i=1;
LOOPS (WHILE, DO-WHILE, FOR)
Test Expression

In this expression, we have to test the condition. If the condition evaluates to true then, we will
execute the body of the loop and go to the update expression. Otherwise, we will exit from the for a
loop.

Example:

i <= 10

Update Expression:

After executing the loop body, this expression increments/decrements the loop variable by some
value.

Example:
i++;
LOOPS (WHILE, DO-WHILE, FOR)
• 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);
• }
• }
• }
Output:
1
2
3
4
5
6
7
8
9
10
JUMP STATEMENTS (BREAK, CONTINUE)
• Break statement

In java, the break statement is used to terminate the execution of the nearest looping statement or
switch statement. The break statement is widely used with the switch statement, for loop, while loop,
do-while loop.

Syntax:
break; Output:

class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
System.out.println(i);
}
}
}
JUMP STATEMENTS (BREAK, CONTINUE)
• Continue Statement
The continue statement pushes the next repetition of the loop to take place, hopping any code
between itself and the conditional expression that controls the loop.

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
System.out.println();
// using continue keyword
// to skip the current iteration
continue;
}
System.out.println(i);
}
}
}
JUMP STATEMENTS (BREAK, CONTINUE)
• Return Statement
The “return” keyword can help you transfer control from one method to the method that called it.
Since the control jumps from one part of the program to another, the return is also a jump statement.

lass ReturnExample {
// A simple method that takes two integers as input and
// returns their sum
public static int calculateSum(int num1, int num2)
{
// Print a message indicating the method has started
System.out.println("Calculating the sum of " + num1
+ " and " + num2);
int sum = num1 + num2;
System.out.println("The sum is: " + sum);

// Return the calculated sum


return sum;
JUMP STATEMENTS (BREAK, CONTINUE)
• // Note: Any code after the 'return' statement will
• // not be executed. But "Final" is an exception in
• // the case of try-catch-final block.
• // System.out.println("end"); // error : unreachable
• // statement
• }
• public static void main(String[] args)
• {
• // Call the calculateSum method
• int result = calculateSum(5, 10);

• // Print the result
• System.out.println("Result: " + result);
• }
• }

You might also like