Java Basics: Basic
Syntax
Programming Fundamentals in Java
Java Package
Refers to the grouping of classes and/or subpackages.
Its structure is similar to that of a directory
syntax:
package <packagename>;
Import Statements
Import statement is a way of giving the proper
location for the compiler to find that particular class
Syntax to load all classes available in
<java_installation>/java/lang:
import java.lang.*;
Syntax to load System class available in
<java_installation>/java/lang:
import java.lang.System;
Java Variables
▪ Instance Variables: Instance variables are
variables within a class but outside any method.
These variables are initialized when the class is
instantiated. Instance variables can be accessed
from inside any method, constructor or blocks of
that particular class.
syntax:
<modifier> <datatype> <variablename> [=
<defaultvalue>];
Java Variables
▪ Class Variables: are variables declared within a
class, outside any method, with the static keyword
syntax:
<modifier> static <datatype> <variablename> =
<value>;
Java Variables
▪ Local Variables: variables defined inside
methods, constructors or blocks are called local
variables. The variable will be declared and
initialized within the method and the variable will be
destroyed when the method has completed
syntax:
<datatype> <variablename> [= <initialvalue>];
Java Methods
A collection of statements that are grouped together to
perform an operation.
Method
syntax: Signature
<modifier> <returnType>
<methodName>(<parameters>){
<statements>;
}
returnType could either be void (if no value is returned) or
data type (if a value is returned by the method).
Java Constructor
special type of method used for creating and initializing
a new object.
syntax:
<modifier> <className>(<parameters>){
<statements>;
}
Java Object
It is an instance of a class. It is created everytime you
instantiate a class with a new keyword.
syntax:
<classname> <objectName> = new
<classConstructor>;
Accessing Members of an Object
It is an instance of a class. It is created everytime you
instantiate a class with a new keyword.
syntax:
<objectName>.
Java Main Program Structure
<package declaration>;
<import declarations>;
public class <classname>{
<global variable declarations>;
public static void main(String[] args){
<local variable declarations>;
<statements>;
}
}
Java Regular Class Structure
<package declaration>;
<import declarations>;
public class <classname>{
<attribute declarations>;
<constructor declarations>;
<method declarations>;
}
Basic Program Structure
Class
main method where the java program
processing starts
Stateme
nt
End of the main
method End of
the
End of the stateme
MyFirstJavaProgram class nt