Java Unit 2
Java Unit 2
WITH JAVA
PRESENTATION
MITALI PANCHAL
UNIT 2
DATA TYPES, OPERATORS AND
CONTROL STATEMENT
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Example:
Example:
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.
double d1 = 12.3
PRIMITIVE AND NON-PRIMITIVE DATA TYPES
Char Data Type
• 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.
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.
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.
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.
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.
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.
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.
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.
• 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 {
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.
SYNTAX:
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
• }
• 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.
• 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.
• 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.
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.
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:
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);