JAVA-Notes-Unit-1_Part 1
JAVA-Notes-Unit-1_Part 1
Lecture Notes
OBJECT ORIENTED
Subject Name
PROGRAMMING THROUGH JAVA
The team initiated this project to develop a language for digital devices such as
set-top boxes, television, etc. Originally C++ was considered to be used in the project
but the idea was rejected for several reasons (For instance C++ required more
memory). Gosling endeavoured to alter and expand C++ . James Gosling and his team
called their project “Greentalk” and its file extension was .gt and later became to
known as “OAK”.
Why “Oak”?
The name Oak was used by Gosling after an oak tree that remained outside his office.
Also, Oak is an image of solidarity and picked as a national tree of numerous nations
like the U.S.A., France, Germany, Romania, etc. But they had to later rename it as
“JAVA” as it was already a trademark by Oak Technologies.
The name Java originates from a sort of espresso bean. The team came up with this
name while having a coffee near their office. Java was created on the principles
like Robust, Portable, Platform Independent, High Performance, Multithread,
etc. and it is widely used in internet programming, mobile devices, games, e-
business solutions, etc.
2. Java Platform, Enterprise Edition (Java EE) –A platform for developing and
running web and enterprise applications.
3. Java Platform, Micro Edition (Java ME) –A flexible environment for applications
that run on mobile and embedded devices.
4. Java Card - It is the tiniest of Java platforms targeted for embedded devices like
SIM cards, Banking Cards, Identity Cards, Healthcare Cards, Passports and
Several IoT Products.
Java Buzzwords
The primary objective of Java programming language creation was to make it
simple, portable and secure programming language. Apart from this, there are some
excellent features which play an important role in the popularity of this language. The
features of Java are also known as Java Buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Interpreted
4. Platform Independent
5. Architectural Neutral
6. Portable
7. Secured
8. Robust
9. High Performance
10.Multithreaded
11.Dynamic
12.Distributed
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple programming
language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-Oriented
3. Interpreted
4. Platform Independent
The Java platform differs from most other platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
5. Architectural Neutral
6. Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform ie different operating systems and architectures. It doesn't require any
implementation.
Java code is compiled into bytecode that can run on any device with a Java
Virtual Machine (JVM).
The JVM is platform-dependent, meaning that a different JVM is designed for
each operating system.
The bytecode is platform-independent, meaning that it can run on different
operating systems.
This allows developers to write code once and run it on many different
devices.
7. Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No Explicit Pointer
Java Programs run inside a Virtual Machine Sandbox
8. Robust
The Java is robust language ie strong because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java. All these
points make Java robust.
9. High Performance
10.Multithreaded
11.Dynamic
12.Distributed
For executing any Java program, the following software or application must be properly
installed.
Install the JDK if we do not have installed it, download the JDK and install it.
https://www.oracle.com/in/java/technologies/downloads/
Set path of the jdk/bin directory
Create the Java program.
Compile and run the Java program.
Creating Hello World Example
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Test it Now
Output:
Hello Java
We must understand the differences between JDK, JRE, and JVM before proceeding
further to Java.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:
JRE
JRE is an acronym for Java Runtime Environment. The Java Runtime Environment is
a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.
JVM
JVMs are available for many hardware and software platforms. JVM, JRE, and
JDK are platform dependent because the configuration of each OS is different from each
other. However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
The path is required to be set for using tools such as javac, java, etc.
If you are saving the Java source file inside the JDK/bin directory, the path is not
required to be set because all the tools will be available in the current directory.
However, if you have your Java file outside the JDK/bin folder, it is necessary to set the
path of JDK.
1. Temporary
2. Permanent
To set the temporary path of JDK, you need to follow the following steps:
For Example:
For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer properties -> advanced tab -> environment variables -> new
tab of user variable -> write path in variable name -> write path of bin folder in
variable value -> ok -> ok -> ok
For Example:
1) Go to MyComputer properties
8) Click on ok button
9) Click on ok button
Now your permanent path is set. You can now execute any program of java from any
drive.
Java Keywords
Java keywords are reserved words with predefined meanings in the Java
programming language. They are part of the syntax and cannot be used as identifiers,
such as variable names, class names, or method names.
List of Java Keywords
1. Arrays:
A collection of similar types of data. For example, int arr[] = new int[5];.
2. Classes:
User-defined data types. For example, String, ArrayList, etc.
3. Interfaces:
Like classes but only contain method signatures.
For example, Comparable, Serializable, etc.
4. String :
In Java, a string is a sequence of characters. It’s a data type used to represent text
rather than numeric data. Strings in Java are immutable, meaning once a string object is
created, its contents cannot be changed.
Example :
// Declare String without using new operator
String s = "Welcome to VJIT !";
// Declare String using new operator
String s1 = new String("Welcome to CSE-Data Science !");
5. Enum:
An enum is a special data type used to define a collection of constants. It allows you
to create a set of named constants that represent a finite set of possibilities, typically
related to some specific type or category. Enums are declared using the enum keyword.
Example :
B.Tech (CSE-DS)-II-II Sem Page 22
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I
enum Day
{
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY
}
Variables
Types of Variables
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't even
aware that the variable exists.
Output:
Variable: 10
2. Instance Variables
A variable declared inside the class but outside the body of the method, is called
an instance variable. It is not declared as static.
import java.io.*;
public class InstanceVariableDemo
{
//Defining Instance Variables
public String name;
public int age=19;
//Creadting a default Constructor initializing Instance Variable
public InstanceVariableDemo()
{
this.name = "Deepak";
}
public static void main(String[] args)
{
// Object Creation
InstanceVariableDemo obj = new InstanceVariableDemo();
System.out.println("Student Name is: " + obj.name);
System.out.println("Age: "+ obj.age);
}
}
Output:
Student Name is: Deepak
Age: 19
3. Static Variables
A variable that is declared as static is called a static variable also known as class
variables. It cannot be local. You can create a single copy of the static variable and
share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
StaticVariableDemo.java
class Student
{
//static variable
static int age;
}
S1 age is: 23
S2 age is: 23
Operators in Java
Java operators are the symbols that are used to perform various operations on variables
and its values.
Types of Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Bitwise Operators
7. Comparison Operators
8. Ternary Operator
Operators Operations
+ Addition
- Subtraction
x Multiplication
/ Division
% Modulus
Assignment Operators
Assignment Operators are mainly used to assign the values to the variable in the
program.
= X = Y; X = Y;
+= X += Y; X = X + Y;
-= X -= Y; X = X - Y;
*= X *= Y; X = X * Y;
/= X /= Y; X = X / Y;
%= X %= Y; X = X % Y;
Relational Operators
Relational operators are assigned to check the relationships between two particular
operators.
Unary Operators
Unary Operators in Java are used in only one operand.
Operators Description
+ Unary Plus
- Unary Minus
++ Increment operator
-- Decrement Operator
! Logical complement operator
Bitwise Operators
Bitwise Operators in Java are used to assist the performance of the operations on
individual bits.
Operators Descriptions
~ Bitwise Complement
<< Left shift
>> Right shift
>>> Unsigned Right shift
& Bitwise AND
^ Bitwise exclusive OR
Comparison Operators
To compare two values (or variables), comparison operators are used. A
comparison's return value is either true or false. These are referred to as "Boolean
values."
Operators Operations
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Ternary Operator
The only conditional operator that accepts three operands is the ternary operator in
Java. Java programmers frequently use it as a one-line alternative to the if-else
expression.
Expressions in Java
An expression in Java is a construct that evaluates to a single value. This value
can be a number, a string, an object, or any other data type depending on the components
of the expression. Expressions can include variables, literals, method calls, and
operators.
There are different types of control statements in Java for different conditions. We
can divide control statements in Java into three major types:
1. Conditional Statements
2. Looping Statements
3. Jumping Statements
Conditional Statements
Conditional statements in Java are similar to making a decision in real life, where
we have a situation and based on certain conditions we decide what to do next.
1. if Statement
These are the simplest and yet most widely used control statements in Java.
The if statement is used to decide whether a particular block of code will be executed or
not based on a certain condition.
In the above flow diagram, we can see that whenever the condition is true, we
execute the if block otherwise we skip it and continue the execution with the code
following the if block.
Syntax:
if(condition)
{
// block of code to be executed if the condition is true
}
For example:
Output
10 is less than 15
Outside if-block
2. if-else Statement
The if statement is used to execute a block of code based on a condition. But if the
condition is false and we want to do some other task when the condition is false, how
should we do it?
That's where else statement is used. In this, if the condition is true then the code inside
the if block is executed otherwise the else block is executed.
Let's see the execution flow of the if-else statement in a flow diagram:
The above flow diagram is similar to the if statement, with a difference that whenever
the condition is false, we execute the else block and then continue the normal flow of
execution.
Syntax:
if (condition)
{
// If block executed when the condition is true
}
else
{
// Else block executed when the condition is false
}
Now, if the condition is false, the else block is executed and the if block code is skipped.
This is one example of controlling the flow of a program through control statements in
java.
For example:
int n = 10;
if (n > 5)
{
System.out.println("The number is greater than 5.");
}
else
{
System.out.println("The number is 5 or less.");
}
}
}
Output
The number is greater than 5.
Nested control statements mean an if-else statement inside other if or else blocks. It is
similar to an if-else statement but they are defined inside another if-else statement.
Let us see the syntax of a specific type of nested control statements where an if-
else statement is nested inside another if block.
Syntax:
if (condition)
{
// If block code to be executed if condition is true
if (nested condition)
{
// If block code to be executed if nested condition is true
}
else
{
// Else block code to be executed if nested condition is false
}
}
else
{
// Else block code to be executed if condition is false
}
Explanation:
Here, we have specified another if-else block inside the first if block. In the syntax, you
can see the series of the blocks executed according to the evaluation
of condition and nested condition.
Using this, we can nest the control flow statements in Java to evaluate multiple related
conditions.
Let's see the execution flow of the above-mentioned nested-if-else statement in a flow
diagram:
Example:
Let’s say that we want to know which floor of the mall a person needs to go to do
shopping based on the age and gender of the person. Let’s see the implementation of this
example through nested-if:
Output:
4. if-else-if Ladder
In this, the if statement is followed by multiple else-if blocks. We can create a decision
tree by using these control statements in Java in which the block where the condition is
true is executed and the rest of the ladder is ignored and not executed.
If none of the conditions is true, the last else block is executed, if present.
Let's see the execution flow of the if-else ladder in a flow diagram:
As you can see in the above flow diagram of the if-else ladder, we execute the if block if
the condition is true, otherwise if the condition is false, instead of executing the else
block, we check other multiple conditions to determine which block of code to execute.
If none of the conditions are true, the last else block, if present, is executed.
The syntax and execution flow of the if-else-if ladder statement is as follows:
Syntax:
if(condition1)
{
// Executed only when the condition1 is true
}
else if(condition2)
{
// Executed only when the condition2 is true
}
.
.
else
{
// Executed when all the conditions mentioned above are true
}
Example:
Let’s say that we have a browser-specific code, where we want to execute a code
depending upon the browser the user is using. Let’s try to implement this in the code:
Output:
Explanation:
As you can see, the first two conditions are not true. Hence, the first two blocks are not
executed. The third condition is true and hence the third block of code is executed giving
the output: The browser is chrome. Following this block, all other blocks (the
last else block) are ignored.
Here we can write the browser-specific implementation in the equivalent block, and if
none of the supported browsers are encountered then we can also give an error in the
last else block.
5. switch Statement
Switch statements are almost similar to the if-else-if ladder control statements in Java. It
is a multi-branch statement. It is a bit easier than the if-else-if ladder and also more user-
friendly and readable.
The switch statements have an expression and based on the output of the expression, one
or more blocks of codes are executed.
These blocks are called cases. We may also provide a default block of code that can be
executed when none of the cases are matched similar to the else block.
Syntax:
switch (expression)
{
case value1:
//code block of case with value1
break;
case value2:
//code block of case with value2
break;
.
.
case valueN:
//code block of case with valueN
break;
default:
//code block of default value
}
There are certain points that one needs to be remembered while using switch statements:
The expression can be of type String, short, byte, int, char, or an enumeration.
We cannot have any duplicate case values.
The default statement is optional.
Usually, the break statement is used inside the switch to terminate a statement
sequence.
The break statement is optional. If we do not provide a break statement, the
following blocks will be executed irrespective of the case value. This is known as
the trailing case.
Let's see the execution flow of the switch statement in a flow diagram:
In the above flow diagram, we have a switch expression and we match the output of the
expression through a series of case blocks.
Whichever case matches the output, its block is executed and execution skips to the end
of the switch; otherwise, if none of the cases matches, the default block is executed.
B.Tech (CSE-DS)-II-II Sem Page 40
OBJECT ORIENTED PROGRAMMING THROUGH JAVA UNIT-I
Here, we have multiple case statements and each case code block is followed by a break
statement to stop the execution to that case only.
Example:
If we take the previous example, we can easily implement that using switch statements:
Output:
In this example, the case with the value “chrome” is matched and hence its block is
executed. If we do not give a break statement in this block, the trailing blocks(default
block in this example) will also be executed.
Also, it's worthwhile to notice that the switch statement made the code more readable
and cleaner.
Code:
Output:
We can see that the default block is also executed. It is due to the following reason:
Once a case value is matched, all the following blocks of code are executed until
a break statement or the end of the switch statement is encountered.
This is not the expected behavior and hence we should use the break statement. We’ll
learn more about the break statement in the next sections.
Looping Statements
Java provides a set of looping statements that executes a block of code
repeatedly while some condition evaluates to true. Looping control statements in Java
are used to traverse a collection of elements, like arrays.
1. while Loop
The while loop statement is the simplest kind of loop statement. It is used to iterate over
a single statement or a block of statements until the specified boolean condition is false.
The while loop statement is also called the entry-control looping statement because the
condition is checked prior to the execution of the statement and as soon as the boolean
condition becomes false, the loop automatically stops.
You can use a while loop statement if the number of iterations is not fixed.
Normally the while loop statement contains an update section where the variables, which
are involved in while loop condition, are updated.
Let's see the execution flow of the while loop statement in a flow diagram:
We initialize a loop counter variable. After that, we check the loop condition and
if it's true, then the body of the loop is executed followed by the update of the
counter variable.
The control then again switches back to the loop condition and the cycle continues
till the condition is false and we execute the statements outside the loop body.
The syntax and execution flow of the while loop statement is as follows:
Syntax:
while (condition)
{
// code block to be executed
}
Example:
Let's say we want to print the numbers from 10 to 1 in decreasing order. Let's implement
this through a while loop.
// Update Section
num--;
}
}
}
Output:
10
9
8
7
6
5
4
3
2
1
Here, we have used the loop condition as num > 0 and then at each iteration of the loop,
we have decreased the value of the num variable by 1.
So the loop runs till the value of num becomes 1 from 10, and we get the desired output.
2. do-while Loop
The Java do-while loop statement works the same as the while loop statement with the
only difference being that its boolean condition is evaluated post first execution of the
body of the loop. Thus it is also called exit controlled looping statement.
You can use a do-while loop if the number of iterations is not fixed and the body of the
loop has to be executed at least once.
Let's see the execution flow of the do-while loop statement in a flow diagram:
We also initialize a counter variable, but instead of checking the loop condition at
the start, the body of the loop is executed.
After the completion of the loop body, we check the loop condition and continue
to execute the loop body till the condition is false when we come out of the loop
and execute the rest of the code.
The syntax and execution flow of the do-while loop statement is as follows:
Syntax:
do
{
// code block to be executed
} while (condition);
Example:
Let's try to use the same example of printing the number in decreasing order through a
do-while loop:
10
9
8
7
6
5
4
3
2
1
The implementation and output are almost similar, with the change that, even if the
value of the num initially is less than 1. We'll get at least one print statement with the
value of the num as the output.
3. for Loop
Unlike the while loop control statements in Java, a for loop statement consists of
the initialization of a variable, a condition, and an increment/decrement value, all in one
line. It executes the body of the loop until the condition is false.
The for loop statement is shorter and provides an easy way to debug structure in
Java. You can use the for loop statement if the number of iterations is known.
In a for loop statement, execution begins with the initialization of the looping
variable, then it executes the condition, and then it increments or decrements the looping
variable.
If the condition results in true then the loop body is executed otherwise the for
loop statement is terminated.
Let's see the execution flow of the for loop statement in a flow diagram:
As you can see in the above flow diagram, we have a for loop statement. In this
statement, the loop condition is checked, and if the condition is true, the for loop body is
executed until the condition is false and we continue with the normal flow of execution.
Syntax:
Example:
Output:
4. for-each Loop
general-purpose loop that we can use for any use case, the for-each loop can only be
used with collections or arrays.
In for-each loop statement, you cannot skip any element of the given array or collection.
Also, you cannot traverse the elements in reverse order using the for-each loop control
statement in Java.
Let's see the execution flow of the for-each loop statement in a flow diagram:
We check if the collection has any elements or not. If it has the elements, then the
first element is assigned to the local variable mentioned in the for each expression,
and the for each loop body is executed.
After this, we again check if the collection has any remaining elements and this
cycle continues till we have traversed all the elements.
The syntax and execution flow of for each loop statement is as follows:
Syntax:
Example:
Output:
Jump/Branching Statements
Jump/Branching control statements in Java transfer the control of the program to other
blocks or parts of the program and hence are known as the branch or jump statements.
1. Break Statement
The break statement as we can deduce from the name is used to break the current flow of
the program. The break statement is commonly used in the following three situations:
The break statement cannot be used as a standalone statement in Java. It must be either
inside a switch or a loop. If we try to use it outside a loop or a switch, JVM will give an
error.
Let's see the execution flow of the break statement in a flow diagram:
In the above flow diagram of a break statement, whenever the loop body encounters a
break statement, it stops the current flow of execution and jumps to the first statement
out of the loop body.
Syntax:
We have already seen how we use the break inside a switch. Let’s see the syntax in the
case of a loop:
for(condition)
{
// body of the loop
break;
}
while(condition)
{
// body of the loop
break;
}
Example 1:
Output:
As we can see the loop was terminated even when the condition of the loop was still
true. This is how we can use the break statement in a loop.
Example 2:
In case, we have nested loops, the break statement will only break the execution of the
loop its part of. For example:
if (inner_index == 3)
{
break;
}
}
Output:
2. Continue Statement
Sometimes there are situations where we just want to ignore the rest of the code in the
loop body and continue from the next iteration. The continue statement in Java allows us
to do just that. This is similar to the break statement in the sense that it bypasses every
line in the loop body after itself, but instead of exiting the loop, it goes to the next
iteration.
Let's see the execution flow of the continue statement in a flow diagram:
In the above flow diagram of a continue statement, whenever the continue statement has
encountered the rest of the loop body is skipped and the next iteration is executed if the
loop condition is true.
Syntax:
for(condition)
{
// body of the loop
continue;
//the statements after this won't be executed
}
while(condition)
{
// body of the loop
continue;
// the statements after this won't be executed
}
Example:
Let’s try to print the odd number between 1 to 10 as we did in the example of the for
loop, but this time we’ll use the continue statement:
System.out.println("The odd numbers between 1 to 10 are: ");
for (int number = 1; number <= 10; number++)
{
if (number % 2 == 0) continue;
System.out.println(number);
}
Output:
The odd numbers between 1 to 10 are:
1
3
5
7
9
3. Return Statement
The return statements are used when we need to return from a method explicitly. The
return statement transfers the control back to the caller method of the current method. In
the case of the main method, the execution is completed and the program is terminated.
Return statements are often used for conditional termination of a method or to return
something from the method to the caller method.
Let's see the execution flow of the return statement in a flow diagram:
As you can see in the above flow diagram, whenever a return statement is encountered
anywhere in a method, the execution of the current method is stopped and the flow of
the program returns to the caller method of the current method.
The syntax and execution flow of the return statement is as follows:
Syntax:
void method()
{
// body of the method
return;
}
Example:
Let’s say we are searching an element in a list, and as soon as we find it, our work is
done and we should exit the function. Let’s see the implementation of this problem:
public class ReturnStatementDemo
{
public static String search(int key)
{
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int element : numbers)
{
if (element == key)
{
return "Success";
// Putting statements post this return statement
// Will throw compile-time error
}
}
return "Failure";
}
public static void main(String[] args)
{
System.out.println(search(3));
System.out.println(search(10));
}
}
Output:
Success
Failure
As we can search that the value 3 was in the array and we get the output as “Success”,
but since value 10 does not exist in the array, we get the “Failure” as the output.
Rules of Typecasting
Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down. It is done automatically. It is safe
because there is no chance to lose data. It takes place when:
WideningExample.java
Converting a higher data type into a lower one is called narrowing type casting. It
is also known as explicit conversion or casting up. It is done manually by the
programmer. If we do not perform casting, then the compiler reports a compile-time
error.
double -> float -> long -> int -> char -> short -> byte
NarrowingExample.java
Arrays in Java
An array is a collection of similar types of data.
1. Array Declaration
type[] arrayName;
type: The data type of the array elements (e.g., int, String).
2. Create an Array
To create an array, you need to allocate memory for it using the new keyword:
We can access array elements using their index, which starts from 0:
The first line sets the value of the first element to 10. The second line retrieves the value
of the first element.
arrayRefVar=new datatype[size];
2. Two-Dimensional Array
Two-dimensional arrays store the data in rows and columns:
In this, the array has two rows and five columns. The index starts from 0,0 in the left-
upper corner to 1,4 in the right lower corner.
Output:
268
486
469
This line uses the keyword class to declare that a new class is being defined.
class HelloWorld
{
//
//Statements
}
2. HelloWorld
It is an identifier that is the name of the class. The entire class definition,
including all of its members, will be between the opening curly brace ” { ” and the
closing curly brace ” } “.
3. main Method
In the Java programming language, every application must contain a main
method. The main function(method) is the entry point of your Java application, and it’s
mandatory in a Java program. whose signature in Java is:
public static void main(String[] args)
Explanation of the above syntax
public : So that JVM can execute the method from anywhere.
static : The main method is to be called without an object. The modifiers are public
and static can be written in either order.
void : The main method doesn’t return anything.
main() : Name configured in the JVM. The main method must be inside the class
definition. The compiler executes the codes starting always from the main method.
String[] : The main method accepts a single argument, i.e., an array of elements of
type String.
Like in C/C++, the main method is the entry point for your application and will
subsequently invoke all the other methods required by your program.
The next line of code is shown here. Notice that it occurs inside the main() method.
System.out.println("Hello, World");
This line outputs the string “Hello, World” followed by a new line on the screen.
Output is accomplished by the built-in println( ) method. The System is a predefined
class that provides access to the system and out is the variable of type output stream
connected to the console.
Comments
They can either be multiline or single-line comments.
// This is a simple Java program.
// Call this file "HelloWorld.java".
This is a single-line comment. This type of comment must begin with // as in
C/C++. For multiline comments, they must begin from /* and end with */.
Important Points
The name of the class defined by the program is HelloWorld, which is the same as
the name of the file(HelloWorld.java). This is not a coincidence. In Java, all codes
must reside inside a class, and there is at most one public class which contains the
main() method.
By convention, the name of the main class(a class that contains the main method)
should match the name of the file that holds the program.
Every Java program must have a class definition that matches the filename (class
name and file name should be same).
Compiling the Program
After successfully setting up the environment, we can open a terminal in Windows
and go to the directory where the file – HelloWorld.java is present.
Now, to compile the HelloWorld program, execute the compiler – javac, to specify
the name of the source file on the command line, as shown:
javac HelloWorld.java
The compiler creates a HelloWorld.class (in the current working directory) that
contains the bytecode version of the program.
Execute the Program
Now, to execute our program, JVM (Java Virtual Machine) needs to be called using
Java tool, specifying the name of the class file on the command line, as shown:
java HelloWorld
This will print “Hello World” to the terminal screen.