Search Java Tutorials

Custom Search

What You Will Want to Complete This Tutorial?

You must have at least 1st and 2nd pre-requirements to start the tute. Other requirements will require for last chapters only. These all are free to use and download!
  1. Java Development Kit Standard Edition (JDK / J2SE) Any Version(www.java.com)
  2. Any Text Editor (Note Pad quite enough or get Notepad++ from (http://notepad-plus.sourceforge.net)
  3. Java Run Time Environment (JRE) Any Version(www.java.com)
  4. Java Enterprise Edition (J2EE) for advanced developing (For last few chapters)(www.java.com)
  5. Java Wireless Toolkit for Mobile Application Development (For Mobile Application Development Chapters) (www.java.com)
  6. Tomcat Web Server to run Servlets. (www.tomcat.apache.org/)
Your operating system may be any version of Windows.
What will you learn (As a summary)?
  1. How to build console and windowed applications using Java
  2. How to build web page elements with Java Applets
  3. How to build Database Programs with Java
  4. How to build enterprise applications with Beans
  5. How to add Email functions to Java programs
  6. How to program smart devices (Phone, PDA etc…) with Java

Blocks and Scopes in Java

Within any class or method, the code between a pair of curly braces is called a block. When you declare a variable within a block, you can not reference that variable outside the block. The portion of a program within which you can reference a variable is the ‘Variables scope’.

Sample Program:
Case: This program defines a variable called ‘x’ inside main method. The scope of the variable x starts with its declaration and must be ends with main method closing curly brace. You can retrieve its value on that scope, but you can’t do it out f scope. So, when you compile program you’ll get “Cannot resolve symbol” error in line 12 which is out of scope of variable ‘x’.

public class VariableScope
{
public static void main(String[] args)
{
//scope of the main method starts
int x = 12;
System.out.println("x is: " + x);
anOtherMethod();
}
//scope of the main method ends

public static void anOtherMethod()
{
//scope of the anOtherMethod starts
System.out.println("x is: " + x);
}
//scope of the anOtherMethod ends
}


This is the output:



Now take a look at this, you may define two variables in different scopes and the variables may overlap.

public class OverlapScope
{
public static void main(String[] args)
{
int x = 55;
System.out.println("main method:- x is: " + x);
overlap();
System.out.println("main method:- x is: " + x);
}

public static void overlap()
{
int x = 66;
System.out.println("overlap method:- x is : " + x);
}
}


The output is:




Even the variable names overlapped, java knows keep in track both variables separately. This is also known as nesting variables.

No comments: