Basic Java Program

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

Creating Simple Java Program:

Let's create the hello java program

class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

To compile: javac Simple.java


To execute: java Simple

Output:

Hello Java

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible
to all.
o

What is constant?
o Constant is a value that cannot be changed after assigning it. Java does not
directly support the constants. For e.g. numeric values in PI. static is a keyword. If
we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke
the static method. The main() method is executed by the JVM, so it doesn't require
creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss
it in coming section.

System.out.println() is used to print statement. Here, System is a class, out is an


object of the class, println() is a method of the class.

Structure of Java Program:

o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors

Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of
the program. It improves the readability of the program. Whatever we write in the
documentation section, the Java compiler ignores the statements during the execution of
the program. To write the statements in the documentation section, we use comments.
The comments may be single-line, multi-line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//). For example:

1. //First Java Program

o Multi-line Comment: It starts with a /* and ends with */. We write between these
two symbols. For example:

1. /*It is an example of
2. multiline comment*/

o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:

1. /**It is an example of documentation comment*/

Package Declaration
The package declaration is optional. It is placed just after the documentation section. In
this section, we declare the package name in which the class is placed. Note that there
can be only one package statement in a Java program. It is necessary because a Java
class can be placed in different packages and directories based on the module they are
used. For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:

1. package javatpoint; //where javatpoint is the package name


2. package com.javatpoint; //where com is the root directory and javatpoint is the subdire
ctory

Import Statements
The package contains the many predefined classes and interfaces. If we want to use any
class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to import
the class. It is written before the class declaration and after the package statement. We
use the import statement in two ways, either import a specific class or import all classes
of a particular package. In a Java program, we can use multiple import statements. For
example:

1. import java.util.*; //it imports all the class of the java.util package

Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the
class. It contains only constants and method declarations. Another difference is that it
cannot be instantiated. We can use interface in classes by using the implements keyword.
An interface can also be used with other interfaces by using the extends keyword. For
example:

1. interface car
2. {
3. void start();
4. void stop();
5. }

Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. We use the class keyword to define the class. It contains
information about user-defined methods, variables, and constants. Every Java program
has at least one class that contains the main() method. For example:

1. class Student //class definition


2. {
3. }

Class Variables and Constants


In this section, we define variables and constants that are to be used later in the program.
In a Java program, the variables and constants are defined just after the class definition.
The variables and constants store values of the parameters. It is used during the execution
of the program. We can also decide and define the scope of variables by using the
modifiers. It defines the life of the variables. For example:

1. class Student //class definition


2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }

Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method. In other words, it is an
entry point of the class. It must be inside the class. Inside the main method, we create
objects and call the methods. We use the following statement to define the main()
method:

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


2. {
3. }
For Example:

public class Student //class definition

4. {
5. public static void main(String args[])
6. {
7. //statements
8. }
9. }

What is constant?
o Constant is a value that cannot be changed after assigning it. Java does not
directly support the constants. For e.g. numeric values in PI. static is a keyword. If
we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke
the static method. The main() method is executed by the JVM, so it doesn't require
creating an object to invoke the main() method. So, it saves memory.

Type of Constants:
Like other programming language, Java also has some constants. In the previous
section, we have discussed, Java constants, how to declare constants. So, in this section,
we will discuss the only types of constants in Java and how to use it.
There are the following types if constants in Java:

1. Numeric Constants
o Integer Constants
o Real Constants
2. Non-numeric Constants
o Character Constants
o String Constants

Numeric Constants
Numeric constants are the constants that contains numerals. It may also have a leading
sign and decimal point.

Rule to Define Numeric Constants

o Must have at least one digit.


o It should not have comma, space, and another special symbol.
o It may have positive or negative sign. If no sign is preceded then the constant
assumed positive.

There are the following two types of numeric contestants:

Integer Constants
A constant that contains digits (0-9) and does not have decimal point is called integer
constants. By default, it is type of int. There are the following three types of integer
constants:

o Decimal Constants: It contains digits between 0 to 9. Note that must not start with
0. For example, 898, 67, 66.
o Octal Constants: It contains digits between 0 to 7 and must begin with 0. For
example, 012, 032, 067.
o Hexadecimal Constants: It contains digits between 0 to 9 and letters a to f (either
in upper or lower case). It must begin with 0X or 0x. For example, 0x23, 0x76,
0X6A, 0XFF.

Real Constants

Numeric constants that have a decimal point are called real or floating-point constants.
By default, the real constants are of double type. We can explicitly mention the type of a
floating-point constant as a float by appending the letter f or F at the end of the constant.
For example, 45f, -0.14f, 5.6F.

The real constants can be written in the following two forms:

o Fractional Form
o Exponential Form

Fractional Form

Rules to Define Fractional Form

1. It must have a decimal point


2. It may have positive or negative sign. The default is positive sign and it is optional.
3. Comma, spaces, or any other symbols are not allowed.

For example, 3.14, -9.1, 0.67.

Exponential Form
It is used to represent a real constant when a number is too small or too large.

For example, 0.00000149 can be represented as 1.49e-6. The part of the number before e
is called mantissa i.e 1.49, whereas, the part after e is called the exponent i.e, 6.

Rules to Define Exponent Form

o Mantissa and exponent must be separated by e or E.


o Mantissa can be positive or negative, the default is positive.
o The exponent can be positive or negative, the default is positive

For example, 100.34e4, -56E10, 0.233E10, -0.94e15.

Non-numeric Constants
A constant that does not contain digits is called non-numeric constants. There are the
following two types of non-numeric constants:

Character Constants

A Character constant is a single alphabet, digit or any special symbol enclosed using single
quotes. For example, 'Y', 'd', '6', '#', '&'.

The maximum length of a character constant is 1 character long. It means that we cannot
put more than one character inside single quotation marks.

String Constants

String constants consist of zero or more characters enclosed in double quotes (""). At the
end of the string, the null character i.e '\0' is automatically placed by the compiler. For
example, "hello", , "111",”@june”

Backslash Character Constants:


Java also supports backslash character constants. These are used in output methods. It is
also known as escape sequence. For Example, \n, \t, \a, etc.

o Although it consists of two characters but it represents a single character.


o Each escape sequence has Unicode value.
o Each and Every combination must start with backslash character(\).
o Java supports some special backslash character constant.

The following table denotes the backslash character constants used in Java.

\b Backspace

\f From feed

\n New line

\r Carriage return

\t Horizontal tab

\" Double quote

\' Single quote

\\ Backslash

\v Vertical tab

\? Question mark

Java Variables:
In Java, Variables are the data containers that save the data values during
Java program execution. Every Variable in Java is assigned a data type that
designates the type and quantity of value it can hold. A variable is a memory
location name for the data.

• The value stored in a variable can be changed during program execution.


• Variables in Java are only a name given to a memory location. All the
operations done on the variable affect that memory location.
• In Java, all variables must be declared before use.

How to Declare Variables in Java?


We can declare variables in Java as pictorially depicted below :

Datatype Name: int count;

1. datatype: Type of data that can be stored in this variable.


2. data_name: Name was given to the variable

In this way, a name can only be given to a memory location. It can be assigned values in
two ways:
• Variable Initialization
• Assigning value by taking input

How to Initialize Variables in Java?

It can be perceived with the help of 3 components that are as follows:


• datatype: Type of data that can be stored in this variable.
• variable_name: Name given to the variable.
• value: It is the initial value stored in the variable.

e.g.

Int age =20;

The Scope of Variables in Java


• Each variable has a scope that specifies how long it will be seen and used in a
programme. Java code must be efficient and error-free, which requires an
understanding of variable scope. The scope of variables in Java will be explored in
this section, along with their effects on how programmes are executed.

• The area of the variable is accessible is called its scope.

There are three scopes for variables in Java: local, instance, class, and method variables.

Local Variables:
Local variables are those that are declared inside of a method .They are not available
outside of the method definition .Local variables can be declared inside the program
blocks that are defined the opening ( { ) and closing braces ( } ). These variables are visible
to the program only.
The Java compiler throws an error if a local variable is not initialised before being used.
The range of local variables is the smallest of all the different variable types.

Example :

public SumExample

public void calculateSum() {

1. int a = 5; // local variable


2. int b = 10; // local variable
3. int sum = a + b;
4. System.out.println("The sum is: " + sum);
5. }
6. }

Output:

The sum is: 15

Instance Variables:
1. Within a class, but outside of any methods instance variables are declared. They
are accessible an instance variable can be declared using different access modifiers
available in Java like default, private, public, and protected to all methods and blocks
in the class and are a part of an instance of the class. Instance variables are
accessible inside the same class that declares them.

Example:

1. public class Circle {


2. double radius; // instance variable
3. public double calculateArea() {
4. return Math.PI * radius * radius;
5. }
6. }

Class Variables (Static Variables):


In a class but outside of any method, the static keyword is used to declare class
variables, also referred to as static variables. Class variables can be accessed by using
the class name . The value of a class variable can be accessed and modified by
using class methods or instance methods.

The following is the syntax to declare class variables.

<static> <data_type> <variable_name>;

where,
<static> implies that all instances of the class share the same static variable
<data_type> is the data type of the variable.
<variable_name> is the name of the variable.

Example :

1. public class Bank {


2. static double interestRate; // class variable
3.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

Boolean one = false


Byte Data Type
The byte data type is an example of primitive data type. It is size is 1byte. Its value-range
lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is
most required. It can also be used in place of "int" data type.

Example: byte a = 10, byte b = -20

Short Data Type


The short data type size is 2 byte. Its value-range lies between -32,768 to 32,767
(inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value
is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type size is a 4 byte.. Its default value is 0. Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.The int data type
is generally used as a default data type for integral values unless if there is no problem
about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type size is 8 byte. Its default value is 0. Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. The long data type
is used when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type:


It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise
values, . Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is generally used for decimal values just like float. Its default value
is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is used to store characters.The char type requires size of 2 bytes but,
it can hold only a single character.

Example:

char letterA = 'A'


Types of Non-primitive data types
There are five types of non-primitive data types in Java

1. Class
2. Array
3. Interface

The class represents a group of variables and group of function. Class is a set of object that
having attribute.

Java array is an object which contains elements of a similar data type. Arrays are commonly used
to store multiple values in single variable.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

1.

2.
1.

2.


You might also like