0% found this document useful (0 votes)
16 views

Skip To Content2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Skip To Content2

Uploaded by

raroy67751
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Skip to content

geeksforgeeks
Courses 90% Refund
Tutorials
Java
Practice
Contests

Sign In

Java Arrays
Java Strings
Java OOPs
Java Collection
Java 8 Tutorial
Java Multithreading
Java Exception Handling
Java Programs
Java Project
Java Collections Interview
Java Interview Questions
Java MCQs
Spring
Spring MVC
Spring Boot
Hibernate

Content Improvement Event


Share Your Experiences
Java Tutorial
Overview of Java
Basics of Java
Java Basic Syntax
Java Hello World Program
Java Data Types
Primitive data type vs. Object data type in Java with Examples
Java Identifiers
Operators in Java
Java Variables
Scope of Variables In Java
Wrapper Classes in Java
Input/Output in Java
Flow Control in Java
Operators in Java
Strings in Java
Arrays in Java
OOPS in Java
Inheritance in Java
Abstraction in Java
Encapsulation in Java
Polymorphism in Java
Constructors in Java
Methods in Java
Interfaces in Java
Wrapper Classes in Java
Keywords in Java
Access Modifiers in Java
Memory Allocation in Java
Classes of Java
Packages in Java
Java Collection Tutorial
Exception Handling in Java
Multithreading in Java
Synchronization in Java
File Handling in Java
Java Regex
Java IO
Java Networking
JDBC - Java Database Connectivity
Java 8 Features - Complete Tutorial
Java Backend DevelopmentCourse
Java Basic Syntax
Last Updated : 14 Jul, 2024
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

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

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 Free Java Course, which
offers comprehensive coverage and practical exercises

Three 90 Challenge is back on popular demand! After processing refunds worth INR
1CR+, we are back with the offer if you missed it the first time. Get 90% course
fee refund in 90 days. Avail now!
Want to be a master in Backend Development with Java for building robust and
scalable applications? Enroll in Java Backend and Development Live Course by
GeeksforGeeks to get your hands dirty with Backend Programming. Master the key Java
concepts, server-side programming, database integration, and more through hands-on
experiences and live projects. Are you new to Backend development or want to be a
Java Pro? This course equips you with all you need for building high-performance,
heavy-loaded backend systems in Java. Ready to take your Java Backend skills to the
next level? Enroll now and take your development career to sky highs.

author
mayur_patil

958
Previous Article
How is Java platform independent?
Next Article
Java Hello World Program
Read More
Down Arrow
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 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
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
Article Tags :
Java
java-basics
Practice Tags :
Java
three90RightbarBannerImg
course-img
215k+ interested Geeks
Master Java Programming - Complete Beginner to Advanced
Avail 90% Refund
course-img
214k+ interested Geeks
JAVA Backend Development - Live
Avail 90% Refund
course-img
30k+ interested Geeks
Manual to Automation Testing: A QA Engineer's Guide
Avail 90% Refund
geeksforgeeks-footer-logo
Corporate & Communications Address:- A-143, 9th Floor, Sovereign Corporate Tower,
Sector- 136, Noida, Uttar Pradesh (201305) | Registered Address:- K 061, Tower K,
Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh,
201305
GFG App on Play Store
GFG App on App Store
Company
About Us
Legal
Careers
In Media
Contact Us
Advertise with us
GFG Corporate Solution
Placement Training Program
Explore
Job-A-Thon Hiring Challenge
Hack-A-Thon
GfG Weekly Contest
Offline Classes (Delhi/NCR)
DSA in JAVA/C++
Master System Design
Master CP
GeeksforGeeks Videos
Geeks Community
Languages
Python
Java
C++
PHP
GoLang
SQL
R Language
Android Tutorial
DSA
Data Structures
Algorithms
DSA for Beginners
Basic DSA Problems
DSA Roadmap
DSA Interview Questions
Competitive Programming
Data Science & ML
Data Science With Python
Data Science For Beginner
Machine Learning Tutorial
ML Maths
Data Visualisation Tutorial
Pandas Tutorial
NumPy Tutorial
NLP Tutorial
Deep Learning Tutorial
Web Technologies
HTML
CSS
JavaScript
TypeScript
ReactJS
NextJS
NodeJs
Bootstrap
Tailwind CSS
Python Tutorial
Python Programming Examples
Django Tutorial
Python Projects
Python Tkinter
Web Scraping
OpenCV Tutorial
Python Interview Question
Computer Science
GATE CS Notes
Operating Systems
Computer Network
Database Management System
Software Engineering
Digital Logic Design
Engineering Maths
DevOps
Git
AWS
Docker
Kubernetes
Azure
GCP
DevOps Roadmap
System Design
High Level Design
Low Level Design
UML Diagrams
Interview Guide
Design Patterns
OOAD
System Design Bootcamp
Interview Questions
School Subjects
Mathematics
Physics
Chemistry
Biology
Social Science
English Grammar
Commerce
Accountancy
Business Studies
Economics
Management
HR Management
Finance
Income Tax
Databases
SQL
MYSQL
PostgreSQL
PL/SQL
MongoDB
Preparation Corner
Company-Wise Recruitment Process
Resume Templates
Aptitude Preparation
Puzzles
Company-Wise Preparation
Companies
Colleges
Competitive Exams
JEE Advanced
UGC NET
UPSC
SSC CGL
SBI PO
SBI Clerk
IBPS PO
IBPS Clerk
More Tutorials
Software Development
Software Testing
Product Management
Project Management
Linux
Excel
All Cheat Sheets
Recent Articles
Free Online Tools
Typing Test
Image Editor
Code Formatters
Code Converters
Currency Converter
Random Number Generator
Random Password Generator
Write & Earn
Write an Article
Improve an Article
Pick Topics to Write
Share your Experiences
Internships
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By
using our site, you acknowledge that you have read and understood our Cookie Policy
& Privacy Policy
Got It !
Lightbox

You might also like