Sunday, October 24, 2021

Interface in java-AapKiApniSchool


Interface in java: 

interface is a blueprint of class in java that is used to define contracts. It can contain static constant and abstract method. Interface is used in java for achieving abstraction. With the help of interface we can achieve multiple Inheritance. Till java 7 we can't create methods with body. All the methods will be abstract public.


In java 8 we can create default and static methods with body.

In java 9 we can create private method also.


Uses of Interface:


1. For achieving multiple Inheritance.

2. For achieving loose coupling.

3. For achieving abstraction.

4. Interface is used for abstraction.Many people thinks that why we use interface when we have abstract class. Abtract class is heavy weight as it can contain non-final variable,non-abstract method,constructors alos but Interface methods are public abstract and all variables are public static final.


How to declare an interface?

We declare interface in java with Interface keyword. By default all the variables in interface are public static final and all methods are public abstract.

Syntax:


import java.lang.*;
// Any number of import statements

public interface NameOfInterface {
   // Any number of final, static fields
   // Any number of abstract method declarations\
}


New Features in JDK8 Interface:


1. Prior to Java8 we could not able to add implementation in Interface. From Java8 we can provide some default implementation with default method. Default implementation has special use.It doen't affect the abstraction behind the Interface.
Suppose we want to provide new functionality in existing interface then it will not work as once we will create any method then all implementations class need to provide implementation those class need this functionality or not.
2. We can create static method in Java8 Interface. This static method we can access by this interface name only. For calling static method of Interface we don't need any object of implementation class.


Java 8 Default Method in Interface:


  // An example to show that interfaces can
// have default methods from JDK 1.8 onwards
interface In1
{
    final int a = 10;
    default void display()
    {
        System.out.println("Default Method");
    }
}
  
// A class that implements the interface.
class MainClass implements In1
{
 
    public static void main (String[] args)
    {
        MainClass t = new MainClass();
        t.display();
    }
}


Output :
Default Method


Java 8 Static Method in Interface:


 
 // An example to show that interfaces can
// have static methods from JDK 1.8 onwards
interface In1
{
    final int b = 10;
    static void message()
    {
        System.out.println("Static Method");
    }
}
  
// A class that implements the interface.
class MainClass implements In1
{
   
    public static void main (String[] args)
    {
        In1.message();
} }


Output :
Static Method


New Features in JDK9 Interface:

1. We can create private method.
2. We can create private static method.

Marker or tagged interface:

An interface which don't have any any field or methods. An empty interface is called marker interface which is used to provide some special information to JVM. Some Marker interface is used very frequently like Serializable, Cloneable and Remote.

  public interface Serializable 
{
  // Empty,no fields and no methods
}
  

Serializable interface:

Serializable interface is a marker interface which is part of Java.io package. A class that implements this interface that the capabilty to save the state of that class objet in file, without implementing this class, class can't save state of object in file.

Implementing Interfaces:

When a class is implementing Interface that class has to provide implementaion of all the methods of interface. If class is not providing implementation then that class has to declare that method as abstract.
A class use the implements keyword.

interface Printable{  
void print();  
}  
 
class Test implements Printable{  
public void print(){System.out.println("Printing Data");}  
  
public static void main(String args[]){  
Test obj = new Test();  
obj.print(); } }

Output :
Printing Data

Rules For Implements Interface:

1. A Class can implenets multiple interfaces.
2. A class can extends only one class but can implemets multiple interfaces at a time.
3. An interface can extends another interface also.
4. An implementation class itself can be abstract and if so, interface methods need not be implemented.
5. Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

Sunday, February 7, 2021

Abstract java | Abstract class in Java | Abstraction in oops-AapKiApniSchool

 

In this blog we will discuss what is Abstract class? How Abstract class is linked with Abstraction? We will check the use of Abstract class in Java. Also we will discuss why do we use Abstract class in Java?We will understand the real scnearion of Abstract class with examples. We will discuss Abstraction in java with example. We will unstandard the purpose of abstraction in OOP and also we will check that we can create constructor in abstract class.

 

Table of Abstract class:

 

  1. What is Abstraction? 

     1.1 Abstraction in java with real time example.

    1.2 How do you achieve abstraction?

  2. Abstract Class

    2.1 Use of Abstract Class

    2.2 Why do we use Abstract class in Java?

   2.3 What is the synatx of Abstract Class in Java?

   2.4 Abstract method in java

  2.5 Where do we use abstract class in real time?

 2.6 Can abstract class have constructor?

 2.7 What is the difference between data hiding and data abstraction?

 

Abstraction in Java: 

Abstraction is a process that hide the implementation and show only functionality. For example you have a car and you know how to drive car but how exactly internally clutch,brake and gear box work, we don't know. And it is not needed for driving car.Here implemetation of clutch,brake and gear is hidden. We know only functionality. Abstract class is sed to implement Abstraction process.

Ways to achieve Abstraction


There are two ways to achieve abstraction in java

 

  • Abstract class (0 to 100%)
  • Interface (100%)

 

Abstract java:

If any java class is declared with abstract keyword that class is called Abstract class. Abstract class can contain abstract method and non-abstract method. Abstract method means method is declared but don't have any body.Non-Abstract method have body.Abstract method is declared with Abstract keyword. Abstract method can declare only in abstract class.
 

Key Point Of Abstract Class:

 
  • It can have abstract and non-abstract methods.
  • It can contain static and non-static methods. 
  •  We can't create object of abstract class.
  •   It can have final methods and constructor. 
 

Use of Abstract class:

 
Abstract class is used for implementing abstraction. It hide the complexity and show only functionality. For example: Car. A car is having  lots of . Like braking system,gear etc. Car is hiding implementation as we don't know how braking systems or gear is working. Without knowing implementation we can use object this is called Abstraction that is implemented by Abstract class.
 

Why do we use Abstract class in Java?

Abstract class in java is used to achive Abstaraction that hide complexity.

 

What is the synatx of Abstract Class in Java?

abstract class A{

}

 

Abstract method in java:

In this class vehicle is an abstract class that is containg one abstract method. This class implementation is given by Car class.

 

abstract class Vehicle{
abstract void run();
}
class Car extends Vehicle{
void run(){System.out.println("Car running safely");}   
public static void main(String args[]){
Vehicle obj = new Car ();
obj.run();
}
}
 

Output:

 Car running safely

 

Abstract class having constructor, data member and methods:

Abstract class can contain constructor,data member,abstract method,non-abstract method and static methods also and even main method.
 
File: Test.java
 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 Bank bank= new SBI();
 
 System.out.println("Sbi Bank Interest Rate "+bank.getFdInterestRate());
 bank.rbiStndardRules();
 
 bank= new CBI();
 
 System.out.println("Cbi Bank Interest Rate "+bank.getFdInterestRate());
 
 bank.rbiStndardRules();
}
}
 
 
 
File:SBI.java
 
package youtubeClass;
 
public class SBI extends Bank {
 
@Override
int getFdInterestRate() {
int totalInterestRate=minimumInterestRate+5;
return totalInterestRate;
}
 
}
 
 
File: CBI.java
 
package youtubeClass;
 
public class CBI extends Bank {
 
@Override
int getFdInterestRate() {
int totalInterestRate=minimumInterestRate+4;
return totalInterestRate;
}
 
}
 
 
File: Bank.java
 
package youtubeClass;
 
public abstract class Bank {
 
static int minimumInterestRate=10;
public Bank() {
System.out.println("Abstract Class constructor called");
}
 
abstract int getFdInterestRate();
 
void rbiStndardRules()
{
System.out.println("Rbi Standard Rules");
}
 
}
 
 
 

Output:

 
Abstract Class constructor called
Sbi Bank Interest Rate 15
Rbi Standard Rules
Abstract Class constructor called
Cbi Bank Interest Rate 14
Rbi Standard Rules
 
 

Another real scenario of abstract class: 

The best example of abstract class is Java itself as we know the uses of java class but how these classes internally implemented it is hidden for us.

 
 

Can abstract class have constructor?

Abstract class can have constructor, methods with body or Without body(Abstract method). We can not create object of Abstract class.
 
 

What is the difference between data hiding and data abstraction?

 
The main difference is that data hiding is used to secure data but abstraction is used to hide complexity and show only functionality. Data hiding is implemented by encapsulation. Where we encapsulate our data member and methods in single unit. That unit is called class in Java.
 
 

Where do we use abstract class in real time?

 
The best example of abstract class in real time is ATM. We can withdraw money,check balance,register mobile number etc. Without knowing implementation of this operations. It provide the security from unauthorized object. It is showing only functionality and hiding complexity.
 
 
 

 

 
 
 
 

Friday, February 5, 2021

Loops in java-AapKiApniSchool

In this blog we will discuss all 3 type of loop in java in details. We will also discuss Infinite loops also. We will also discuss why for loop better than while loop and difference between while and do while loop. We will go through enhanced for loop that is also known for for-each loop.

Table of content:

  1. What are loops?
  2. What are the 3 types of loops?
  3. What is loop syntax?
  4. What is difference between while loop and do while loop?
  5. WHY IS FOR loop better than while loop?
  6. Which for loop is faster?
  7. Which loop is faster in Java?
  8. Infinite loop
    1. Infinite for loop
    2. Infinite while loop
    3. Infinite do-while loop
  9. Enhanced for loop(for-each loop)

Loops in java:

Loops in Java is used to execute some set of instructions repeatedly when some are conditions.

Types of Loops:

  1. for loop
    1. Enhanced for loop
    2. Infinite for loop
  2. while loop
    1. Infinite while loop
  3. do while loop
    1. Infinite do while loop

For loop:

For loop is a short hand of writing loop. It consists initialization,condition and increament/decreapment in one line.

Syntax:

  for(initlozation;condition;increment/decreament)
{

}

Flow chart:

Initialization:

In Initialization we provide the initial value of variable to start loop. We can use already declared variable or we can create new variable.

Condition:

Before executing loop first condition value is checked if condition is true then only block of loop is executed else loop terminated. Condition is mainly used to terminate loop after a particular condition failed.

Increment/decrement:

After executing first iteration variable value is increment or decrement and again condition checked.

Enhanced For loop:

In java 5 we got enhancement of for loop. Enhanced for loop is providing a simple way for iterating collection or array. Enhanced for loop is used only when you want to iterate a array or collection in a sequential manner without knowing index. Enhanced for loop is also know is for-each loop. It increase readability. Best drawback of for each loop is when iterating any array or collection we can't skip any element or we can't traverse in reverse order.

for(data_type variable : array | collection){  
//body of for-each loop  
} 
package testjava;

import java.util.ArrayList;
import java.util.List;

public class TestLoop {

	public static void main(String[] args) {
		
		List list= new ArrayList<>();

		list.add("Sunil");
		list.add("Anil");
		list.add("Narendra");
		
		for(String x:list)
		{
			System.out.println(x);
		}
	}

}

Output:
Sunil
Anil
Narendra

Java Infinite for loop:

If you don't pass Initialization, condition and increment/decrement value in for loop then it will be infinite for loop.
for(;;)
{}

While loop:

While loop first check condition, if condition is true then it will execute the body of loop otherwise terminate loop. While loop is used when iteration is not fixed. While loop also known for Entry check loop.

   while(condition)
   {
      //loop body
   }
  

Java Infinitive While Loop:

if you pass true in condition then it will be infinite while loop. It will never terminate.
 
    package testjava;

public class TestLoop {

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

}

  
Note: If you want to stop infinite loop then press Ctrl+C

do while:

do while loop first execute the body after that check condition. If condition is true then again it will execute iteration. do while loop execute at least one time if condition is true or not. In do while loop for first execution condition is not checked.
    
<1 pre=""> package testjava; public class TestLoop { public static void main(String[] args) { int i=1; do { System.out.println("Number is "+i); }while(i<1); } }
<1 pre="">
<1 pre="">Output:
<1 pre="">
<1 pre="">Number is 1

Java Infinitive do-while Loop

If you pass true in the do-while loop, it will be infinitive do-while loop.

Syntax:

do{  
//code to be executed  
}while(true);  
<1 pre="" style="background-color: powderblue;">package testjava;

public class TestLoop {

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

}

Note: If you want to stop infinite loop then press Ctrl+C

What is difference between while loop and do while loop?

While loop first check condition if condition is true then execute the body of loop but do-while loop first execute the body and then check condition if condition is true then it will condition execute loop. Do-While loop execute at least one time if condition is false or true. While loop can execute 0-n time but Do-While loop execute 1-n times.

WHY IS FOR loop better than while loop?

Performance of for loop and while loop is same. The advantage of a for loop is that it's harder to accidentally do an infinite loopOr rather, it's more obvious when you do one because you generally put the loop var in the initial statement. If we know the iteration then we should use for loop. If we don't know the iteration then we should use while loop. For example reading a file. 

Friday, January 29, 2021

Switch case java | Java Switch Statement-AapKiApniSchool

In this blog we will learn switch case java in details. We will discuss Java Switch Multiple Case. We will check java switch syntax,use of default case,how do exit switch case and create nested switch statement in java in details..

Table Of Content:

 1. switch case in java/java switch

2. java switch enum

3. java switch string

4.Is switch case faster than if else Java?

5. Can we use float in switch case in Java?

6. Does a switch statement need a default Java?

7. Can we create a nested switch statement in Java?

8.How do you exit a switch in Java?

9.Java Wrapper in Switch Statement

 

Switch case in java/java switch:

Switch case is like if-else-if statement. Switch case java execute one statement from multiple conditions.We can give expression of these type byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short. From Java 7 it accept String also.

 

Key Points:

  • Case value must be unique otherwise java compiler throw error.
  • The case value must be literal or constant. It doesn't allow variables.
  • Switch case type must be byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short types.
  • Switch case can have default case that is used if no case found.It is optional.
  • After each case we can put break keyword but it is optional.

 

 

Syntax:

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

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

 

 

Sample Code Without Break Keyword: 

Java Switch case execute all the statement after first match if break keyword not available.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="red";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
 
case "green":System.out.println("This is Green color.");
 
case "blue":System.out.println("This is Blue color.");
 
default:System.out.println("This is default color.");
}
 
}
 
}
 

OutPut:

 
This is Red color.
This is Green color.
This is Blue color.
This is default color.
 

Sample Code With Break Keyword:

It execute that particular case if break keyword is available.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="red";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
break;
 
case "green":System.out.println("This is Green color.");
break;
case "blue":System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
 
}
 

Output:

 
This is Red color.
 

Is switch case faster than if else Java?

Switch case is faster for multiple choice and complex conditions. Switch Case also increase readability. If Switch acse are very less than it will not impact performance. In that situation we can use if-else also.

Can we use float in switch case in Java?:

We can't use float in switch case. We will get complie time error if we try to use float in switch case.

Does a switch statement need a default Java?/Default Case Executions: 

Default case is optional in java switch case.Default case will be executed if switch expression value is not matching to any case.

 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
String color="yellow";
 
switch(color)
{
case "red":System.out.println("This is Red color.");
break;
 
case "green":System.out.println("This is Green color.");
break;
case "blue":System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
 
}
 

Output:

 
This is default color.
 

Java Enum in Switch Case/Java switch enum:

 In java switch case we can use Enum also.

 
package youtubeClass;
 
public class Test {
 
 public enum Colors { red,blue }
public static void main(String[] args) {
 
Colors[] colors = Colors.values();   
for(Colors color:colors) {
 
switch(color)
{
case red:System.out.println("This is Red color.");
break;
case blue:System.out.println("This is Blue color.");
break;
default:System.out.println("This is default color.");
}
 
}
}
}
 
 

Output:

 
This is Red color.
This is Blue color.
 

Java switch string: 

From Java 5 we can use String in Switch Case.

 

package youtubeClass;

public class SwitchCase {

public static void main(String[] args) {

String name="anil";

switch(name)
{
case "sunil":
System.out.println("My Full name is Sunil Sharma");
break;

case "anil":
System.out.println("My Full name is Anil Sharma");
break;
}

}

}

Output:

My Full name is Anil Sharma

Can we create a nested switch statement in Java?

Yes we ca create nested switch statement in java.

package youtubeClass;

public class SwitchCase {

public static void main(String[] args) {

int x=1,y=3;

switch(x)
{
case 1:
switch(y)
{
case 3:
System.out.println("Value is 3");
break;
}
break;
case 2:
System.out.println("Value is 2");
}

}

}


Java Wrapper in Switch Statement: 

 
We can use wrapper classes in Switch statement.
 
package youtubeClass;
 
public class Test {
 
public static void main(String[] args) {
 
Integer age = 18;
 
switch(age)
{
case 17:System.out.println("Sorry you are not eligable for DL.");
break;
case 18:System.out.println("you are eligable for DL.");
break;
default:System.out.println("Please provide valid age.");
}
 
}
}
 
 

Output:

you are eligable for DL.

Tuesday, January 26, 2021

Java list | Arraylist in java | Java ArrayList-AapKiApniSchool

 In this blog we will learn Java List and ArrayList in Java. Different Different type of List and Commonly used methods.


Java list | Arraylist in java


List: List is an interface in java that's implementation is given by ArrayList,LinkedList,Stack and Vector. List extends Collection interface.

Synatx for instantiate the List interface.

List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

Collection Interface Main Methods:

public boolean add(E e)
public boolean addAll(Collection<? extends E> c)
public boolean remove(Object element)
public boolean removeAll(Collection<?> c)
default boolean removeIf(Predicate<? super E> filter)
public void clear()
public int size()
public Object[] toArray()
default Stream<E> stream()

ArrayList:

ArrayList implements List interface in java. It is a Array with dynamic size. It main inseration order and it is not thread safe. The elements stored in the ArrayList class can be randomly accessed. It can store duplicate data.


package com.mkyong;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new ArrayList<>();
list.add("Sunil");
list.add("anil");
list.add("Narendra");
System.out.println("List "+list);

}

}




arraylist




LinkedList: 

LinkedList implements List interface. It don't maintain insertion order. It can store duplicate data. We can't access random data from LinkedList.It is not thread safe. Adding new element in Linkedlist is fast as compare to ArrayList.It maintain the inseration order. Internally it use LinkedList for storing data.


package com.mkyong;

import java.util.LinkedList;
import java.util.List;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new LinkedList<>();
list.add("Sunil");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}



LinkedList



Vector: 

Vector is similar to ArrayList but it is thread safe. Vector also internally use dynamic array.


package com.mkyong;


import java.util.List;
import java.util.Vector;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new Vector<>();
list.add("Sunil1");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}


Stack:

Stack is a sub class of Vector. It contain all the methods of Vector and some additional methods like push,peek and pop. Push is used to insert data.Pop is used to remove data. Stack use First-In Last-Out DataStructure.


package com.mkyong;


import java.util.List;
import java.util.Stack;

public class ListDemo {

public static void main(String[] args) {
List<String> list= new Stack<>();
list.add("Sunil1");
list.add("anil");
list.add("Narendra");
list.add("Sunil");
System.out.println("List "+list);

}

}



package com.mkyong;
import java.util.Stack;

public class ListDemo {

public static void main(String[] args) {
Stack<String> list= new Stack<>();
list.push("Sunil1");
list.push("anil");
list.push("Narendra");
list.push("Sunil");
System.out.println("List "+list);
list.pop();
System.out.println("List "+list);

}

}




Monday, January 25, 2021

Java object to xml | JAXB marshalling - convert java object to xml | Convert java object to xml in java

 In this blog we will discuss Java Object to xml.JAXB marshalling - convert java object to xml. Also we will check how to convert Java objet to xml file.


Java object to xml | JAXB marshalling - convert java object to xml | c


Maven Dependency:

<!-- https://mvnrepository.com/artifact/javax.xml/jaxb-api -->
<dependency>
    <groupId>javax.xml</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.0</version>
</dependency>


Spring Boot Dependency:

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

Program for Converting Java Object to xml String:


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ConvertJavaObjectToXml {

public static void main(String[] args) {
Person person= new Person("Sunil",24,"India");
try {
JAXBContext contextObj = JAXBContext.newInstance(Person.class);
Marshaller marshallerObj = contextObj.createMarshaller(); 
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshallerObj.marshal(que, new FileOutputStream("question.xml"));
 
StringWriter sw = new StringWriter();
 
marshallerObj.marshal(person,sw);
 
String xmlString=sw.toString();
 
System.out.println("xmlString "+xmlString);
 
marshallerObj.marshal(person, new FileOutputStream("person.xml"));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  

}


package com.mkyong;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Person {

private String name;
//@XmlElement
private int age;
//@XmlElement
private String address;
public Person() {
super();
// TODO Auto-generated constructor stub
}

public Person(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@XmlElement
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
@XmlElement
public void setAddress(String address) {
this.address = address;
}
}



Program for Converting Java Object to Xml File



import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class ConvertJavaObjectToXml {

public static void main(String[] args) {
Person person= new Person("Sunil",24,"India");
try {
JAXBContext contextObj = JAXBContext.newInstance(Person.class);
Marshaller marshallerObj = contextObj.createMarshaller();

//This line is used to format xml file
marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

 
StringWriter sw = new StringWriter();
 
marshallerObj.marshal(person,sw);
 
 
marshallerObj.marshal(person, new FileOutputStream("person.xml"));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  

}

}


Note: your xml willbe stored in same location where your project existing.

Saturday, January 23, 2021

Java if else | Ternary operator java | Conditional operator in java-AapKiApniSchool

 In this blog i will explain you how to use java if else. We will change if else to ternary opertaor java.


Java if else | Ternary operator java | Conditional operator in java | Conditional statements in java


Java if else is used to check boolean condition true or false. There are diffent types of if else statements

1. if statement
2. if else statement
3. nested if else
4. if else if


Java if Statement:

Java if statement execute if the given condition is true.

Syntax:

if(condition)
{
code will be executed
}

Java if else statement:

In Java if else statement code written inside if block will be executed if given condition is true.Otherwise else block code will be executed.

if(Condition)
{
 //This code will be executed if condition is true
}
else{
  //This code will be executed if condition is false
}


Java nested if else:


In Java nested if else will be executed if outer if condition is true.

if(condition)
{
   if(Condition)
{
   //This code will be executed if outer and inner conditions are true.

}
else{
 //This code will be executed if outer if condition is true aand inner conditions is false.
}
}
else{

}


Java if-else-if:

In Java if else if statement first if condition is checked if first if condition is false then else if condition will be checked if else if condition is true then else if block will be executed otherwise else block will be executed.

if(Condition1)
{}
else if(Condition2)
{}
else{
}


Ternary operator java:

We can convert if else statement to ternary operator statement.

if else statement:

if(2<5)
{
  return true;
}
else{
 return false;
}

Ternary Operator:

boolean x=2<5?true:false;

Featured Post

Interface in java-AapKiApniSchool

Interface in java:  interface is a blueprint of class in java that is used to define contracts. It can contain static constant and abstract ...

Popular Posts