Variable Declaration In Java

You can declare a variable in Java same as C, C++. It has the same syntax which is given below:
type var-name;

Where type is the data type which a variable will hold. As given in program, println( ) is used to display the string "The value of num : 12"

The print( ) method is same as println( ), except that it does not output a newline character after each call.


PROGRAM
/* 
  This is a second Java program.
  Call this file as "VarDeclDemo.java".
 */

public class VarDeclDemo {

 public static void main(String[] args) {

  int num;  // This declare a variable called num 

  num = 12; // This assigns a value to num
  
  System.out.println("The value of num : " + num);
  
  num = num + 10;
  
  System.out.print("The value of num + 10 : ");
  System.out.println(num);
 }
}

The output of program is as below:

OUTPUT
C:\>javac VarDeclDemo.java
C:\>java VarDeclDemo
The value of num : 12
The value of num + 10 : 22

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative