Nothing Special   »   [go: up one dir, main page]

Corejava Slides

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 137

Basic Program on Java

public class MyFirstClass {


public static void main(String[] args) {
System.out.println("Hello world");
}
}
Program code of datatype
package Second;
public class Second {
public static void main(String[] args) {
int x;
x=3;
double y = 5.5;
System.out.println("x is "+x);
System.out.println("y is "+y);
}
}
Operators & Operator Precedence
Code Snippet for operators
public class Third {
public static void main(String[] args) {
int a = 5;
int b = 3;
int c = 4;
int sum = a + b * c;
System.out.println("sum is "+sum);
}
}
What is a Class ?
It is a template or blueprint from which objects are created.
It is a logical entity. It can’t be physical.
A class in Java can contain:
Fields (variables)
methods
constructors
blocks
nested class and interface
What is n Object ?
An entity that has state and behavior is known as an object.
An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• identity: Object identity is typically implemented via a unique ID.
• The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Relation Between Class and Object –
Object is an instance of a class.
Class is a template or blueprint from which objects are created.
So object is the instance(result) of a class.
In another way, we can say that objects are variables of type class
Some Important Concepts that come along with Classes and Objects are –
• Instance variables
• Methods
• new keyword
Instance variable in Java
A variable which is created inside the class but outside the method, is known as instance variable.
Instance variable doesn’t get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword in Java
The new keyword is used to allocate memory at run time. All objects get memory in Heap memory
area.
package mystudentexample;
class Student{
int id; // instance variables
String name; // instance variables
}
public class MyStudentExample {
public static void main(String[] args) {
Student object1 = new Student();
Student obj2;
obj2 = new Student();
obj2.id = 2;
obj2.name = "Simple Snippets";
object1.id = 1;
object1.name = “Srikanth";
System.out.println(object1.id);
System.out.println(object1.name);
System.out.println(obj2.id);
System.out.println(obj2.name);
}
}
Java Methods
User-defined Methods
Types of Methods public class FunctionExample {
• Standard Library Methods
• User-defined Methods public int max(int x, int y)
{
if(x>y){
return x;
Standard Library Methods }
else {
public class Numbers { return y;
public static void main(String[] args) { }
}
System.out.print("Hello World");
public static void main(String[] args) {
} // TODO code application logic here
} FunctionExample obj = new FunctionExample();
int num = obj.max(5, 6); // FUNCTION CALL
System.out.println("Max value is: "+num);
}

}
Java Constructors Explained

A constructor is a special method in Java. It is called when an instance of object is created and
memory is allocated for the object. It is called constructor because it constructs the values at the time
of object creation.
Default Constructor
A constructor that has no parameter is known as default constructor. If we don’t define a constructor
in a class, then compiler creates default constructor(with no arguments) for the class.
Default constructor example
public class MyClass {
int number;
public MyClass() {
System.out.println("Constructor Called");
number=5;
}
public static void main(String[] args) {

MyClass obj = new MyClass(); // Constructor Called


System.out.println("Number value is: "+obj.number);
}
}
Parameterized Constructor
public class MyClass {
int number;
public MyClass(int x) {
System.out.println("Parameterized Constructor Called");
number=x;
}

public static void main(String[] args) {

MyClass obj = new MyClass(4); // Parameterized Constructor Called


System.out.println("Number value is: "+obj.number);
}
}
Constructor Overloading void displayData()
public class MyClass { {
int num1;
System.out.println("Num1: "+num1+"\nNum2:
double num2;
"+num2);
//Default Constructor
public MyClass()
}
{ public static void main(String[] args) {
System.out.println("Default Constructor Called");
num1=1; MyClass obj1 = new MyClass(); // Default
num2=1.5; Constructor Called
} obj1.displayData();
//Parameterized Constructor 1 MyClass obj2 = new MyClass(5); //
public MyClass(int x) {
Parameterized Constructor 1 Called
System.out.println("Parameterized Constructor 1 Called");
obj2.displayData();
num1=x;
}
MyClass obj3 = new MyClass(5,5.5); //
//Parameterized Constructor 2
Parameterized Constructor 2 Called
public MyClass(int x, double z) { obj3.displayData();
System.out.println("Parameterized Constructor 2 Called"); }
num1=x; }
num2=z;
}
Simple Java Program for Practice
1. Swap of two numbers
Public class swap{
public static void main(String[] args)
{
int first = 5, second = 10;
System.out.println("--Before swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
// Value of first is assigned to temporary
int temporary = first;
// Value of second is assigned to first
first = second;
// Value of temporary (which contains the initial value of first) is assigned to second
second = temporary;
System.out.println("--After swap--");
System.out.println("First number = " + first);
System.out.println("Second number = " + second);
}}
2. Number is positive or negative
public static void main(String[] args)
{
double number = 12;
if (number < 0.0)
{
System.out.println(number + " is a negative
number.");
}
else if ( number > 0.0)
{
System.out.println(number + " is a positive
number.");
}
else
{
System.out.println(number + " is 0.");
}
}
Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. Using recursive algorithm, certain problems can be solved quite easily.
Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A method in java that calls itself is called
recursive method.
public class FactorialExample {
static int fact(int n)
{
if(n!=1)
{
return n*(fact(n-1));
}
else
{
return 1;
}
}
public static void main(String[] args)
{
System.out.println("Factorial of 4 is: "+fact(4));
}
}
Method Overloading
Method overloading in Java is a feature which makes it possible to use the same method name to
perform different tasks.
public static void main(String[] args)
{
public class Methodoverloading
int a=5;
{ double b = 7.5;
double add(int x, double y) float c = 4.5f;
{ double result;
return(x+y); Methodoverloading obj = new Methodoverloading();
} result = obj.add(a, b);
double add(double x, int y) System.out.println("Addtion is: "+result);
{ result = obj.add(b, a);
return(x+y); System.out.println("Addtion is: "+result);
} result = obj.add(b,a,c);
double add(double x, int y, float z) System.out.println("Addtion is: "+result);
{ }
return(x+y+z); }
} Output:
Addition is: 12.5
Addition is: 12.5
Addition is: 17.0
static keyword
The static keyword in java is used primarily for memory management.
Static keyword can be used with class, variable, method and blocks.
The static keyword belongs to the class than instance of the class i.e if
you make a member static, you can access it without object.
The static can be:
• variable (also known as class variable)
• method (also known as class method)
• block
• nested class
1. static Variable
public class Cube public static void main(String[] args)
{ {
Cube c1=new Cube();
int side;
Cube c2=new Cube(5);
static int objectCount=0;
Cube c3=new Cube(8);
Cube()
Cube c4=new Cube(10);
{ Cube c5=new Cube(11);
objectCount++; System.out.println("Number of Cube
} Objects: "+objectCount);
Cube(int x) }
{ }
side=x; Output: 05
objectCount++;
}
2. static Method
Main Use: Object creation isn’t required, we can
directly access static method from main function
public class Cube
{
static int calculateCube(int side)
{
return (side*side*side);
}
public static void main(String[] args)
{
//System.out.println("Cube value of 5 is: "+calculateCube(5));
System.out.println("Cube value of 5 is: "+Cube.calculateCube(5));
}
}
NOTE:
Why java main method is static?
The main reason why java main() method is made static is because object is not required to call static method.
If it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.
3. static Blocks in Java Output:
So in general static block – static block is invoked
• Is used to initialize the static data member. Cube value of 5 is: 125
• It is executed before main method at the time of classloading.
public class Cube {
static
{
System.out.println("static block is invoked");
}
static int calculateCube(int side)
{
return (side*side*side);
}
public static void main(String[] args) {
//System.out.println("Cube value of 5 is: "+calculateCube(5));
System.out.println("Cube value of 5 is: "+Cube.calculateCube(5));
}
}
4. static class psvm()
static class in Java {
A class can be made static only if it is a nested class. One obj1 = new One();
1. Nested static class doesn’t need reference of Outer class obj1.disp();
2. A static class cannot access non-static members of the Outer class One.Two obj2 = new One.Two();
Syntax
obj2.disp();
}
class One
}
{
class Two
{
disp(){

}
}
}
CODE: static Class in Java
class JavaExample
{
private static String str = "TNS Java Sessions";
static class MyNestedClass
{
public void disp()
{
System.out.println(str);
}
}
public static void main(String args[])
{
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
Arrays in Java with Program Examples
Arrays in Java are a group of like-typed variables that are referred to by a common name.
Array is a collection of similar type of elements that have contiguous memory location.
• Arrays in Java are Objects.
• In Java all arrays are dynamically allocated.(discussed below)
• Java array can be also be used as a static field, a local variable or a method parameter.
• The size of an array must be specified by an int value and not long or short.
• In case of primitives data types, the actual values are stored in contiguous memory locations.
• In case of objects of a class, the actual objects are stored in heap segment.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single Dimensional Arrays
Creating, Initializing, and Accessing an Array
The general form of a one-dimensional array declaration is

type var-name[];
OR
type[] var-name;
Instantiating an Array in Java
int intArray[]; //declaring array int[] intArray = new int[20]; // combining both statements in one
intArray = new int[20]; // allocating memory to 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;

//printing array
for (int i = 0; i < a.length; i++) //length is the property of array
System.out.println(a[i]);

}
}
Arrays of Objects
An array of objects is created just like an array of primitive type data items in the following way.
class Student // Elements of array are objects of a class // so on...
{ Student. arr[2] = new
public class GFG Student(3,"shikar");
public int roll_no;
{ arr[3] = new
public String name; public static void main (String[] args) Student(4,"dharmesh");
Student(int roll_no, String name) { arr[4] = new
{
// declares an Array of integers. Student(5,"mohit");
Student[] arr;
this.roll_no = roll_no; // accessing the elements of
this.name = name; // allocating memory for 5 objects of type the specified array
} Student. for (int i = 0; i < arr.length; i++)
arr = new Student[5]; System.out.println("Element
}
at " + i + " : " +
// initialize the first elements of the array arr[i].roll_no +" "+
arr[0] = new Student(1,"aman"); arr[i].name);
}
// initialize the second elements of the }
array
arr[1] = new Student(2,"vaibhav");
Java Multi Dimensional Arrays
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
2-D Array in Java Example Program
class multiDimensional
{
public static void main(String args[])
{
int arr[][] = { {2,7,9},{3,6,1},{7,4,2} };
for (int i=0; i< 3 ; i++)
{
for (int j=0; j < 3 ; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Jagged array in java is array of arrays such that member arrays can be of different sizes, i.e., we can create a 2-D
arrays but with variable number of columns in each row. These type of arrays are also known as Jagged arrays.
// Program to demonstrate 2-D jagged array in Java
class Main
// Displaying the values of 2D Jagged array
{ System.out.println("Contents of 2D
public static void main(String[] args) Jagged Array");
{ for (int i=0; i<arr.length; i++)
// Declaring 2-D array with 2 rows {
int arr[][] = new int[2][];
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
// Making the above array Jagged
System.out.println();
// First row has 3 columns }
arr[0] = new int[3]; }
// Second row has 2 columns }
arr[1] = new int[2];
// Initializing array Contents of 2D Jagged Array
int count = 0; 012
for (int i=0; i<arr.length; i++) 34
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
Java Single Inheritance Program Example –
class Animal class TestInheritance
{ {
void eat() public static void main(String args[])
{
{
Dog d=new Dog();
System.out.println("eating...");
d.bark();
}
d.eat();
} }
class Dog extends Animal }
{
void bark()
{
System.out.println("barking...");
}
}
Single Level Inheritence – Program 2
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Java Multilevel Inheritance Program Example –
class Animal {
class TestInheritance2 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); BabyDog d = new BabyDog();
} d.weep();
} d.bark();
d.eat();
class Dog extends Animal {
}
void bark() {
}
System.out.println("barking...");
}
}
class BabyDog extends Dog {
void weep() {
System.out.println("weeping...");
}
}
Multilevel Inheritence – Example2 Class SubClass2 extends SubClass1
{
Class SuperClass public void methodC()
{ {
public void methodA()
System.out.println("SubClass2");
}
{
public static void main(String args[])
System.out.println("SuperClass"); {
} SubClass2 obj = new SubClass2();
} SubClass2.methodA(); //calling super class
Class SubClass1 extends SuperClass method
{
SubClass2.methodB(); //calling subclass 1
method
public void methodB()
SubClass2.methodC(); //calling own method
{
}
System.out.println("SubClass1 "); }
}
}
Java Hierarchial Inheritance Program Example –
class Animal { class TestInheritance3 {
void eat() { public static void main(String args[]) {
System.out.println("eating..."); Cat c = new Cat();
}
c.meow();
c.eat();
}
//c.bark();//C.T.Error
class Dog extends Animal { }
void bark() { }
System.out.println("barking...");
}
}
class Cat extends Animal {
void meow() {
System.out.println("meowing...");
}
}
Java Hierarchial Inheritance Program Example –2
Class A Class C extends A
{
{
public void methodC()
public void methodA() {
{ System.out.println("Sub class Method C");
System.out.println("Super class method"); }
}
public static void main(String args[])
{
}
A obj1 = new A();
Class B extends A B obj2 = new B();
{ C obj3 = new C();
public void methodB() obj1.methodA(); //calling super class method
obj2.methodA(); //calling A method from subclass
{
object
System.out.println("Sub class Method B"); obj3.methodA(); //calling A method from subclass
} object
} }
}
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A
and B classes have same method and you call it from child class object, there will be ambiguity to
call method of A or B class.
In C++ we have virtual keyword to tackle this ambiguity however, in Java Multiple Inheritance is
possible only via Interfaces.
Java Even Odd Program Code Example –
class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Java Largest of Three Numbers Program Code Example –
import java.util.Scanner;

class LargestOfThreeNumbers

public static void main(String args[])

int x, y, z;

System.out.println("Enter three integers ");

Scanner in = new Scanner(System.in);

x = in.nextInt();

y = in.nextInt();

z = in.nextInt();

if ( x > y && x > z )

System.out.println("First number is largest.");

else if ( y > x && y > z )

System.out.println("Second number is largest.");

else if ( z > x && z > y )

System.out.println("Third number is largest.");

else

System.out.println("Entered numbers are not distinct.");

}
Swapping of 2 Variables using 3rd Variable in C++
#include <iostream>
using namespace std;

int main() {
int a,b,c;
cout<<"Enter value of a: ";
cin>>a;
cout<<"Enter value of b: ";
cin>>b;
cout<<"Before Swapping: a: "<<a<<" b: "<<b<<endl;
// start: swapping logic
c=a;
a=b;
b=c;
// end: swapping logic
cout<<"After Swapping: a: "<<a<<" b: "<<b<<endl;
return 0;
}
Swapping of 2 Variables Without using 3rd Variable in C++
#include <iostream>
using namespace std;

int main() {
int a,b;

cout<<"Enter value of a: ";


cin>>a;
cout<<"Enter value of b: ";
cin>>b;
a=a+b;
b=a-b;
a=a-b;
cout<<"After swap a: "<<a<<" b: "<<b;
return 0;
}
Java program to check LEAP year
public class JavaApplication4 {
public static void main(String[] args) {
int year = 2020;
if(year%400==0)
{
System.out.println("Leap Year");
}
else if(year%4==0 && year%100!=0)
{
System.out.println("Leap Year");
}
else
{
System.out.println("Not a Leap Year");
}
}
}
Java program to Find Factorial of a Number
public class JavaApplication4 {
public static void main(String[] args) {

int num = 4;
int factorial =1;
for(int i = num; i>0; i--)
{
factorial = factorial *i;
}
System.out.println("Factorial is: "+factorial);

}
}
Java program to Find if a Number is PALINDROME or not –

package javaapplication4;

public class JavaApplication4 {

public static void main(String[] args) {

int num=121;

int temp=num;

int rev = 0;

while(num>0)

rev = rev*10;

rev = rev + num%10;

num = num/10;

if(temp == rev)

System.out.println("Palindrome");

else

System.out.println("Not Palindrome");

}
Java Program to Print FIBONACCI Series using FOR LOOP
// 0 + 1 + 1 + 2 + 3 + 5 + 8 +

package javaapplication4;
public class JavaApplication4 {
public static void main(String[] args) {
int a = 0;
int b = 1;
int c;
for(int i = 0; i<5 ; i++)
{
System.out.print(a+" ");
c = a+b;
a=b;
b=c;
}

}
}
Polymorphism in Java – Method Overloading | Method Overriding
• Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many and “morphs” means forms.
So Polymorphism means the ability to take many forms.
• Polymorphism is a concept by which we can perform a single task in different ways.

• Compile Time Polymorphism – Method Overloading


• Run Time Polymorophism – Method Overriding
Run Time Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at
runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. Thus this happens only when
Inheritance is implemented.
The method to be called is based on the object being referred to by the reference variable.
Some Rules to follow in Method Overriding –
• Overriding and Access-Modifiers : The access modifier for an overriding method can allow more, but not less, access than
the overridden method. For example, a protected instance method in the super-class can be made public, but not private, in
the subclass.
• Final methods can not be overridden.
• Static methods can not be overridden(Method Overriding vs Method Hiding).
• Private methods can not be overridden.
• The overriding method must have same return type (or subtype)
• Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword.
// A Simple Java program to demonstrate // Driver class
// method overriding in java class Main
// Base Class {
public static void main(String[] args)
class Parent
{
{ // If a Parent type reference refers
void show() { System.out.println("Parent's show()"); } // to a Parent object, then Parent's
}
// show is called
Parent obj1 = new Parent();
// Inherited class obj1.show();
class Child extends Parent
{ // If a Parent type reference refers
// to a Child object Child's show()
// This method overrides show() of Parent
// is called. This is called RUN TIME
@Override // POLYMORPHISM.
void show() { System.out.println("Child's show()"); } Parent obj2 = new Child();
} obj2.show();
}
}
Packages in Java
• Package in java as the name suggests is a pack(group) of classes, interfaces and other packages.
• Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

Packages are used for:


• Preventing naming conflicts. For example there can be two classes with name Teacher in two
packages, college.staff.icse.Teacher and college.staff.cbse.Teacher
• Making searching/locating and usage of classes, interfaces, enumerations and annotations easier.
• Providing access control: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member
(without any access specifier) is accessible by classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).
Package in java can be categorized in two form,
• built-in package
• user-defined package.
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?
import package.*;
import package.classname;
1) Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
• The import keyword is used to make the classes and interface of another package accessible to the
current package.
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Packages Example Step 2: import pack.*;
Step1 : package pack; import Subpackage.*;
public class A{ class B{
public void msg(){System.out.println("Hello");} public static void main(String args[]){
A obj = new A();
}
C obj1 = new C();
Step 1.1 package pack; D obj2 = new D();
public class C { obj.msg();
public void msg() obj1.msg();
{ obj2.msg();
System.out.println("Hello C"); }
}
}
}
Step 1.3 package Subpackage;

public class D {

public void msg()


{System.out.println("Hello D");}
}
Access Modifiers in Java
Access modifiers in java specify the scope of a class, constructor ,
variable , method or data
member. There are four types of access modifiers available in java:
• Private - The private access modifier is accessible only within class
• Default – No keyword required - accessible only within package.
• Protected - is accessible within package and outside the package but
through inheritance only
• Public - The public access modifier is accessible everywhere
Private Access Modifier
The private access modifier is accessible only within class. The private access modifier is
specified using the keyword private.
• The methods or data members declared as private are accessible only within the
class in which they are declared.
• Any other class of same package will not be able to access these members.
• Classes or interface can not be declared as private.
package p1; class B Output
class A { error: display() has private access in A
{ public static void main(String args[]) obj.display();
private void display() {
A obj = new A();
{
//trying to access private method of
System.out.println("TNS Sessions");
another class
} obj.display();
} }
}
Default Access Modifier
If you don’t use any modifier, it is treated as default by default. The default modifier is accessible
only within package.
• The data members, class or methods which are not declared using any access modifiers
i.e. having default access modifier are accessible only within the same package.

package p1; package p2;


//Class MyClass1 is having Default import p1.*;
access modifier //This class is having default access modifier
class MyClass1 class MyClass2
{ {
void display() public static void main(String args[])
{ {
System.out.println("Hello World!"); //accessing class MyClass1 from package p1
} MyClass1 obj = new MyClass1();
} obj.display();
}
}
Output
Compile time error
Protected Access Modifier
The protected access modifier is specified using the keyword protected.
• The protected access modifier is accessible within package and outside the package but through inheritance only.
• The protected access modifier can be applied on the data member, method and constructor.
• It can’t be applied on the class.

package p1; package p2;


import p1.*;
public class A public class B extends A
{ {
protected void display() public static void main(String[] args)
{
{ B obj = new B();
System.out.println("TNS obj.display();
Sessions"); }
}
} Output: TNS Sessions
}
Public Access Modifier
The public access modifier is specified using the keyword public.
• The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
• Classes, methods or data members which are declared as public are accessible from every where in
the program. There is no restriction on the scope of a public data members.

package p1; package p2;


public class A import p1.*;
class B
{ {
public void display() public static void main(String[] args)
{ {
System.out.println("TNS Sessions"); A obj = new A();
obj.display();
} }
} }
Output: TNS Sessions
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context.
Final can be:
1. variable
2. method
3. class
Final is a non-access modifier applicable only to a variable, a method or a class.
Basically final keyword is used to perform 3 tasks as follows –
1. To create constant variables
2. To prevent method overriding
3. To prevent Inheritance
Java final variable
• If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Java final method
• If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Java final class
If you make any class as final, you cannot extend it.
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Is final method inherited?
Yes, final method is inherited but you cannot override it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Super Keyword in Java
The super keyword in java is a reference variable which is used to refer immediate parent class
object. The keyword “super” came into the picture with the concept of Inheritance.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.
Uses of java super Keyword –
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor
1) super is used to refer immediate parent class instance variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
2) super can be used to invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
3) super is used to invoke parent class constructor.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Abstract Methods
A method that is declared as abstract and does not have implementation is known as abstract method.
abstract void disp();
1. In Java, an instance of an abstract class cannot be created, we can have references of abstract class type though.

abstract class Base


class Main
{ {
public static void main(String args[])
abstract void fun();
{
} // Uncommenting the following line will cause compiler error as the
class Derived extends Base // line tries to create an instance of abstract class.
// Base b = new Base();
{ // We can have references of Base type.
void fun() Base b = new Derived();
b.fun();
{ }
System.out.println("Derived fun() called"); }
Output
} Derived fun() called
}
2. An abstract class can contain constructors in Java. And a constructor of abstract class is
called when an instance of a inherited class is created.
abstract class Base
{ void fun()
Base() {
System.out.println("Derived fun() called");
{
}
System.out.println("Base Constructor Called");
}
} class Main
abstract void fun(); {
} public static void main(String args[])
class Derived extends Base {
Derived d = new Derived();
{
}
Derived()
}
{ Output
System.out.println("Derived Constructor Called"); Base Constructor Called
} Derived Constructor Called
3. In Java, we can have an abstract class without any abstract method. This allows us to create classes that cannot be instantiated, but
can only be inherited.
abstract class Base Output
{ Base fun() called
void fun()
{
System.out.println("Base fun() called");
}
}
class Derived extends Base
{
}
class Main {
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
4. Abstract classes can also have final methods (methods that cannot be overridden). For example, the following program compiles and
runs fine.

abstract class Base class Main


{ {
final void fun() public static void main(String
{ args[])
System.out.println("Derived fun() called"); {
}
Base b = new Derived();
b.fun();
}
}
class Derived extends Base
}
{ Output
} Derived fun() called
Java Interfaces Explained with Program
• An interface in java is a mechanism to achieve abstraction.
• Like a class, an interface can have methods and variables, but the methods declared in interface are by default
abstract (only method signature, no body).
• It is used to achieve abstraction and multiple inheritance in Java
• Interfaces specify what a class must do and not how.
• It is the blueprint of the class.
• If a class implements an interface and does not provide method bodies for all functions specified in the
interface, then class must be declared abstract.
• By interface, we can support the functionality of multiple inheritance.
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
• An interface can contain any number of methods.
How to Declare Interfaces ?
Interface is declared by using interface keyword. It provides total abstraction; means all the
methods in interface are declared with empty body and are public and all fields are public, static
and final by default. A class that implement interface must implement all the methods declared in
the interface
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}
interface Pet{
public void test();
}
class Dog implements Pet{
public void test(){
System.out.println("Interface Method Implemented");
}
public static void main(String args[]){
Pet p = new Dog();
p.test();
}
}
interface Bank
class ICICI implements Bank
{ {
public float rateOfInterest()
float rateOfInterest();
{
} return 9.7f;
}
class SBI implements Bank
}
{ public class JavaApplication4
{
public float rateOfInterest()
public static void main(String[] args)
{ {
Bank b = new SBI();
return 9.15f;
System.out.println("ROI: " + b.rateOfInterest());
} }
}
}
Multiple Interfaces
To implement multiple interfaces, separate them with a comma: class Main {
interface FirstInterface { public static void main(String[] args) {
public void myMethod(); // interface method DemoClass myObj = new DemoClass();
} myObj.myMethod();
interface SecondInterface { myObj.myOtherMethod();
public void myOtherMethod(); // interface method }
} }
class DemoClass implements FirstInterface, SecondInterface {
public void myMethod() {
System.out.println("Some text..");
}
public void myOtherMethod() {
System.out.println("Some other text...");
}
}
Java Scanner
• Scanner class in Java is found in the java.util package. Java provides various ways to read input from the keyboard, the java.util.Scanner
class is one of them.
• The Java Scanner class breaks the input into tokens using a delimiter which is whitespace by default.
import java.util.*;
public class ScannerClassExample1 {
public static void main(String args[]){
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Java File Handling
Java Create and Write To Files
Create a File
To create a file in Java, you can use the createNewFile() method.
This method returns a boolean value: true if the file was successfully created, and false if the file already exists.
Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some
reason):
Example
catch (IOException e) {
import java.io.File; // Import the File class
System.out.println("An error occurred.");
import java.io.IOException; // Import the IOException class to handle errors
e.printStackTrace();
public class CreateFile { }
public static void main(String[] args) { }
try { }
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
}
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you
are done writing to the file, you should close it with the close() method:

import java.io.FileWriter; // Import the FileWriter class


import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in the previous chapter:
Example
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("filename1.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
Delete a File
To delete a file in Java, use the delete() method:

Example
import java.io.File; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("filename1.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
Java - Exceptions
• An exception (or exceptional event) is a problem that arises during the execution of a program.
• When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.

An exception can occur for many different reasons.


• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of memory.

Categories of Exceptions
• Checked exceptions
• Unchecked exceptions
• Errors
Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at
compilation-time, these are also called as compile time exceptions.
For example: if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the programmer to
handle the exception.
import java.io.File; C:\>javac FilenotFound_Demo.java
import java.io.FileReader; FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be
thrown
public class FilenotFound_Demo { FileReader fr = new FileReader(file);
^
1 error
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These
are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of
an API.
public class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5


at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
Exception Hierarchy
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error
which is derived from the Throwable class.
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.
Keyword Description
Try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone.
It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't
throw an exception. It specifies that there may occur an exception
in the method. It is always used with method signature.
Java Exception Handling Example
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}

Exception in thread main java.lang.ArithmeticException:/


by zero
rest of the code...
Common Scenarios of Java Exceptions
1) A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will
occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java try-catch block
Java try block
• Java try block is used to enclose the code that might throw an exception. It must be used within the method.
• If an exception occurs at the particular statement of try block, the rest of the block code will not execute. So, it is
recommended not to keeping the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}
Problem without exception handling Solution by exception handling

public class TryCatchExample1 { public class TryCatchExample2 {

public static void main(String[] args) {


public static void main(String[] args) {
try
{
int data=50/0; //may throw exception int data=50/0; //may throw exception
}
//handling the exception
System.out.println("rest of the code");
catch(ArithmeticException e)
{
} System.out.println(e);
}
System.out.println("rest of the code");
}
}

}
Java catch multiple exceptions
public class MultipleCatchBlock2 {
public class MultipleCatchBlock1 {
public static void main(String[] args) {
public static void main(String[] args) {
try{
try{ int a[]=new int[5];
int a[]=new int[5];
a[5]=30/0; System.out.println(a[10]);
} }
catch(ArithmeticException e) catch(ArithmeticException e)
{ {
System.out.println("Arithmetic Exception occurs"); System.out.println("Arithmetic Exception occurs");
} }
catch(ArrayIndexOutOfBoundsException e) catch(ArrayIndexOutOfBoundsException e)
{ {
System.out.println("ArrayIndexOutOfBounds System.out.println("ArrayIndexOutOfBounds
Exception occurs"); Exception occurs");
} }
catch(Exception e) catch(Exception e)
{ {
System.out.println("Parent Exception occurs"); System.out.println("Parent Exception occurs");
} }
System.out.println("rest of the code"); System.out.println("rest of the code");
} }
} }
public class MultipleCatchBlock4 {
public static void main(String[] args) {
try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java Nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
class Excep6{
public static void main(String args[]){
going to divide
try{
java.lang.ArithmeticException: / by zero
try{
java.lang.ArrayIndexOutOfBoundsException: Index
System.out.println("going to divide");
5 out of bounds for length 5
int b =39/0;
other statement
normal flow..
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.

Case 1: exception doesn't occur. Case 2: exception occurs and not handled.
class TestFinallyBlock{ class TestFinallyBlock1{
public static void main(String args[]){ public static void main(String args[]){
try{ try{
int data=25/5; int data=25/0;
System.out.println(data); System.out.println(data);
} }
catch(NullPointerException e){System.out.println(e);} catch(NullPointerException e)
finally{System.out.println("finally block is always {System.out.println(e);}
executed");} finally{System.out.println("finally block is always
System.out.println("rest of the code..."); executed");}
} System.out.println("rest of the code...");
} }
}
Output: Output:
5
finally block is always executed
finally block is always executed
rest of the code... Exception in thread main
java.lang.ArithmeticException:/ by zero
Case 3: exception occurs and handled.
public class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}

Output: Exception in thread main


java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
Java throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw keyword.

The syntax of java throw keyword is given below.


throw exception;
Example Output:
public class TestThrow1{
static void validate(int age){
Exception in thread main
if(age<18)
java.lang.ArithmeticException:not valid
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an
exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Syntax of java throws
return_type method_name() throws exception_class_name{
//method code
}
import java.io.IOException; void p(){
class Testthrows1{ try{
void m()throws IOException{
n();
}catch(Exception e){System.out.println("exception
throw new IOException("device error");//checked exception
handled");}
} }
void n()throws IOException{ public static void main(String args[]){
m(); Testthrows1 obj=new Testthrows1();
} obj.p();
System.out.println("normal flow...");
}
}
Java Pass by Value vs Pass by Reference
• Pass by Value: The method parameter values are copied to another variable and then the copied variable is passed, that’s
why it’s called pass by value.
• Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by
reference.
• Code for pass by value
public class JavaApplication4 { Output:
static void displayPrimitive(int a) Before the function a: 5
{ Inside Display Primitive method
System.out.println("Inside Display Primitive method");
a :10
a=a+5;
After the function a: 5
System.out.println("a :"+a);
}
public static void main(String[] args) {
int a =5;
System.out.println("Before the function a: "+a);
displayPrimitive(a);
System.out.println("After the function a: "+a);
}
}
Pass by Reference –
public class JavaApplication4 {
Output:
static void displayArray(int[] a) Before the method
{ 222
System.out.println("\nInside Display Array method"); Inside Display Array method
a[0]=0; a[1]=0; a[2]=0; 000
for(int i=0;i<3;i++) After the function
System.out.print(a[i]+" ");
000
}
public static void main(String[] args) {
int arr[] = {2,2,2};
System.out.println("Before the function");
for(int i=0;i<3;i++)
System.out.print(arr[i]+" ");
displayArray(arr);
System.out.println("\nAfter the function");
for(int i=0;i<3;i++)
System.out.print(arr[i]+" ");
}
}
Wrapper Classes in Java | Autoboxing vs Unboxing
• The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into corresponding
objects.
• A Wrapper class is a class whose object wraps or contains a primitive data types.
• Wrapper classes in java provides the mechanism to convert primitive into object and object into primitive.
• Since J2SE 5.0, autoboxing and unboxing feature converts primitive into object and object into primitive
automatically. The automatic conversion of primitive into object is known as autoboxing and vice-versa
unboxing.
Autoboxing
Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing.
For example – conversion of int to Integer, long to Long, double to Double etc.
The Java compiler applies autoboxing when a primitive value is:
• Passed as a parameter to a method that expects an object of the corresponding wrapper class.
• Assigned to a variable of the corresponding wrapper class.
• Program: Primitive Types to Wrapper Objects
class Main {
public static void main(String[] args) {

// create primitive types


Output
int a = 5;
double b = 5.65; An object of Integer is created.
An object of Double is created.
//converts into wrapper objects
Integer aObj = Integer.valueOf(a);
Double bObj = Double.valueOf(b);

if(aObj instanceof Integer) {


System.out.println("An object of Integer is created.");
}

if(bObj instanceof Double) {


System.out.println("An object of Double is created.");
}
}
}
However, the Java compiler can directly convert the primitive types into corresponding objects. For example,

int a = 5;
// converts into object
Integer aObj = a;

double b = 5.6;
// converts into object
Double bObj = b;
This process is known as auto-boxing
Unboxing
It is just the reverse process of autoboxing. Converting an object of a wrapper class to its corresponding primitive type is
known as unboxing.
The Java compiler applies unboxing when an object of a wrapper class is:
• Passed as a parameter to a method that expects a value of the corresponding primitive type.
• Wrapper Objects into Primitive Types

class Main {
public static void main(String[] args) { Output

// creates objects of wrapper class The value of a: 23


Integer aObj = Integer.valueOf(23);
The value of b: 5.55
Double bObj = Double.valueOf(5.55);

// converts into primitive types


int a = aObj.intValue();
double b = bObj.doubleValue();

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


System.out.println("The value of b: " + b);
}
}
However, the Java compiler can automatically convert objects into corresponding primitive types. For example,

Integer aObj = Integer.valueOf(2);


// converts into int type
int a = aObj;

Double bObj = Double.valueOf(5.55);


// converts into double type
double b = bObj;
This process is known as unboxing.
Advantages of Wrapper Classes
In Java, sometimes we might need to use objects instead of primitive data types. For example, while working with collections.
// error
ArrayList<int> list = new ArrayList<>();

// runs perfectly
ArrayList<Integer> list = new ArrayList<>();
Typecasting in Java
• Typecasting in Java is assigning a value of one type to a variable of another type. When you assign value of one data type to
another, the two types might not be compatible with each other.
• If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion
(Widening ) and if not then they need to be casted or converted explicitly(narrowing).
2 types of Type Casting in java
• Automatic Type Conversion (Widening – implicit)
• Narrowing (Explicit)
• Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens when:
• The two data types are compatible.
• When we assign value of a smaller data type to a bigger data type.
class Test
{
public static void main(String[] args) Output
{ Int value 100
int i = 100; Long value 100
//automatic type conversion Float value 100.0
long l = i;

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


System.out.println("Long value "+l);
}
}
Narrowing or Explicit Type Conversion
• If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion cannot be done.
• Here, target-type specifies the desired type to convert the specified value to.
class Test
{
public static void main(String[] args)
{ Output
double d = 100.04; Double value 100.04
//explicit type casting Long value 100
long l = (long)d; Int value 100
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i);
}
}
Java Control Statements | Conditional & Looping Control Statements
They are mainly categorized in 2 types –
Conditional Control Statements
Whenever a condition is to be tested depending on which particular tasks are to be performed, Conditional control statements are used.
Looping / Iterative Control Statements
Whenever a particular task has to be iterated for a particular number of times or depending on some condition, Looping control statements are
used.
Java If-Else Conditional Statements.

• if statement
if(condition){
• if-else statement
//code to be executed
• if-else-if ladder }
• nested if statement

Java if Statement
• The Java if statement tests the condition. It executes the if block if condition is true.

public class IfExample {


public static void main(String[] args) {
int num=20;
if(num>0){
System.out.print("Positive");
}
}
}
Java 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.

if(condition){ public class IfElseExample {


//code if condition is true public static void main(String[] args)
}else{ {
//code if condition is false int number=13;
} if(number%2==0){
System.out.println("even
number");
}else{
System.out.println("odd
number");
}
}
}
Java if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements. It is used when more than 1 condition is to be checked in
relation with the problem.

if(condition1){ public class IfElseIfExample {


//code to be executed if condition1 public static void main(String[] args) {
is true int num=0;
}else if(condition2){
//code to be executed if condition2 if(num<0){
is true System.out.println("Negative");
} }
else if(condition3){ else if(num>0){
//code to be executed if condition3 System.out.println("Positive");
is true }
} }else{
... System.out.println("Neither Negative
else{ nor Positive");
//code to be executed if all the }
conditions are false }
} }
Java Switch Case Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. It is a multi-way branch
statement.

public class SwitchExample {


public static void main(String[] args) {
int number=20;
switch(number){
case 10:
System.out.println("10");break;
case 20:
System.out.println("20");break;
case 30:
System.out.println("30");break;
default:System.out.println("Not in 10,
20 or 30");
}
}
}
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. Usually while loop is used to when we don’t know how many times do we need to iterate the
loop in advanced or the number of iterations is based on some condition.

public class WhileExample {


while(condition){
public static void main(String[] args)
//code to be executed
{
}
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
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.

public class DoWhileExample {


public static void main(String[] args) {
int i=10;
do{
System.out.println(i); // the loop will execute once even
when i=10 and condition is i<10
i++;
}while(i<10);
}
}
For Loop
The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to
use for loop. Typically used when number of iterations in pre defined or already known.

for loop syntax public class ForExample {


for(initialization;condition;incr/decr){ public static void main(String[] args) {
//code to be executed for(int i=1;i<=10;i++){
} System.out.println(i);
for(initialization;condition;incr/decr){ }
//code to be executed }
} }

You might also like