We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11
A simple Java Program, Data
types and variables, Arrays
A simple Java Program • Class a • { • public static void main(String[] args) • { • System.out.println(“Hi”); • } •} • D:\imit\javac a.java • D:\imit\java a Data types and variables • Public class a{ • public static void main(string[] args) • { • int x = 123; • double y =3.14; • boolean z =true; • char symbol=‘@’; • string name=“IMIT”; • System.out.println(“Hello” +name); • } • } Scope and lifetime of a variable • Scope of a variable refers to in which areas or sections of program can the variable be accessed. • Lifetime of a variable refers to how long the variable stays alive in memory. • General convention for a variable’s scope is it is accessible only within the block in which it is declared. • A block begins with a curly braces:- { statements } • Class a • { • public static void main(String[] args) • { • int x; • // Beginning of inner block • { • int y =100; • x = 200; • System.out.println(“x=” +x); • }// End of inner block • System.out.println(“x=” +x); • y=200;//Error as y is not accessible in outer block Variable Type Scope Lifetime Instance variable Through out the Until the object is class except in available in static methods memory Class variable Through out the Until the end of the class program Local variable Within the block in Until the control which it is declared leaves the block in which it is declared Arrays in JAVA • It is used in the same manner as in C and C++. • The creation of array is different from C or C++. • It must be created by using the new operator. • Java supports dynamic array creation. • There is no static array creation in Java. • Syntax: • Datatype arrayname = new Datatype[size]; • int no[] = new int [5]; • Datatype[ ] arrayname = new Datatype[ size]; • int[] no = new int[5];
Datatype arrayname[ ]= {values}
int no[ ] ={1,2,5,6,7}
int n; int no[ ] = new int[n]; • Int x=1; • System.out.println(x); • System.out.println(++x); • System.out.println(x); • Int x=1; • System.out.println(x); • System.out.println(x++); • System.out.println(x); •122 •112