Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
32 views

Java Notes

Uploaded by

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

Java Notes

Uploaded by

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

Java comments

We use Java comments because of the following


 They help explain complex logic.

 Useful for generating documentation and guiding future developers.


 Enable temporarily disabling code sections for testing and debugging
purposes.
For example,

Stay updated with the latest blogs on online courses and skills
Enter Mobile Number

Register Now

// Print a greeting message to the console


System.out.println("Hello World");
Copy code
Types of Java Comments
We have three types of comments in Java
 Single-Line Comments
 Multi-Line Comments
 Documentation Comments
Let’s understand each one by one in detail
Single-Line Comments
Single-line comments in Java are used to comment out a single line or a part of it. They begin
with two forward slashes (//) and extend to the end of the line. Single-line comments are helpful
for brief explanations or notes relevant to the local code.
Syntax
// comment text
Example
In the code below, single-line comments describe each step in the program, making the code
more readable and understandable.

public class Main {


public static void main(String[] args) {
// Declare a variable to store the number
int number = 10;

// Calculate the square of the number


int square = number * number;

// Print the result


System.out.println("The square of " + number + " is: " + square);
}
}
Copy code
Output
The square of 10 is: 100

Multi-Line Comments
Multi-line comments in Java are used to comment out blocks of text spanning multiple lines.
They start with /* and end with */. Everything between these markers is considered a comment
and is ignored by the Java compiler. Multi-line comments help provide detailed explanations or
temporarily disable a block of code during debugging.
Syntax
/*
This is a multi-line comment.
It can span several lines.
The Java compiler ignores everything in this block.
*/
Example
In the code below, the multi-line comment provides a clear explanation of the Fibonacci
sequence and the logic behind the loop that calculates it. This kind of detailed explanation helps
in understanding the purpose and functionality of the code, especially for complex algorithms.

public class Main {


public static void main(String[] args) {
int n = 10; // number of elements in the Fibonacci series

/* The Fibonacci sequence is a series of numbers where


a number is the addition of the last two numbers,
starting with 0, and 1.

This loop calculates each number in the series


up to the nth number and prints them. */
int n1 = 0, n2 = 1;
System.out.print("First " + n + " terms: ");

for (int i = 1; i <= n; ++i) {


System.out.print(n1);

if (i < n) {
System.out.print(", ");
}

// compute the next term


int sum = n1 + n2;
n1 = n2;
n2 = sum;
}
}
}
Copy code
Output
First 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

Constructors in Java Explained

In Java, constructors initialize newly created objects, setting their initial state. They share the same name as
the class, lack a return type, and are automatically invoked upon object instantiation.

How to Return an Array in Java

In Java, methods can return arrays to provide multiple data elements of a consistent type in a single response.
There are various ways on how to return an array. Today...read more
Polymorphism in Java: Meaning and its Types

Polymorphism is a fancy-sounding word that really just means “many shapes.” And in the world of Java
programming, it refers to the ability of objects to take on different forms...read more

Documentation Comments
Documentation comments in Java, often referred to as doc comments, are a special type of
comment used to generate JavaDoc documentation. JavaDoc is a tool provided by Oracle that
generates standard HTML documentation from these comments. Documentation comments are
crucial for explaining the code’s functionality, parameters, return values, and thrown exceptions
at a higher level. It makes them an essential part of professional Java development.
Syntax
/**
* Description or summary of the class, method, or field.
*
* @tag description
*/
Important components of this syntax include
 Start and End: The comment begins with /** and ends with */. This distinguishes it
from regular multi-line comments that start with /*.
 Description: The first part is usually a description or summary of the class, method, or
field that the comment is documenting.
 Tags: After the description, you can include various tags to provide more specific
information.
Various tags used in Java documentation comments are as follows.
Tag Name Description Syntax Example
Describes a parameter passed to a method or
@param @param paramName desc
constructor.
@return Describes the return value of methods. @return description
@throws/@exception Describes the exception thrown by a method. @throws ExceptionClass
@see Adds a reference or a link to another element. @see className#methodN
@author States the author of the code. @author name
@version Specifies the version of the class, interface, or method. @version versionInfo
Indicates when the class, method, or field was first
@since @since version
added to the project.
@deprecated Marks the method or class as obsolete. @deprecated description
Inserts an inline link to another element in the
@link {@link package.class#me
documentation.
Like @link, but displays the link text instead of the {@linkplain package.class
@linkplain
code font. label}
@code Displays text in code font. {@code code}
Indicates that text should be interpreted literally,
@literal {@literal text}
ignoring Javadoc tags.
Example
In the code below, documentation comments are used. This type of commenting is essential for
large-scale projects, API libraries, or any Java code that will be used or maintained by others, as
it ensures that anyone reading the code can quickly understand its purpose, usage, and behaviour
without delving into the implementation details.

/**
* The BankAccount class simulates a bank account.
*/
public class BankAccount {

/**
* The balance field stores the current balance.
*/
private double balance;

/**
* The constructor initializes the balance to 0.
*/
public BankAccount() {
balance = 0;
}

/**
* The deposit method adds money to the account.
*
* @param amount The amount to add to the balance.
*/
public void deposit(double amount) {
balance += amount;
}

/**
* The withdraw method subtracts money from the account.
*
* @param amount The amount to subtract from the balance.
*/
public void withdraw(double amount) {
balance -= amount;
}

/**
* The getBalance method returns the account balance.
*
* @return The current balance of the account.
*/
public double getBalance() {
return balance;
}

/**
* The main method for the BankAccount class.
*
* @param args Command line arguments (not used).
*/
public static void main(String[] args) {
BankAccount myAccount = new BankAccount();

// Demonstrate deposit
myAccount.deposit(200.00);
System.out.println("Balance after deposit: " + myAccount.getBalance());

// Demonstrate withdrawal
myAccount.withdraw(50.00);
System.out.println("Balance after withdrawal: " + myAccount.getBalance());
}
}
Copy code
Output
Balance after deposit: 200.0
Balance after withdrawal: 150.0

What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command prompt
to run the java class, an instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader. There are three built-in classloaders in
Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null because it is an
11. //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloade
r
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Test it Now

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler"
refers to a translator from the instruction set of a Java virtual machine (JVM) to
the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java
uses JNI framework to send output to the Console or interact with OS libraries.

You might also like