Variable Declaration in Java

Declaring variables in Java

Just like in C or C++, Java allows you to declare variables using a familiar syntax:

type variableName;

Here, type is the data type which a variable will hold.

Example

Here’s a simple program that demonstrates variable declaration and usage:


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);
 }
}

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

Notes

  • System.out.println() prints with a new line.
  • System.out.print() prints on the same line.

Comments

Popular posts from this blog

Develop an Android application to display “Hello World!” on screen

Program to design an applet which draws a circle (having color BLUE) inside a triangle (having color YELLOW)

Build a Simple Android App to Display Student Details