How to use Java variable scopes?
Also methods & constructors.
/**
* Author : DarkL0rd
* Created : 8 Jan 2023 Sunday
* Define : Variable Scopes
*/
public class ScopeDemo {
public static void main(String[] args) {
//Invoking
Demo demo = new Demo();
demo.doSomething("Hello");
}
}
/**
* Class
*
*/
class Demo {
//Constructor - Second Working
Demo() {
System.out.println("Constructor : Body : " + body);
}
//Method - Third Working
//In Method there is no []
void doSomething(String args) {
System.out.println("Method : Body : " + body);
//For Loop
// for( int i = 0; i < 10; i ++) {
// System.out.println("For Loop : Body : " + body + i);
// }
}
int body = 1;
{
String name = "Block Variable Code";
//Code Block - First Working
System.out.println("Code Block : Body : " + body + name);
}
}
Methods in Java. Keep learning and stay at home.
public class Methods {
public static void main(String[] args) {
}
// Return Type
// Method Name
// Arguments
// Method Body
void hello() {
System.out.println("Hello Dude!");
}
void hello(String name) {
}
void hello(String name, int count) {}
// Vararges (Variable Arguments) Java 5
// Last Parameter, We cant write anything behind varargs
void hello(String ... names) {}
void hello(int count, String ... names) {}
//Method Name + Arguments List = Method Signature
int add(int a, int b) {
return '0';
}
}
Constructors in Java.
// Static Variable hiding global scope or local scope ?
public class Constructor {
public static void main(String[] args) {
//Variable Assign
Hello hello;
//Invoke a Constructor with int type
hello = new Hello(5);
hello.greet();
}
}
class Hello {
//Global Scope Variable
int count;
//Constructor Method with int type
//Constructor Scope, Local Scope
//Global Scope define in Const Method
//Variable hiding need this keywords to invoke
Hello(int count) {
this.count = count;
}
void greet() {
for (int i=0; i < count; i++) {
System.out.println("Hello Java");
}
}
}
Thanks for tomorrow !
Better than Others, Harder than Ever.