Category Archives: Core Java

Complete Array Tutorial in Java with Programming Example

Java ArrayIn this chapter you will learn:

  1. What is an Array?
  2. Single Dimensional Array vs. Multi-Dimensional Array
  3. How to pass an array to method
  4. Array Class and Manipulation

What is an array?

An array is a collection of data of same data type. It is like a container object which holds fixed number of same type value. The size of array is defined when initialized array. The item stored in array is called element and each element is accessed by index position. Normally the first index position of array is 0.

Array

Types of Array

There are two types of array in Java.

  1. Single Dimensional Array
  2. Multi-Dimensional Array

Single Dimensional Array

Single dimensional array has only one row of data. It is also considered as simple type array. The data can be stored or accessed using simple for loop or other looping constructs.

Initialization:
  datatype[] arrayname=new datatype[size]; 


Array

In the above example there are 8 elements in array which stores data in following manner.

Index position 0 = 23
Index position 1 = 55
Index position 2 = 34
Index position 3 = 90
Index position 4 = 37
Index position 5 = 77
Index position 6 = 16
Index position 7 = 56

Programming Example

class SingleArray
{
  public static void main(String[] args)
  {
    //Created integer type array with 5 elements
    int[] arr=new int[8];
    
    //storing data in array
    arr[0] = 23;
    arr[1] = 55;
    arr[2] = 34;
    arr[3] = 90;
    arr[4] = 37;  
    arr[5] = 77;
    arr[6] = 16;
    arr[7] = 56;
    
    //Accessing Data
    for(int i=0; i<8; i++)
    {
      System.out.println("Index Position: " + i + 
	  " Value = " + arr[i]);
    }
  }
}

Output

Index Position: 0 Value = 23
Index Position: 1 Value = 55
Index Position: 2 Value = 34
Index Position: 3 Value = 90
Index Position: 4 Value = 37
Index Position: 5 Value = 77
Index Position: 6 Value = 16
Index Position: 7 Value = 56D:\JavaProgram>__

Multi-Dimensional Array

Multi-Dimensional array have more than one row of data. It is actually a set of single dimensional array. To access multi-dimensional array data you need to use nested loop.

Initialization

   String[][] book=new String[4][3];
   

Multi Dimensional Array

Programming Example

class MultiArray
{
  public static void main(String[] args)
  {
    //Creating array with 2 row and 5 column
    String[][] book=new String[4][3];
    
    //Storing Data in first row
    book[0][0] = "Book";
    book[0][1] = "AuthorName";
    book[0][2] = "Age";
       
    //Storing Data in second row
    book[1][0] = "C#";
    book[1][1] = "Lyric Angel";
    book[1][2] = "30";
    
    //Storing Data in 3rd row
    book[2][0] = "Java";
    book[2][1] = "Eddy Angelil";
    book[2][2] = "34";
    
    //Storing Data in 4th row
    book[3][0] = "PHP";
    book[3][1] = "Raine Finley";
    book[3][2] = "28";
    
    
    //Accessing Data 
    
    //Traversing Row
    for(int i =0; i<4; i++)
    {
      //Traversing Column
      for(int j=0; j<3; j++)
      {
        System.out.print("book["+i+"]["+j+"] = " + 
		book[i][j]+"\t");
      }
      System.out.println("\n - - - - - - - - - -");
    }
  }
}

Output

book[0][0] = Book  book[0][1] = AuthorName  book[0][2] = Age
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[1][0] = C#   book[1][1] = Lyric Angel   book[1][2] = 30
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[2][0] = Java  book[2][1] = Eddy Angelil   book[2][2] = 34
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
book[3][0] = PHP  book[3][1] = Raine Finley   book[3][2] = 28
– – – – – – – – – – – – – – – – – – – – – – – – – – – – – –
_

Pass Array to a method

You can also pass an array to method. The method will process the array and return output as per your programming logic. Here, we are including a programming example in which we have created two methods that will return largest number and smallest number.

Programming Example

class ArraytoMethod
{
  public static void main(String[] args)
  {
    int[] arr=new int[5];
    arr[0] = 23;
    arr[1] = 65;
    arr[2] = 38;
    arr[3] = 10;
    arr[4] = 53;
    
    int max,min;
    max=getmax(arr);
    min=getmin(arr);
    
    System.out.println("Largest Number is " + max);
    System.out.println("Smallest Number is " + min);
  }
  
  public static int getmax(int[] a)
  {
    int num=a[0];
    for(int i=0; i<a.length; i++)
    {
      if(num < a[i])
      {
        num = a[i];
      }
    }
    return num;
  }
  public static int getmin(int[] b)
  {
    int num=b[0];
    for(int i=0; i<b.length; i++)
    {
      if(num > b[i])
      {
        num = b[i];
      }
    }
    return num;
  }
  
}

Output

Largest Number is 65
Smallest Number is 10
_

Summary

In this chapter you have learned complete details of java array with programming examples. All topics are explained with suitable programming examples. In the next chapter you will learn about Strings and Collections.


Constructors in Java with Programming Example

In this chapter you will learn:Java Constructors

  1. What is a constructor in java?
  2. What is the need of constructors?
  3. Programming Example
 What is Constructors?

A Constructor is a special method in java which is used for initializing objects. A constructor is a way to pass value to class which is required when objects is initialized. Let’s learn it with this example.

We have a class for temperature converter which converts Fahrenheit into Celsius. The condition is you need Fahrenheit value when class is initialized into object. There is no way to pass value later. A constructor is used here for this purpose.

Every class has one or more than one constructors with same name of class. If you don’t define any constructor, compiler will automatically make default constructor with no value.

How to create Constructor?

A constructor in java can be created same name with class. For example

 class PrintData
 {
  //Default Constructor
  public PrintData()
  {
  }
  //A Constructor which require string argument while initialing objects.
  public PrintData(String name)
  {
  }
 } 


 Programming Example
class DemoCons
{
  public static void main(String[] args)
  {
    Demo dc=new Demo(); //Default Constructor Called
    Demo dc1=new Demo("Hello Friend"); //string constructor called
    dc.PrintMessage(); //PrintMessage() Method Executed
  }
}

class Demo
{
   //Constructor Block
  public Demo()
  {
    System.out.println("I am Default Constructors");
  }
  public Demo(String message)
  {
    System.out.println(message);
  }
  //End of Constructor Block
  
  public void PrintMessage()
  {
    System.out.println("PrintMessage() Method Executed...");
  } 
}

Output

D:\JavaProgram>javac DemoCons.java

D:\JavaProgram>java DemoCons
I am Default Constructors
Hello Friend
PrintMessage() Method Executed…

D:\JavaProgram>__

Explanation:

In the above programming example we have done the following job.

  1. In the above example we have created 2 constructors.
  2. public Demo() is a default constructors. It will executed if object is initialized without parameter.
  3. public Demo(String message): It is second constructor and will be executed when object is initialized with String parameter.
  4. This constructors are executed when objects is initialized as follow:
      Demo dc=new Demo(); //Default Constructor Called
      Demo dc1=new Demo("Hello Friend"); //string constructor called
    
    
    

Summary

In this chapter you have learned how to create and initialized constructors in java. The next chapter will demonstrate Array in Java.


Classes, Objects and Methods in Java with Programming Example

In this chapter you will learn:Java Classes

  1. What are classes in java and how to create it?
  2. What is objects and how to initialize it?
  3. What is methods and how to create it?
  4. Programming Example
This is the very important chapter in java which enables you to make your own class, objects and methods. As you know java is object oriented programming language which means you can write program once and use it many times. The place where you write programming logic is class and when you use your program multiple times it is objects.

What are classes?

Classes are the blueprint of your program. It is the place where you define variables, methods, constructors, blocks, interfaces and program logic. Once classes are completed you can use it many times by creating its alias name or objects.

How to define class?

You can define class with class keyword as follow:

  public class MyClass
 

What is object and how to initialize it?

An object is an alias of the class which represents class behavior. A class may have many objects with different names. You can define objects as follow:

  Class_Name object_name=new Class_Name();


What is method or function?

A method of function is a basic building block of program which contains set of code and referred to by a name. A method is created inside class and can be accessed anywhere in program directly by name or followed by its class name.

How to define method?

It is very easy to define method in java. You can write method as follow:

public void myname()
{
//code block
}

Or 

public String myname()
{
//code block
Return String_Value
}


OK. It’s enough for theory. Let’s understand all these concepts using programming example. In the following program we will create classes, methods and objects.

Programming Example:

class CreatingClass
{
  public static void main(String[] args)
  {
    int result;
    
    //Creating Calculator Object
    Calculator calc=new Calculator();
    //Calling Add() method
    result=calc.Add(12,18);
    
    //Creating PrintData Class Object
    PrintData pdata=new PrintData();
    //Calling print() method
    pdata.print(result);
  }
}

//Defining Class Calculator
class Calculator
{
  public int Add(int num1, int num2)
  {
    System.out.println("Calculator Class Started...");
    return num1 + num2;
  }
}

//Defining Class PrintData
class PrintData
{
  public void print(int value)
  {
    System.out.println("PrintData Class Started.. ");
    System.out.println(value);
  }
}

Output

D:\JavaProgram>javac CreatingClass.java

D:\JavaProgram>java CreatingClass
Calculator Class Started…
PrintData Class Started..
30

D:\JavaProgram> __

Explanation:

In the above programming example we have done the following job.

  1. Created 2 separate class Calculator and PrintData.
  2. Calculator class have a method Add(int num1, int num2) which requires 2 integer number to process and it returns addition of both number.
  3. PrintData class have a method print(int value) which requires an integer value and print it on screen.
  4. In the main method I have created object of Calculator Class and send 2 integer value for processing.
    Calculator calc=new Calculator();
    result=calc.Add(12,18);
    
  5. Next create object of PrintData and used it’s print method for printing output.
    PrintData pdata=new PrintData();
    pdata.print(result);
    

Summary

So, we have explained how to create classes objects and methods in Java. However there are lots of thing in classes but we can’t explain all those things here. It will make this article heavy for understanding. You will learn all those things part by part in the next few chapters. The next chapters explain Constructors in Java.


How to get User Input in Java?

In this chapter you will learn:get user input

  1. How to get Integer Input?
  2. How to get String Input?
  3. How to get Float Input?

This chapter demonstrates how to get user input in java. Various times while programming in java you need to accept some value from the user end. This value might be integer, string or float. As a java programmer you must know the input mechanism of java. Once you will finish this chapter, I am sure you will be master in accepting input in Java.

How to get user input in java?

To get input in java there are several classes which allow you to accept user end data but the most popular way is using Scanner Class.

Scanner Class

It is the most popular way to accept user input. Scanner class uses following method to accept different types of data. You must import java.util.Scanner class before using scanner method.

 

 Scanner sc=new Scanner(System.in);
 

 

Method Description
sc.next() Accept only one string and break when white space detected.
sc.nextLine() Accept full line of string with white space.
sc.nextByte() Accept byte data and store in byte variable.
sc.nextShort() Accept short data and store in short variable.
sc.nextInt() Accept number and store in integer variable.
sc.nextLong() Accept long value and store it in long variable.
sc.nextFloat() Accept float value and store it in float variable.
sc.nextDouble() Accept double value and store it in double variable.

Here we are writing a program which accept some user input and print the output. The program will ask following details from the user.

Name:
Age:
Mobile No:
Sex:
Qualification:

Programming Example

//You must write this line here for using Scanner class in program
import java.util.Scanner;

class ScannerClass
{
  public static void main(String[] args)
  {
    String name;
    int pin;
    Short age;
    Long mobileNumber;
   
    
    //Initializing Scanner Class
    Scanner sc=new Scanner(System.in);
    
    //Getting User Details
    System.out.println("Enter Your Name: ");
    name=sc.nextLine();   
    System.out.println("Enter your 4 Digit Pin Number: ");
    pin=sc.nextInt();
    System.out.println("Enter your age: ");
    age=sc.nextShort();    
    System.out.println("Enter your Mobile Number: ");
    mobileNumber=sc.nextLong();
    
    //Printing User Details
    System.out.println("********************User Details**********************");
    System.out.println("Name : " + name);
    System.out.println("Pin : " + pin);
    System.out.println("Age : " + age);
    System.out.println("MobileNumber : " + mobileNumber);
  
  }
}

Output

D:\JavaProgram>javac ScannerClass.java

D:\JavaProgram>java ScannerClass
Enter Your Name:
Christian Bale
Enter your 4 Digit Pin Number:
8851
Enter your age:
40
Enter your Mobile Number:
878765642

********************User Details**********************
Name : Christian Bale
Pin : 8841
Age : 40
MobileNumber : 878765642

D:\JavaProgram> __

Explanation

In the above example we added Scanner Library to program so that we can use Scanner class.

 //You must write this line here for using Scanner class in program
 import java.util.Scanner;


After that we have used several Scanner Object methods for accepting different types of value as

  name=sc.nextLine(); //For accepting string
  pin=sc.nextInt(); //For accepting integer
  age=sc.nextShort(); //For accepting short
  mobileNumber=sc.nextLong(); //For accepting Long


Summary

In this chapter you have learned how to accept user input in java. In the next chapter you will learn to define classes, objects and methods in java.

Decision Making Control in Java

In this chapter you will learn:decision-making-skills

  1. What is Decision Making in Java?
  2. What is If else Statement?
  3. What is switch case statement?
  4. Programming Example

What is Decision Making in Java?

Decision Making is a process in which a condition is evaluated and based on true/false result program gets direction to execute. Mainly If-else and switch case statements are responsible for decision making in Java.

What is If Else Statement?

If Else statement is primary decision making or branching control in Java. It tests a condition and return Boolean value (true or false) as output. If the output is true the if block executed otherwise else block gets executed. You can understand it with this picture.

Syntax

if(boolean_expression)
{
   /* statement(s) will execute if the boolean expression is true */
}
else
{
   /* statement(s) will execute if the boolean expression is false */
}

 

Programming Example

class IfElse
{
  public static void main(String[] args)
  {
    int num1, num2;
    num1=10;
    num2=12;
    
    //In this program Else block gets executed
    if(num1>num2)
    {
      System.out.println(num1 + "is greater than " + num2);
    }
    else
    {
      System.out.println(num2 + " is greater than " + num1);
    }
  }
}

Output

D:\JavaProgram>javac IfElse.java

D:\JavaProgram>java IfElse
12 is greater than 10

D:\JavaProgram> __

 

What is Switch Case Statement in Java?

If you have to use multiple if else statement you can use switch case statement instead of it. In switch case statement there is a condition inside a switch and a list of condition in case. When a case condition matches with switch condition the program executes the particular case condition.

Syntax

switch(expression){
    case value :
       //Statements
       break; //optional
    case value :
       //Statements
       break; //optional
    //You can have any number of case statements.
    default : //Optional
       //Statements
}

Programming Example

import java.util.Scanner;

class SwitchCase
{
  public static void main(String[] args)
  {
    String DayName;    
    System.out.println("Enter a Day Name in small letter:");
    
    //Getting Input from user
    Scanner scan=new Scanner(System.in);
    DayName=scan.nextLine();
    
    switch(DayName)
    {
      case "sunday":
      {
        System.out.println("wooo... hoooo.... It's Sunday");
        break;
      }
      case "monday":
      {
        System.out.println("oh no! Its Monday");
        break;
      }
      case "tuesday":
      {
        System.out.println("Again Tuesday");
        break;
      }
      case "wednesday":
      {
        System.out.println("Wednesday is so boring..");
        break;
      }
      case "thursday":
      {
        System.out.println("Thursday!!! Thursday!!! Thursday!!!");
        break;
      }
      case "friday":
      {
        System.out.println("It's Friday Now!!!");
        break;
      }
      case "saturday":
      {
        System.out.println("It's Saturday.. Party Night!!!");
        break;
      }
      default:
      {
        System.out.println("Invalid Day Name");
      }
    }
  }
}

Output

D:\JavaProgram>javac SwitchCase.java

D:\JavaProgram>java SwitchCase
Enter a Day Name in small letter:
saturday
It’s Saturday.. Party Night!!!

D:\JavaProgram> __

Summary

In this chapter you have learned what is decision making, if else block and switch case statement in Java. It is also known as branching in Java. In the next chapter you will learn how to get input from user in Java.

Learn Loop System in Java with Programming Example

In this chapter you will learn:Loop

  1. What is loop in Java?
  2. Explain For loop, do while loop and while loop
  3. Loop programming example
 What is loop in Java?

Loop is very important statement in any programming. Loop is a techniques to repeat a block of code certain times. Sometimes you need to execute a task multiple times especially working with array when you need to store or retrieve value. Loop helps you to read all element of array.

How many types of loop available in Java?

Java provides following looping constructs to work with.

  1. For Loop
  2. While Loop
  3. Do While Loop

Apart from it there are two looping control statements are available which decide whether your loop will be terminated in meanwhile the process or continue by skipping current iteration of loop.

(i) Break statement – It terminated the loop completely and forward execution to outside from loop.
(ii) Continue Statement – It skips only current iteration of loop. It doesn’t break the loop.

For Loop:

For loop is most common but most usable loop in Java. It requires 3 condition to work properly.

(i) Initialization – Starting point of loop
(ii) Termination – Loop breaks when reaches this point.
(iii) Increment/Decrement – Increment or decrement loop iteration.

Syntax:

for (initialization; termination; increment) 
{
    statement(s)
}

Programming Example

class ForLoop
{
  public static void main(String [] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
    for(int i=0; i<7; i++)
    {      
      System.out.println(str[i]);
    }
  }
}

Output

D:\JavaProgram>javac ForLoop.java

D:\JavaProgram>java ForLoop
sunday
monday
tuesday
wednesday
thursday
friday
saturday

D:\JavaProgram> __

Another way to use For Loop in Java (Like Foreach)

class ForeachLoop
{
  public static void main(String[] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};   
    for(String s: str)
    {
      System.out.println(s);
    }
  }
}

Output

D:\JavaProgram>javac ForeachLoop.java

D:\JavaProgram>java ForeachLoop
sunday
monday
tuesday
wednesday
thursday
friday
saturday

D:\JavaProgram> __

 

While Loop

In while loop you initialize the loop variable before the loop starts. While are just keeping test whether condition is true or not and inside the while condition increment/decrement process done.

Programming Example

class WhileLoop
{
  public static void main(String [] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};    
    int i = 0;
    while(i<7)
    {
      System.out.println(str[i]);
      i++;
    }
  }
}

Output

D:\JavaProgram>javac WhileLoop.java

D:\JavaProgram>java WhileLoop
sunday
monday
tuesday
wednesday
thursday
friday
saturday

D:\JavaProgram> __

 

Do While Loop

In do while is slightly different from while loop. The while loop executes if the condition matches but in do while loop statement, the loop starts first then check condition in second iteration. It means whether or not condition is matches, the loop executes one iteration by default.

Programming Example

class DoWhileLoop
{
  public static void main(String [] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};    
    int i = 0;
    do
    {
      System.out.println(str[i]);
      i++;
    }
    while(i<7);
  }
}

Output

D:\JavaProgram>javac DoWhileLoop.java

D:\JavaProgram>java DoWhileLoop
sunday
monday
tuesday
wednesday
thursday
friday
saturday

D:\JavaProgram> __

Break Statement:

As earlier explained; that the break statement terminates the loop and sends execution control outside the loop. Let’s understand it with suitable programming example:

class BreakStatement
{
  public static void main(String[] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
    for(int i=0; i<7; i++)
    {  
      if(str[i]=="thursday")
      {
        System.out.println("Breaking the loop. sorry!!!");
        break;
      }
      System.out.println(str[i]);
    }
  }
}

Output

D:\JavaProgram>javac BreakStatement.java

D:\JavaProgram>java BreakStatement
sunday
monday
tuesday
wednesday
Breaking the loop. sorry!!!

D:\JavaProgram> __

Continue Statement:

The continue statement skips the current iteration of loop and increment loop value by 1. It doesn’t terminate the loop instead it only terminate the current iteration of loop. Let's understand it with suitable programming example:

Programming Example

class ContinueStatement
{
  public static void main(String[] args)
  {
    String [] str = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
    for(int i=0; i<7; i++)
    {  
      if(str[i]=="thursday")
      {
        System.out.println("This information is not available. Sorry!!!");
        continue;
      }
      System.out.println(str[i]);
    }
  }
}

Output

D:\JavaProgram>javac ContinueStatement.java

D:\JavaProgram>java ContinueStatement
sunday
monday
tuesday
wednesday
This information is not available. Sorry!!!
friday
saturday

D:\JavaProgram> __

Return Statement

The return statement exits execution control from the current method and send it where method was invoked. There are two types of return statement in Java. One which return a value and another one which doesn’t return any value.

Programming Example

class ReturnStatement
{
  public static void main(String[] args)
  {
    int result;
    result=add(20,30);
    System.out.println(result);    
  }
  
  public static int add(int num1, int num2)
  {
    return num1+num2;
  }
}

Output

D:\JavaProgram>javac ReturnStatement.java

D:\JavaProgram>java ReturnStatement
50

D:\JavaProgram>

Summary

In this chapter you have learned looping statement in java. You have also learned what the for loop, while loop, do while loop, return statement, break statement and continue statement in Java. In the next chapter you will learn about Decision Making in Java.

Bitwise Operator in Java – Programming Example

In this chapter you will learn:BitwiseOperators

  1. What is bitwise operator?
  2. How bitwise operator works?
  3. Programming example of bitwise operator
 What is bitwise operator?

AND (&), EXCLUSIVE OR (^), INCLUSIVE OR (|) are called a bitwise operator. Bitwise operator is less commonly used in java programming so you need not to dive deeply in bitwise operator. Bitwise operator is just exists in Java but not in use.

Here, we are taking 2 values and their binary value:

Value 1: 45
Binary value of 45 is : 0010 1101

Value 2: 55
Binary Value of 55 is : 0011 0111

Bitwise And (&) Operator

Bitwise And operator compares each bit of both value respectively and set 1 if both value is 1 otherwise set 0 if one of them is 0.

For example:
num3 = num1 & num2;

Let’s understand it as follow:

Num1 = 0010 1101
Num2 = 0011 0111
————————————-
Num3 = 0010 0101

So the num3 holds the value 37 which is equivalent to binary number 0010 0101

 Bitwise EXCLUSIVE OR (^) or XOR

Bitwise exclusive OR (^) operator compares each bit of both value respectively and set 1 if one of them is 1 and other one is 0.

Example
num3 = num1 ^ num2;

Let’s understand it as follow:

Num1= 0010 1101
Num2= 0011 0111
————————————-
Num3= 0001 1010

So, the num3 holds the value 26 which is equivalent to binary number 0001 1010

Bitwise Inclusive OR (|)

Bitwise inclusive OR (|) operator compares each bit of both operands and set 1 if one of them is 1.

Example
num3 = num1 | num2;

Let’s understand it as follow:

Num1= 0010 1101
Num2= 0011 0111
————————————-
Num3= 0011 1111

So, the num3 holds the value 63 which is equivalent to binary number 0011 1111

Programming Example of bit operator in Java

class BitwiseOperator
{
  public static void main(String[] args)
  {
    int num1, num2, num3;
    num1 = 45;
    num2 = 55;
            
    //Using Bitwise AND(&) Operator
    num3 = num1 & num2;
    System.out.println("Result of num1 & num2 is "+num3);
    
    //Using Bitwise Exclusive OR(^) Operator
    num3 = num1 ^ num2;
    System.out.println("Result of num1 ^ num2 is "+num3);
    
    //Using Bitwise Inclusive OR(|) Operator
      num3 = num1 | num2;
      System.out.println("Result of num1 | num2 is "+num3);
  }
}

Output

D:\JavaProgram>javac BitwiseOperator.java

D:\JavaProgram>java BitwiseOperator
Result of num1 & num2 is 37
Result of num1 ^ num2 is 26
Result of num1 | num2 is 63

D:\JavaProgram> __

Summary

In this chapter you have learned what the bitwise operator in java is and how to use them in a program. Bitwise operator is rarely used by java programmer. In the next chapter you will learn about Loop statements in Java.

(? :) Conditional/Ternary Operator in Java – Programming Example

In this chapter you will learn:

  1. What is conditional or ternary operator in java
  2. Programming example 

    ternary operator

 

What is conditional or ternary operator in java?

Symbol of Ternary operator is (?:) and it is also known as ternary operator. This operator works on 3 operands and simply minify your code by removing if else clause.

Syntax of ternary operator:

variable x = (expression) ? value if true : value if false
 Programming Example:
class TernaryOperator
{
  public static void main(String[] args)
  {
    int num1, num2, num3;
    num1 = 5;
    num2 = 10;
    
    //Output will be 10
    num3=(num1 == num2) ? num1 : num2;
    System.out.println(num3);
    
    //Output will be Hello
    String s;
    s=(num1 != num2) ? "Hello" : "Hi";
    System.out.println(s);
  }
}

Output

D:\JavaProgram>javac TernaryOperator.java

D:\JavaProgram>java TernaryOperator
10
Hello

D:\JavaProgram> __

Summary

In this chapter you have learned what conditional or ternary operator in Java is. You have also learned a programming example of conditional operator. In the next chapter you will learn about Bitwise Operator in Java.

Logical or Conditional Operator in Java – Programming Example

In this chapter you will learn:Logical Operators

  1. What is logical/Conditional operator in Java?
  2. Logical operator symbol
  3. Programming example
 What is logical operator in Java?

Logical operator is also known as conditional operator in java. It is And (&&), Or(||) andNot(!). The logical operator is very useful when you need to compare two statements.

Operator Description Example
&& Conditional-AND – Compare two statement and return true if both are true if(username==”user1″ && password==”pass123″)
|| Conditional-OR – compare two statement and return true if one of them is true if(username==”user1″ || password==”pass123″)
?: Ternary (shorthand for if-then-else statement) variable x = (expression) ? value if true : value if false
You can understand the working of logical or conditional operator using this programming example:
Programming Example:
class LogicalOperator
{
  public static void main(String[] args)
  {
    String username, password;
    username="user1";
    password="pass123";
    
    if(username=="user1" && password=="pass123")
    {
      System.out.println("Authorized Login Successful");
    }
    else if(username=="user1" && password!="pass123")
    {
      System.out.println("Incorrect Password");
    }
    else if(username!="user1" && password=="pass123")
    {
      System.out.println("User Not Registered");
    }
    else
    {
      System.out.println("Incorrect UserID and Password");
    }      
  }
}

Output

D:\JavaProgram>javac LogicalOperator.java

D:\JavaProgram>java LogicalOperator
Authorized Login Successful

D:\JavaProgram> __

Summary

In this chapter you have learned what is logical operator or conditional operator in Java. Mostly And(&&), Or(||) and Not(!) is considered as logical operator in Java. In the next chapter you will learn about Ternary Operator in Java.

Relational Operator in Java with Programming Example

In this chapter you will learn:8325088a1445ee08c9faac1a517e4d59

  1. What is relational operator in Java?
  2. What is the symbol of relational operator?
  3. What does relational operator do?
  4. Programming example of relational operator in Java

What is relational operator in Java?

Relational operator is the operator which compares two operands to check whether it is equal, greater than, less than or not equal to another operands.

Operator Description Example
== equal to: compare two operands and check whether it is equal num1 == num2
!= not equal to: compare two operands and check whether it is not equal num1 != num2
> greater than: compare two operands and check whether left operand is greater than right operand num1 > num2
>= greater than or equal to: compare two operands and check whether left operand is greater than or equal to right operand num1 >= num2
< less than: compare two operands and check whether left operand is lesser than right operand num1 < num2
<= less than or equal to: compare two operands and check whether left operand is lesser than or equal to right operand num1 <= num2
What does relational operator do?

You can say relational operator is comparative operator. When you have two operands and you need to check whether it is equal or not, you need equal to (==) relational operator. Relational operator is mostly used with IF conditional constructs and returns Boolean value (true or false).

Programming Example:

class RelationalOperator
{
  public static void main(String[] args)
  {
    int num1, num2;
    num1=20;
    num2=30;
    
    if(num1==num2)
    {
      System.out.println("num1 is equal to num2");
    }
    if(num1!=num2)
    {
      System.out.println("num1 is not equal to num2");
    }
    
    if(num1<num2) {="" system.out.println("num1="" is="" less="" than="" num2");="" }="" if(num1="">num2)
    {
      System.out.println("num1 is greater than num2");
    }
  }
}

Output

D:\JavaProgram>javac RelationalOperator.java

D:\JavaProgram>java RelationalOperator
num1 is not equal to num2
num1 is less than num2

D:\JavaProgram> __

Summary

In this chapter you have learned what relational operator, their symbol is and how they work. You have also seen a complete programming example demonstrating relational operator. In the next chapter you will learn about logical operator in java.