The Wayback Machine - https://web.archive.org/web/20240623235423/https://www.geeksforgeeks.org/java-basic-syntax/
Open In App

Java Basic Syntax

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Java program is an object-oriented programming language, that means java is the collection of objects, and these objects communicate through method calls to each other to work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and semantics of Java.

Basic terminologies in Java

1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a logical template that share common properties and methods.

  • Example1: Blueprint of the house is class.
  • Example2: In real world, Alice is an object of the “Human” class.

2. Object: The object is an instance of a class. It is an entity that has behavior and state.

  • Example: Dog, Cat, Monkey etc. are the object of “Animal” class.
  • Behavior: Running on the road.

3. Method: The behavior of an object is the method.

  • Example: The fuel indicator indicates the amount of fuel left in the car.

4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables.

Example: Steps to compile and run a java program in a console

javac GFG.java
java GFG

Java




import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
        System.out.println("GeeksforGeeks!");
    }
}


Output

GeeksforGeeks!

Note: When the class is public, the name of the file has to be the class name.

Syntax:

1. Comments in Java

There are three types of comments in Java. 

 i. Single line Comment

// System.out.println("This is an comment.");

ii. Multi-line Comment

/*
    System.out.println("This is the first line comment.");
    System.out.println("This is the second line comment.");
*/

iii. Documentation Comment. Also called a doc comment.

/** documentation */

2. Source File Name

The name of a source file should exactly match the public class name with the extension of .java. The name of the file can be a different name if it does not have any public class. Assume you have a public class GFG.

GFG.java // valid syntax
gfg.java // invalid syntax

3. Case Sensitivity

Java is a case-sensitive language, which means that the identifiers AB, Ab, aB, and ab are different in Java.

System.out.println("GeeksforGeeks"); // valid syntax
system.out.println("GeeksforGeeks"); // invalid syntax because of the first letter of System keyword is always uppercase. 

4. Class Names

i. The first letter of the class should be in Uppercase (lowercase is allowed but discouraged).

ii. If several words are used to form the name of the class, each inner word’s first letter should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are numbers and currency symbols, although the latter are also discouraged because they are used for a special purpose (for inner and anonymous classes).

class MyJavaProgram    // valid syntax
class 1Program         // invalid syntax
class My1Program       // valid syntax
class $Program         // valid syntax, but discouraged
class My$Program       // valid syntax, but discouraged (inner class Program inside the class My)
class myJavaProgram    // valid syntax, but discouraged

5. public static void main(String [] args)

The method main() is the main entry point into a Java program; this is where the processing starts. Also allowed is the signature public static void main(String… args).

6. Method Names

i. All the method names should start with a lowercase letter (uppercase is also allowed but lowercase is recommended).

ii. If several words are used to form the name of the method, then each first letter of the inner word should be in Uppercase. Underscores are allowed, but not recommended. Also allowed are digits and currency symbols.

public void employeeRecords() // valid syntax
public void EmployeeRecords() // valid syntax, but discouraged

7. Identifiers in java

Identifiers are the names of local variables, instance and class variables, and labels, but also the names for classes, packages, modules and methods. All Unicode characters are valid, not just the ASCII subset. 

i. All identifiers can begin with a letter, a currency symbol or an underscore (_). According to the convention, a letter should be lower case for variables.

ii. The first character of identifiers can be followed by any combination of letters, digits, currency symbols and the underscore. The underscore is not recommended for the names of variables. Constants (static final attributes and enums) should be in all Uppercase letters.

iii. Most importantly identifiers are case-sensitive.

iv. A keyword cannot be used as an identifier since it is a reserved word and has some special meaning.

Legal identifiers: MinNumber, total, ak74, hello_world, $amount, _under_value
Illegal identifiers: 74ak, -amount

8. White spaces in Java

A line containing only white spaces, possibly with the comment, is known as a blank line, and the Java compiler totally ignores it.

9. Access Modifiers: These modifiers control the scope of class and methods.

  • Access Modifiers: default, public, protected, private.
  • Non-access Modifiers: final, abstract, static, transient, synchronized, volatile, native.

10. Understanding Access Modifiers:

Access Modifier Within Class Within Package Outside Package by subclass only Outside Package
Private

Yes

No

No

No

Default

Yes

Yes

No

No

Protected

Yes

Yes

Yes

No

Public

Yes

Yes

Yes

Yes

11. Java Keywords

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects. 

abstract

assert

boolean

break

byte

case

catch

char

class

const

continue

default

do

double

else

enum

extends

final

finally

float

for

goto

if

implements

import

instanceof

int

interface

long

native

new

package

private

protected

public

return

short

static

strictfp

super

switch

synchronized

this

throw

throws

transient

try

void

volatile

while

 

 



Previous Article
Next Article

Similar Reads

Abstract Syntax Tree (AST) in Java
Abstract Syntax Tree is a kind of tree representation of the abstract syntactic structure of source code written in a programming language. Each node of the tree denotes a construct occurring in the source code. There is numerous importance of AST with application in compilers as abstract syntax trees are data structures widely used in compilers to
5 min read
Java Exercises - Basic to Advanced Java Practice Programs with Solutions
Looking for Java exercises to test your Java skills, then explore our topic-wise Java practice exercises? Here you will get 25 plus practice problems that help to upscale your Java skills. As we know Java is one of the most popular languages because of its robust and secure nature. But, programmers often find it difficult to find a platform for Jav
7 min read
Basic Type Base64 Encoding and Decoding in Java
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss.(Base 64 format reference).The Basic encoding means no line feeds are added to the output and the output is mapped to a set of characters in A-Za-z0-9+/ character set and
2 min read
Basic Calculator Program Using Java
Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user input. Example: Enter the numbers: 2 2 Enter the operator (+,-,*,/) + The final result: 2.0 + 2.0 = 4.0ApproachTake two numbers using the Scanner class. The switch case branching is used to execute
2 min read
Java Program to Get the Basic File Attributes
Basic File Attributes are the attributes that are associated with a file in a file system, these attributes are common to many file systems. In order to get the basic file attributes, we have to use the BasicFileAttributes interface. This interface is introduced in 2007 and is a part of the nio package. The basic file attributes contain some inform
3 min read
Basic Calculator Program in Java Using if/else Statements
We will be creating a basic calculator in java using the nested if/else statements which can perform operations like addition, subtraction, multiplication, division, and modulo of any two numbers. We will be defining the numbers as an integer but if you want the decimal side of numbers as well feel free to initiate them as double or float. Let's se
2 min read
Java OpenCV Programs - Basic to Advanced
Java is a popular programming language that can be used to create various types of applications, such as desktop, web, enterprise, and mobile. Java is also an object-oriented language, which means that it organizes data and behaviour into reusable units called classes and objects. Java is known for its portability, performance, security, and robust
2 min read
Java Threading Programs - Basic to Advanced
Java threading is the concept of using multiple threads to execute different tasks in a Java program. A thread is a lightweight sub-process that runs within a process and shares the same memory space and resources. Threads can improve the performance and responsiveness of a program by allowing parallel execution of multiple tasks. Java threading pr
3 min read
Java Regex Programs - Basic to Advanced
In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Regular Expressions in Java are provided under java.util.regex package. This consists of 3 classes and 1 interface. In Java Interviews, Regex questions are generally asked by Int
5 min read
Basic Operators in Java
Java provides a rich operator environment. We can classify the basic operators in java in the following groups: Arithmetic OperatorsRelational OperatorsBitwise OperatorsAssignment OperatorsLogical Operators Let us now learn about each of these operators in detail. 1. Arithmetic Operators: Arithmetic operators are used to perform arithmetic/mathemat
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg