Showing posts with label Java for base. Show all posts
Showing posts with label Java for base. Show all posts

Wednesday, February 20, 2019

Lesson 6 – Global variable, local variable

A declaration variable has valid inside open and close bracket contain it.
Create new class name six.
Copy in to class.
static int number=10;
public static void main(String args[]) {     
    
System.out.println("Value of nunmber is : "+number);
         
}
Run to see Console screen show number 10.

Add to main and run again.
int number=8;

Now  screen show 8, variable number in main and number outside are different, the outsider call global variable, insider call local variable.
A variable declare after Class open bracket will be global variable, it will colored blue. Local variables will have black color.
Local variable only valid in it ‘s open and close bracket.
Add in to main.
int b=5;
Add to outside main.
int a=so+b;
Eclipse say it doesn’t know b, because b only valid in main, it has black color mean local variable.

Variable a has blue color because it is global variable.
Now cut and move b to top near first open bracket, it become global variable and has blue color.

When start to learn programme you should not name local variable the same with global variable to avoid mistaken when use them later.

When declare a new variable, if it color blue we know it is global variable, no need to see brackets.

Lesson 5 - Try catch

Create a new class name five.
Type these lines.
public static void main(String args[]) {
          int so=0;     
          so=Integer.parseInt("88"); 

          System.out.println("Integer number is: "+so);   
 
          int c=10+so;
          System.out.println("Sum result is: "+c);
}
Run to see result.

We cast a String to number, if for some reason, we can’t do this and get an error, programme will crash.
Add  text to string want to cast, for example, “88a”, run and see.

Eclipse show exception error.
To avoid this, Java use try catch to prevent programme from crash.
Add try catch to that code.
public static void main(String args[]) {
          int so=0;
     try{                
          so=Integer.parseInt("88a"); 

     System.out.println("Integer number is: "+so);   
     } catch (Exception e) {       
     System.out.println("Error when cast string to number");
     }
     int c=10+so;
     System.out.println("Sum result is: "+c);}

When we run, programme print the line Sum result is: 10”, and the error notification we type before.
This different with there no try catch, programme can’t print anything.
When command in try get error, comand in catch run, other codes outside try catch run normally.
Remove text add to cast string, run again.

In Android, if codes need try catch, it will recommend we to add.

But sometime we have to add ourself, for example, get year from Edittext, if user enter invalid number, we use try catch to inform them.