Java Basics

Main Method, System.out.println(), Java Areas, Variables, Default Values & Scanner

Prepared By Krishna Srikanth

1. Levels in Java

The source notes four levels at which Java members and code can be considered:

Data Member Level

Variables or fields belonging to a class.

Member Function Level

Methods defined inside a class.

Class Level

The class as the logical unit containing members and behavior.

Block Level

A group of statements enclosed in braces.

Java Basics source page 1

2. About main() Method

Every Java program execution starts with the main() method. To run a Java program, the source states that JRE must be installed in the system.

Basic Signature

public static void main(String[] args) {
    // statements
}

At runtime, the JVM searches for the main method using the expected prototype:

public static void main(String args[])

Meaning of Each Part

PartMeaning
publicCan be called from anywhere.
staticCan be invoked without creating an object.
voidThe main() method returns nothing.
String[] argsPasses an array of String arguments/parameters.

3. main() Method Signature Forms

The order of the modifiers is not required to be fixed, and the String array can be declared in acceptable equivalent forms.

public static void main(String… args)
public static void main(String args[])
public static void main(String[] args[])
public static void main(String []args)
static public void main(String args[])
Important: The source emphasizes that the JVM looks for the required main-method entry point at runtime. Incorrect forms can lead to a runtime "no such method: main" error.

Summary from the Source

  • The main() method is a static method.
  • You can overload main() in Java.
  • You cannot override main() in Java.
  • The main method can be declared final, strictfp, or synchronized.
  • You cannot call a non-static method directly from a static main method without an object.
  • The JVM creates a main thread to execute the main method.
main method signatures and examples from source PDF

4. About System.out.println()

The source breaks System.out.println() into its Java components.

System

System is a class containing useful class fields and methods. It cannot be instantiated.

out

out is a field of type PrintStream and represents the standard output stream.

println()

println() is a method in the PrintStream class.

Field Summary

FieldDescription
static PrintStream errThe standard error output stream.
static InputStream inThe standard input stream.
static PrintStream outThe standard output stream.

Typical Output Statement

System.out.println(data);

The source explains that out is already open and ready to accept output data, typically corresponding to display output or another destination specified by the host environment.

System.out.println explanation from source PDF

5. Areas of Java Language

The source divides the Java runtime areas into two broad categories:

Instance Area

Contains instance variables and instance methods. Instance members generally require an object for access from a static context.

Static Area

Contains static variables and static methods. Static members can be accessed without creating an object.

Access idea: Static members can be accessed directly from static code, while instance members are accessed by creating an object and using its reference.
Instance area and static area diagram from source PDF

6. Java Variables

Variables are used to hold values that help achieve application requirements and functionality. When declaring a variable, its data type must be specified.

Three Types of Variables in Java

1. Local Variables

Declared inside a method, constructor or block.

2. Instance Variables

Declared inside a class and outside methods.

3. Static Variables

Declared inside a class and outside methods using the static modifier.

7. Local Variables

Variables declared inside a method, constructor or block are called local variables.

  • They can be used only inside the method, constructor or block in which they are declared.
  • They cannot be accessed directly from outside that method, constructor or block.
  • Memory is allocated when the method or constructor starts and released when it completes.
  • The source states that local variables are stored in stack memory.

Example

class Test {
    public static void main(String[] args) {
        int a = 10;   // local variable
        int b = 20;   // local variable

        System.out.println(a);
        System.out.println(b);
    }
}
Local and instance variable examples from source PDF

8. Instance Variables

Variables declared inside a class and outside methods are called instance variables.

  • They are visible in the methods and constructors of the particular class.
  • Instance variables are also known as non-static fields.
  • They have class-wide visibility within the object context.
  • They are accessed using an object/reference variable.
  • Memory is allocated when the object is created.
  • The source states that instance variables are stored in heap memory.

Example

class Test {
    int a = 10;
    int b = 20;

    public static void main(String[] args) {
        Test t = new Test();

        System.out.println(t.a);
        System.out.println(t.b);

        t.m1();
    }

    void m1() {
        System.out.println(a);
        System.out.println(b);
    }
}

9. Static Variables

Variables declared inside a class and outside methods with the static modifier are called static variables.

  • Static variables are visible to the methods and constructors of the class.
  • Static members can be accessed using the class name.
  • The source states that memory is allocated when the .class file is loaded and released when it is unloaded.
  • The source describes static variables as being stored in non-heap memory.

Example

class Test {
    static int a = 1000;
    static int b = 2000;

    public static void main(String[] args) {
        System.out.println(a);
        System.out.println(b);

        Test t = new Test();
        t.m1();
    }

    void m1() {
        System.out.println(a);
        System.out.println(b);
    }
}
Static variables and access methods from source PDF

10. Accessing Static Variables

The source gives three ways to access static members inside static code:

  1. Directly
  2. Using the class name
  3. Using a reference variable

Example

class Test {
    static int x = 100;

    public static void main(String[] args) {
        System.out.println(x);        // 1. directly
        System.out.println(Test.x);   // 2. using class name

        Test t = new Test();
        System.out.println(t.x);      // 3. using reference variable
    }
}
Best practice: Static members are normally accessed using the class name because that clearly communicates that the member belongs to the class rather than an individual object.

11. Variables vs Default Values

Case 1: Instance Variables

For instance variables, the JVM provides default values based on their data types.

class Test {
    int a;
    boolean b;

    public static void main(String[] args) {
        Test t = new Test();

        System.out.println(t.a);
        System.out.println(t.b);
    }
}

Case 2: Static Variables

For static variables, the JVM also provides default values based on their data types.

class Test {
    static int a;
    static float b;

    public static void main(String[] args) {
        System.out.println(Test.a);
        System.out.println(Test.b);
    }
}

Case 3: Local Variables

The JVM does not provide default values for local variables before use. A local variable must be initialized before it is read; otherwise the compiler reports an error such as variable a might not have been initialized.

class Test {
    public static void main(String[] args) {
        int a, b;

        System.out.println(a);  // compilation error
        System.out.println(b);  // compilation error
    }
}
Default values for instance static and local variables from source PDF

12. Instance vs Static Variables

FeatureInstance VariableStatic Variable
DeclarationInside class and outside methods, without static.Inside class and outside methods, with static.
MemorySeparate memory for every object.One shared copy for the class.
AllocationWhen an object is created.When the class is loaded.
AccessUsing object/reference variable.Using class name, and can also be referenced through an object.
StorageHeap memory.Source describes it as non-heap memory.
Effect of changesOne object's value is independent of another object's instance value.All objects use the same static value.
Example: If 10 objects are created, each object has its own copy of an instance variable, while all 10 objects share one copy of a static variable.
Instance versus static variables and class versus object notes from source PDF

13. Class vs Object

Class

  • A logical entity.
  • Contains logic and defines the structure/behavior.
  • Acts as a blueprint for objects.
  • Memory for object data is associated with object creation.

Object

  • A physical/runtime entity representing allocated memory.
  • Created based on a class blueprint.
  • Multiple objects can be created from one class.
  • Each object requires its own memory.
Analogy from the source: A civil engineer's house blueprint can be used to build multiple houses. The class is the blueprint, while each object is an individual house.

14. Characteristics of Variables

Characteristic Local Variable Instance Variable Static Variable
Where declared Inside method, constructor or block. Inside class, outside methods. Inside class, outside methods with static.
Use Within the method, constructor or block. Throughout the class using the object/reference context. Throughout the class using the class context.
Lifetime Created when method/constructor starts; destroyed when it exits. Created when object is created; destroyed when object is destroyed. Created when program/class is loaded; destroyed when the class/program ends or unloads.
Initial value No default value; must initialize before first use. Default value supplied by JVM based on data type. Default value supplied by JVM based on data type.
Object creation Not related to object creation. One copy per object. One shared copy for all objects.
Accessing Directly within its scope. Using object name/reference variable. Using class name.
Memory Stack memory. Heap memory. Source describes it as non-heap memory.
Variable characteristics table from source PDF

15. java.util.Scanner — Dynamic Input

The source introduces the Scanner class for taking dynamic input from the keyboard.

  • Scanner is present in the java.util package.
  • The source notes that Scanner was introduced in Java 1.5.
  • It is used to take dynamic input from the keyboard.

Create Scanner Object

Scanner s = new Scanner(System.in);

Common Scanner Methods

MethodPurpose
s.nextInt()Reads an integer.
s.nextFloat()Reads a float.
s.nextByte()Reads a byte.
s.next()Reads the next token/string.
s.nextLine()Reads a complete line.
s.close()Closes the input stream.

16. Scanner Program — Dynamic Employee Input

import java.util.*;

class Test {
    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);

        System.out.println("Enter emp hobbies");
        String ehobbies = s.nextLine();

        System.out.println("Enter emp no");
        int eno = s.nextInt();

        System.out.println("Enter emp name");
        String ename = s.next();

        System.out.println("Enter emp salary");
        float esal = s.nextFloat();

        System.out.println("***** emp details *****");
        System.out.println("emp no -------> " + eno);
        System.out.println("emp name -----> " + ename);
        System.out.println("emp sal ------> " + esal);
        System.out.println("emp hobbies --> " + ehobbies);

        s.close();
    }
}
Good practice: Close the Scanner when input is no longer required. The source uses s.close() for this purpose.
Scanner dynamic input continuation from source PDF

17. Quick Revision

TopicKey Point
main()Java program entry point searched for by the JVM.
publicAllows the method to be called from anywhere.
staticAllows invocation without creating an object.
voidIndicates that the method returns no value.
String[] argsArray of String arguments passed to main().
SystemClass containing useful fields and methods.
outStatic PrintStream field representing standard output.
println()PrintStream method used to print output followed by a line break.
Local VariableDeclared inside method/constructor/block; must be initialized before use.
Instance VariableDeclared inside class outside methods; one copy per object.
Static VariableDeclared with static; one shared copy per class.
Default ValuesJVM supplies defaults for instance/static variables, not local variables.
ClassLogical blueprint used to create objects.
ObjectRuntime entity created from a class.
Scannerjava.util class used for dynamic keyboard input.