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

Java Basic Syntax

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

To gain a deeper understanding of these concepts and how to implement them in Java programming, consider exploring more detailed resources or comprehensive Java course that cover these fundamentals in depth, helping you to solidify your Java skills.

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



Conclusion

Mastering Java’s basic syntax is essential for any aspiring programmer. It lays the foundation for more advanced concepts and skills. To further enhance your understanding and proficiency, consider enrolling in our Java Course , which offers comprehensive coverage and practical exercises




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
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 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
ProcessBuilder in Java to create a basic online Judge
We have discussed Process and Runtime to create an external process. In this post, ProcessBuilder is discussed which serves the same purpose.Let us understand an application where we need to get source code and find out the language. The application needs a string (containing source code) as input. The application needs to find out the language in
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Spring MVC - Basic Example using JSTL
JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web pages. They can now simply use a tag related to th
8 min read
Spring Security - Basic Authentication
Spring Security is a framework that allows a programmer to use JEE components to set security limitations on Spring-framework-based Web applications. In a nutshell, it’s a library that can be utilized and customized to suit the demands of the programmer. Because it is a part of the same Spring family as Spring Web MVC, it works well together. The m
8 min read
Basic Program in Hibernate
Hibernate is a Java ORM (Object Relational Mapping) framework, that makes it easy to save Java objects to databases. It internally uses JPA (Java Persistence API) to persist the state of the object in the database schema. It does this by creating a link between your objects and database tables, so you don't have to write lots of code to manage the
5 min read
How to Create a Basic Intro Slider of an Android App?
When we download any app and use that app for the very first time. Then we will get to see the intro slider inside our app. With the help of this slider, we educate our users on how they can use that app and it tells in detail about the app. In this article, we will take a look at the implementation of Intro Slider inside our app. Now, let's move t
4 min read
Maven Build Phases and Basic Maven Commands
Maven is a powerful project management tool that is based on POM (project object model) and used for project build, dependency, and documentation. It is a tool that can be used for building and managing any Java-based project. Maven makes the day-to-day work of Java developers easier and helps with the building and running of any Java-based project
5 min read
How to Create a Basic Color Picker Tool in Android?
There are many open-source color picker tools for Android applications to choose from. In this discussion, At the end of this article, one will be able to implement the color picker tool in the Android application, have a look at the following image to get an overview of the discussion. In this article, it's been discussed to implement the very bas
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
java.lang.reflect.Proxy Class in Java
A proxy class is present in java.lang package. A proxy class has certain methods which are used for creating dynamic proxy classes and instances, and all the classes created by those methods act as subclasses for this proxy class. Class declaration: public class Proxy extends Object implements SerializableFields: protected InvocationHandler hIt han
4 min read
Article Tags :
Practice Tags :