A Java program is typically structured in the following way:
Package Declaration (Optional):
Import Statements (Optional):
Class Declaration:
Main Method:
public static void main(String[] args)
.Class Body:
Member Variables (Fields):
Methods:
Statements and Expressions:
Here’s an example illustrating the basic structure of a Java program:
package com.example; import java.util.*; public class MyClass { private int myVariable; public static void main(String[] args) { MyClass myObject = new MyClass(); myObject.myMethod(); } public void myMethod() { myVariable = 10; System.out.println("Value of myVariable: " + myVariable); } }
In the above example, we have a class called MyClass
with a member variable myVariable
, a main
method as the entry point of the program, and another method myMethod
that sets the value of myVariable
and prints it to the console.
Copyright ©TechOceanhub All Rights Reserved.