on Leave a Comment

Scanner Class in Java

Scanner class is used to read input from keyboard. Scanner is class in java.util package. Scanner class provides many methods to read and parse primitive values. Scanner breaks the input into tokens using delimiter which is by default whitespaces. 

To read input from keyboard, we have to make an object of Scanner class by passing predefined object called System.in.

Example:

Scanner sc = new Scanner(System.in);

Here sc is object of Scanner class and System.in represents the standard input stream.

In java.util package, Scanner class extends Object class and implements Iterator and Closeable interfaces.

Methods in Scanner Class

There are many methods in Scanner class but most commonly used methods are:

1. next() is used to take single word input
2. nextInt() is used to take integer input
3. nextFloat() is used to take float input
4. nextDouble() is used to take double input
5. nextLong() is used to take long input
6. nextShort() is used to take short input
7. nextLine() is used to take string input
8. nextBoolean() is used to take boolean input

next().charAt(0). is used to read a single character.

Example of Java Scanner Class

import java.util.Scanner;
class ScannerExample{
 public static void main(String[] args) {
  Scanner sc = new Scanner(System.in);

  System.out.print("Enter a String : ");
  String s = sc.nextLine();
  System.out.println("You have entered "+s);

  System.out.print("\nEnter Integer Value : ");
  int a = sc.nextInt();
  System.out.println("You have entered "+a);

  System.out.print("\nEnter Character Value : ");
  char c = sc.next().charAt(0);
  System.out.println("You have entered "+c);
 }
}

Output:


Enter a String : Java
You have entered Java

Enter Integer Value : 10
You have entered 10

Enter Character Value : B
You have entered B



on 1 comment

Multiple Inheritance in Java

Multiple inheritance is a concept of object oriented programming. In multiple inheritance, a class inherits the properties of two or more class. But java does not support multiple inheritance because of some issues. When both parent classes overrides the same method and child class object is calling that method, then compiler does not know which class method is to be called and which class to give high priority.
Multiple Inheritance
Multiple Inheritance

It will show error because one class trying to extending two classes.

// First Parent class
class ParentClass1
{
    void show()
    {
        System.out.println("ParentClass1");
    }
}
 
// Second Parent Class
class ParentClass2
{
    void show()
    {
        System.out.println("ParentClass2");
    }
}
class SubClass extends ParentClass1, ParentClass2{
 public static void main(String[] args) {
  SubClass obj = new SubClass();

  obj.show();
 }
}

Output:

SubClass.java:18: error: '{' expected
class SubClass extends ParentClass1, ParentClass2{
                                   ^
1 error

Multiple Inheritance by Interfaces

In java, one class can implements two or interfaces. This also does not cause any ambiguity because all methods declared in interfaces are implemented in class.

Example:

interface Interface1
{
   public void show();
}
interface Interface2
{
   public void show();
}
class SubClass implements Interface1, Interface2
{
   public void show()
   {
       System.out.println("A class can implements more than one interfaces");
   }
   public static void main(String args[]){
    SubClass obj = new SubClass();
    obj.show();
   }
}

Output:

A class can implements more than one interfaces


on Leave a Comment

OSI Model: Application Layer and its Functions

In OSI model, application layer is the top most layer. The application layer user interface to enable user to access the network, user may be either human or software. Application layer contains communication protocols and interface to perform process to process communication on network.  Application layer acts as the user interface responsible for displaying received information to the user. Application layer supports many services such as electronic mail, remote file access and transfer, shared database system, directory services, network resource etc.

Functions of Application Layer

Network Virtual Terminal: Network virtual terminal allows user to log on to a remote host. Application creates a software emulation of a terminal at the remote host. User communicates with the software terminal which in turn communicates with the host and vice versa. The remote host assumes that it is communicating with one of its own terminals and allows user to log on.

File Transfer, Access and Management: The application layer allow user to access files in a remote host. User can make changes in files and read data from the file. 

Mail Services: The application layer provides services like E-mail forwarding and storage.

Directory Services: It provides distributed database sources and access for global information about various services.





on Leave a Comment

Java Program to Open Notepad

This java program opens notepad by Runtime class. Notepad is an application comes with Windows operating system. Notepad is text editor. In this program, we create an object of Runtime class and calling exec() method by passing parameter as application name. 

Java Program to Open Notepad

import java.util.*;
import java.io.*;
 
class OpenNotepad {
  public static void main(String[] args) {
   System.out.println("Opening Notepad...");
    Runtime rt = Runtime.getRuntime();
 
    try {
      rt.exec("notepad");
    }
    catch (IOException e) {
      System.out.println(e);
    }   
  }
}

Output:

Opening Notepad...

Java Program to Open Notepad
Notepad




on Leave a Comment

Static and Dynamic Binding in Java

Binding is the association of method call to method body. Binding can be done at compile time and run time. Compile time binding is known as static binding and run time binding is known as dynamic binding.

Static Binding

In static binding, method call is associated with method body at the compile time. When we overload methods, it is important to resolve binding. In case of overloaded methods, binding is resolved at compile time. But we override method, binding cannot be resolved at compile time. Static binding uses only Type information for binding. Binding of methods such as static, private and final is always static binding. Because static, private and final methods cannot be overridden, so they can be only called by object of local class (static method is called by class name). So, binding of static, private and final method needs only Type information.

Example

class ParentClass{
    static void show(){
        System.out.println("Parent Class");
    }
}
public class ChildClass extends ParentClass {
    static void show(){
        System.out.println("Child Class");
    }
    public static void main(String[] args){
        ParentClass obj1 = new ChildClass();
        ParentClass obj2 = new ParentClass();
        obj1.show();
        obj2.show();
    }
}

Output:

Parent Class
Parent Class

Dynamic Binding

Dynamic binding is done at run time. When both parent class and child class defines the same method, in this case object type determines which method to call. And type of object is determined at run time. So, binding of overridden methods is always a dynamic binding.

Example

class ParentClass{
    void show(){
        System.out.println("Parent Class");
    }
}
public class ChildClass extends ParentClass {
    void show(){
        System.out.println("Child Class");
    }
    public static void main(String[] args){
        ParentClass obj1 = new ChildClass();
        ParentClass obj2 = new ParentClass();
        obj1.show();
        obj2.show();
    }
}

Output:

Child Class
Parent Class



on Leave a Comment

Java Program to Find the Largest of Three Numbers

In this article we'll see how to find largest of three numbers in java. 

We will see, Java program to find the largest of three numbers using
(1) If-Else..If Statement
(2) Nested If..Else Statement

Example 1: Java Program to Find the Largest of Three Numbers Using If-Else..If Statement

import java.util.Scanner;
public class LargestOf3{

    public static void main(String[] args) {

        int a, b, c;
        Scanner read = new Scanner(System.in);
        System.out.print("Enter Three Numbers: ");
        a = read.nextInt();
        b = read.nextInt();
        c = read.nextInt();
        
        if( a >= b && a >= c)
            System.out.println(a + " is the largest number.");

        else if (b >= a && b >= c)
            System.out.println(b + " is the largest number.");

        else
            System.out.println(c + " is the largest number.");
    }
}

Output:

Enter Three Numbers: 10 20 30
30 is the largest number.

Example 2: Java Program to Find the Largest of Three Numbers Using Nested If..Else Statement

import java.util.Scanner;
public class LargestOf3{

    public static void main(String[] args) {

        int a, b, c;
        Scanner read = new Scanner(System.in);
        System.out.print("Enter Three Numbers: ");
        a = read.nextInt();
        b = read.nextInt();
        c = read.nextInt();

        if(a >= b) {
            if(a >= c)
                System.out.println(a + " is the largest number.");
            else
                System.out.println(c + " is the largest number.");
        }
        else {
            if(b >= c)
                System.out.println(b + " is the largest number.");
            else
                System.out.println(c + " is the largest number.");
        }
    }
}

Output:

Enter Three Numbers: -10 0 10
10 is the largest number.




on Leave a Comment

Java Program to Add Two Matrices

This java program adds two matrices. First, user enters elements of two matrices, then addition of both matrices is performed using for loop. Finally sum of both matrices is displayed on the screen.

Java Program to Add Two Matrices

import java.util.Scanner;
class AddMatrices
{
 public static void main(String[] args) {
 int a[][] = new int[3][3];
        int b[][] = new int[3][3];
        int c[][] = new int[3][3];
 int i, j;
 Scanner read = new Scanner(System.in);
 System.out.print("Enter the elements of matrix1: ");
 for(i = 0; i<a.length; i++)
 for (j = 0; j<a.length; j++) {
  a[i][j] = read.nextInt();
 }

 System.out.print("\nEnter the elements of matrix2: ");
 for(i = 0; i<b.length; i++)
  for (j = 0; j<b.length; j++) {
   b[i][j] = read.nextInt();
  }

 System.out.println("\nAdding matrix1 and matrix2...");
 for(i = 0; i<b.length; i++)
  for (j = 0; j<b.length; j++) {
   c[i][j] = a[i][j] + b[i][j];
  }

 System.out.println("\nSum of matrix1 and matrix2 is:");
 for(i = 0; i<c.length; i++){
                for(j = 0; j<c.length; j++){
                        System.out.print(c[i][j]+ "\t");
                }
                System.out.println();
        }
 }
}

Output:

Enter the elements of matrix1: 1
2
3
4
5
6
7
8
9

Enter the elements of matrix2: 1
2
3
4
5
6
7
8
9

Adding matrix1 and matrix2...

Sum of matrix1 and matrix2 is:
2       4       6
8       10      12
14      16      18


on Leave a Comment

OSI Model: Presentation Layer and its Functions

Presentation layer is layer 6 of OSI model. Presentation layer concern about the syntax and semantics of information exchanged between systems. Presentation layer is also known as data translate because it translates the data in such a way the receiver will understand the data. After formatting the data, presentation layer passes data to the application layer for further processing and display. There are many other important functions of presentation layer.

Functions of Presentation Layer

Translation: Communicating systems exchange information of different formats such as string, numbers and so on. Presentation layer converts this information into bit stream before transmitting. The presentation layer on receiver converts these data into receiver-dependent format.

Encryption: To ensure privacy, presentation layer perform encryption at transmitter side and decryption at the receiver side.

Compression: The presentation layer performs compression to reduce the bits contained in the information. It reduces the bandwidth of information. Compression is important for transmitting multimedia such as text, audio and video.



on Leave a Comment

Java Array (With Examples)

An array is a data structure, which stores related data items. An array is a group of contiguous data items that shares a common name. If we need a set of variables to store same type of data, instead of defining many variables, we can simply define an array. The individual value in array is known as element.

Advantage of Java Array

- Provides ability to develop concise and efficient program.
- It provides random access. We can access any data at any index.

Disadvantage of Java Array

- We need to know in advance the size of array.
- The memory allocated to array can not be increased or decreased dynamically.

Types of Java Array

- Single Dimensional Array
- Multi-Dimensional Array

Single Dimensional Array

A single dimensional array is array in which list of items is stored under a single name using one subscript.

Declaration of Single Dimensional Array

Syntax:

datatype[] array-name;
or
datatype array-name[];

Example:

int[ ] arr;
char [ ]arr;
short arr[ ];

Instantiation of Java Array

Example:

float []arr = new float[20];

Accessing Array Element

Array index start from 0. We can access array element using indexes. 

Syntax:

array-name[n-1];

Example:

float[] arr = {1.1, 2.2, 3.3, 4.4, 5.5};

If we want to access the 5th element of above array. Then we write following code.

System.out.println("Value of 5th Element is " + arr[4]);


Example of Single Dimensional Java Array

In this java program, we declare, instantiate and access single dimensional array.

public class OneDArray{
 public static void main(String[] args) {
  int[] arr; //Declaration
  arr = new int[5]; //Instantiation
  arr[0] = 10;
  arr[1] = 20;
  arr[2] = 30;
  arr[3] = 40;
  arr[4] = 50;

  for(int i = 0; i<arr.length; i++)
   System.out.println("Value of Element"+i+" is "+arr[i]);
 }
}


Output:

Value of Element0 is 10
Value of Element1 is 20
Value of Element2 is 30
Value of Element3 is 40
Value of Element4 is 50

Multi-Dimensional Array

A multi-dimensional array can have multiple rows and multiple columns. 

Declaration of Multi-Dimensional Array

Syntax:

dataType[][] array-name; or   
dataType array-name[][]; or  
dataType []array-name[];

Instantiation of Multi-Dimensional Array

Example:

int[][] arr=new int[5][5]; 
float array-name[5][5]; or  
char [5]array-name[5];

Initialization of Multi-Dimensional Array

Example:

arr[0][0]=1;  
arr[0][1]=2;  
arr[0][2]=3;  
arr[0][3]=4;  
arr[0][4]=5;  

Example of Multi-Dimensional java array

public class MultiDArray{
 public static void main(String[] args) {
  int[][] arr = new int[3][3]; //Declaring and Instantiating
  arr[0][0]=1;  //Initializing
  arr[0][1]=2;  
  arr[0][2]=3;  
  arr[1][0]=4;  
  arr[1][1]=5;  
  arr[1][2]=6;  
  arr[2][0]=7;  
  arr[2][1]=8;  
  arr[2][2]=9; 
  for (int i = 0; i<arr.length ; i++) {
   for (int j = 0; j<arr.length; j++) {
    System.out.print(arr[i][j]+"\t");
   }
   System.out.println();
  }
 }
}

Output:

1       2       3
4       5       6
7       8       9



on Leave a Comment

Java Program to Convert Hexadecimal to Decimal

This java program converts hexadecimal value to decimal value. First, user has to enter a hexadecimal number, then we have to convert hexadecimal value to decimal value and finally displayed on the screen.

We can convert hexadecimal to decimal by two ways:

- Using parseInt() method of Integer class
- Without using built-in method

Java Program to Convert Hexadecimal to Decimal Using Integer Class

import java.util.Scanner;
public class HexToDec
{
 public static void main(String[] args) {
 String hex;
        Scanner kb = new Scanner(System.in);
  
        System.out.print("Enter Hexadecimal Number : ");
        hex = kb.nextLine();
        System.out.println("\nConverting...\n");
        Integer dec = Integer.parseInt(hex, 16);
        System.out.print("Decimal Equivalent is " + dec);
 }
}

Output:

Enter Hexadecimal Number : B1

Converting...

Decimal Equivalent is 177

Java Program to Convert Hexadecimal to Decimal without Using Integer Class

import java.util.Scanner;

public class HexToDec
{
    public static void main(String args[])
    {
        String hex;
        int dec = 0;
        Scanner kb = new Scanner(System.in);
  
        System.out.print("Enter Hexadecimal Number : ");
        hex = kb.nextLine();
  
        String digits = "0123456789ABCDEF";
        hex = hex.toUpperCase();
        System.out.println("\nConverting...\n");
        for (int i = 0; i < hex.length(); i++)
        {
          char ch = hex.charAt(i);
          int d = digits.indexOf(ch);
          dec = 16*dec + d;
        }
        System.out.print("Decimal Equivalent is " + dec);
    }
}

Output:

Enter Hexadecimal Number : A8

Converting...

Decimal Equivalent is 168



on Leave a Comment

Java Program to Convert Decimal to Hexadecimal

This java program converts decimal value to hexadecimal value. First, user has to enter a decimal number, then we have to convert decimal value to hexadecimal value and finally displayed on the screen.

Hexadecimal Numerals: Hexadecimal is a base-16 number system. It uses 16 symbols, the symbols 0–9 to represent values zero to nine, and A,B,C,D,E,F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

We can convert decimal to hexadecimal by two ways:

- Using built-in method (toHexString() method of Integer class)
- Without using built-in method

Java Program to Convert Decimal to Hexadecimal Using toHexString() Method

import java.util.Scanner;
class DecToHex
{
    public static void main(String args[])
    {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter Decimal Number : ");
      int dec = scan.nextInt();
        
      System.out.println("\nConverting...\n");
      String hex = Integer.toHexString(dec);
      System.out.println("Equivalent Hexadecimal is "+hex);
    }
}


Output:

Enter Decimal Number : 59

Converting...

Equivalent Hexadecimal is 3b

Java Program to Convert Decimal to Hexadecimal without Using Built-in Method

import java.util.Scanner;
class DecToHex
{
   public static void main(String args[])
   {
     Scanner scan = new Scanner( System.in );
     System.out.print("Enter Decimal number : ");
     int dec = scan.nextInt();
     int rem;
     String disp=""; 

     // Digits in hexadecimal number system
     char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
     System.out.println("\nConverting...\n");
     while(dec!=0)
     {
       rem = dec%16; 
       disp = hex[rem]+disp; 
       dec = dec/16;
     }
     System.out.println("Equivalent Hexadecimal is "+disp);
  }
}


Output:


Enter Decimal number : 61

Converting...

Equivalent Hexadecimal is 3D



on Leave a Comment

Continue Statement in Java

The continue statement can be used with loop control statement such as for loop, while loop and do-white loop. If we want to skip some statements in a loop, continue statement can be used. The continue statement can be written anywhere inside a loop body. When continue statement is encountered inside a loop, control jumps to the end of the loop and test expression is evaluated. In case of for loop, update statement is executed and then test expression is evaluated. 

Syntax of continue statement

continue;

Example of java continue statement

class ContinueStatement
{
 public static void main(String[] args) {
  int i;
  for (i =1; i<=10 ; i++) {
   if(i==5 || i==6){
    continue;
   }
   System.out.println(i);
  }
 }
}

Output:

1
2
3
4
7
8
9
10

When i = 5 or i = 6, continue statement is executed and control jump to the update statement of for loop. This is the reason why 5 and 6 is printed.

Continue Statement with Inner Loop

If continue statement is encountered in inner loop, then it continues only inner loop. And test expression is evaluated of inner loop. In case of for loop, update statement of inner loop is evaluated and then test expression is evaluated. 

Example:

class ContinueStatement
{
 public static void main(String[] args) {
  int i, j;
  for (i = 1; i<=5 ; i++) {
   for (j = 1; j<=5; j++) {
    if(i>3 && j>3){
      continue;
       }
       System.out.println("i = "+i+"  "+"j = "+j);
   }   
  }
 }
}

Output:

i = 1  j = 1
i = 1  j = 2
i = 1  j = 3
i = 1  j = 4
i = 1  j = 5
i = 2  j = 1
i = 2  j = 2
i = 2  j = 3
i = 2  j = 4
i = 2  j = 5
i = 3  j = 1
i = 3  j = 2
i = 3  j = 3
i = 3  j = 4
i = 3  j = 5
i = 4  j = 1
i = 4  j = 2
i = 4  j = 3
i = 5  j = 1
i = 5  j = 2
i = 5  j = 3

When (i>3 && j>3) condition holds true, then value of i and j is not displayed. Otherwise, value of i and j is displayed.


on Leave a Comment

Java Break Statement with Examples

The java break statement is a control statement and it is used to break the current flow of a program. The break statement can be used within both flow control statement and decision making statement. 

If a break statement is encountered in a loop, it causes the loop to terminate immediately and the control passes at the next statement following the loop. If break statement is encountered in inner loop, it breaks only inner loop.

The break statement can be used to break a decision making statement like if statement, if...else statement, nested if statement and switch statement.

In switch case, break statement can be used to terminate a case.

Syntax of break statement

break;

Example of break statement

class BreakStatement
{
 public static void main(String[] args) {
  int i;
  for (i =0; i<=10 ; i++) {
   if(i==6){
    break;
   }
   System.out.println(i);
  }
 }
}

Output:

0
1
2
3
4
5