0% found this document useful (0 votes)
71 views24 pages

CH - 1 - Introduction To Java

The document provides an overview of the Java programming language, including its history, features, and uses. It discusses that Java was created in 1995 as an object-oriented language similar to C++, intended initially for set-top boxes but now used widely for mobile apps, web apps, and more. The document outlines Java's key features such as being platform-independent, secure, robust, and simple. It also provides a brief history of Java versions released since 1996.

Uploaded by

Priyansh Gangani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
71 views24 pages

CH - 1 - Introduction To Java

The document provides an overview of the Java programming language, including its history, features, and uses. It discusses that Java was created in 1995 as an object-oriented language similar to C++, intended initially for set-top boxes but now used widely for mobile apps, web apps, and more. The document outlines Java's key features such as being platform-independent, secure, robust, and simple. It also provides a brief history of Java versions released since 1996.

Uploaded by

Priyansh Gangani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 24

Bhagwan Mahavir University Java Programming

Unit:1 Introduction To Java

1.1 History and features of Java


1.2 C++ Vs Java
1.3 Java Virtual Machine & Byte Code
1.4 Java Environment Setup
1.5 Java Program Structure

What is Java?
Java is an object Oriented Programming Language and very similar to C++.

Java is simplified language.

Java is a popular programming language, created in 1995.

It is used for:

• Mobile applications (specially Android apps)


• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection

History of Java
• The history of Java is very interesting.
• Java was originally designed for interactive television, but it was too advanced technology
for the digital cable television industry at the time.
• The history of Java starts with the Green Team.
• Java was developed by James Gosling, who is known as the father of Java, in 1995.
• James Gosling ,Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991.
• The small team of sun engineers called Green Team.
• Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
• Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
• After that, it was called Oak and was developed as a part of the Green project.

Created By: Krishna Patel Page 1


Bhagwan Mahavir University Java Programming

Why Java was named as "Oak"?

Why Oak?
• Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?

Why had they choose the name Java for Java language?

• The team gathered to choose a new name.


• The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic,
lively, cool, unique, and easy to spell, and fun to say.
• According to James Gosling, "Java was one of the top choices along with Silk".
• Since Java was so unique, most of the team members preferred Java than other names.
• Java is an island in Indonesia where the first coffee was produced (called Java coffee).
• It is a kind of espresso bean.
• Java name was chosen by James Gosling while having a cup of coffee nearby his office.

• JDK 1.0 was released on January 23, 1996.


• After the first release of Java, there have been many additional features added to the
language.
• Now Java is being used in Windows applications, Web applications, enterprise
applications, mobile applications, cards, etc.
• Each new version adds new features in Java.

1. JDK Alpha and Beta (1995) 8. Java SE 6 (11th Dec 2006)


2. JDK 1.0 (23rd Jan 1996) 9. Java SE 7 (28th July 2011)
3. JDK 1.1 (19th Feb 1997) 10.Java SE 8 (18th Mar 2014)
4. J2SE 1.2 (8th Dec 1998) 11.Java SE 9 (21st Sep 2017)
5. J2SE 1.3 (8th May 2000) 12.Java SE 10 (20th Mar 2018)
6. J2SE 1.4 (6th Feb 2002) 13.Java SE 11 (September 2018)
7. J2SE 5.0 (30th Sep 2004) 14.Java SE 12 (March 2019)

Created By: Krishna Patel Page 2


Bhagwan Mahavir University Java Programming
15. Java SE 13 (September 2019) 18. Java SE 16 (Mar 2021)
16. Java SE 14 (Mar 2020) 19. Java SE 17 (September 2021)
17. Java SE 15 (September 2020) 20. Java SE 18 (to be released by March

2022)

Features of Java/Buzzwords of Java


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also 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. Portable Interpreted
4. Platform independent 9. High Performance
5. Secured 10.Multithreaded
6. Robust 11.Distributed

7. Architecture neutral 12.Dynamic

8.

Created By: Krishna Patel Page 3


Bhagwan Mahavir University Java Programming

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:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-


oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior(method).

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object Polymorphism
2. Class 5. Abstraction
3. Inheritance 6. Encapsulation
4.

Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform
specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in
which a program runs.

There are two types of platforms software-based and hardware-


based. Java provides a software-based platform.

The Java platform differs from most other platforms in the sense
that it is a software-based platform that runs on top of other
hardware-based platforms. It has two components:

Created By: Damyanti Patel Page 4


Bhagwan Mahavir University Java Programming

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).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is
used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are imported from
network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights
to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL(Secure Socket Layer), JAAS (Java Authentication and
Authorization Service), Cryptography, etc.

Created By: Krishna Patel Page 5


Bhagwan Mahavir University Java Programming

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get
rid(remove) of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make
Java robust.

Architecture-neutral(fix)

Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require
any implementation.

High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI ( Remote
Method Invocation) and EJB(Enterprise Java Bean) are used for creating distributed applications. This
feature of Java makes us able to access files by calling the methods from any machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal
with many tasks at once by defining multiple threads.

Created By: Krishna Patel Page 6


Bhagwan Mahavir University Java Programming

The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

C++ vs Java
There are many differences and similarities between the C++ programming language and Java. A list
of top differences between C++ and Java are given below:

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
Windows-based, web-based,
enterprise, and mobile applications.

Goto C++ supports Java doesn't support the goto


the goto statement. statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by using interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally.
write a pointer program in C++. However, you can't write the
pointer program in java. It means
java has restricted pointer support in
java.

Created By: Krishna Patel Page 7


Bhagwan Mahavir University Java Programming

Compiler and C++ uses compiler only. C++ is Java uses both compiler and
Interpreter compiled and run using the interpreter. Java source code is
compiler which converts source converted into bytecode at
code into machine code so, C++ compilation time. The interpreter
is platform dependent. executes this bytecode at runtime
and produces output. Java is
interpreted that is why it is
platform-independent.

Call by Value C++ supports both call by value Java supports call by value only.
and Call by and call by reference. There is no call by reference in
reference java.

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.

Documentation C++ doesn't support Java supports documentation


comment documentation comments. comment (/** ... */) to create
documentation for java source code.

Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We
so that we can decide whether can override all non-static methods
or not to override a function. by default. In other words, non-
static methods are virtual by
default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift
shift >>> operator. >>> operator that fills zero at the
top for the negative numbers. For
positive numbers, it works same
like >> operator.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.
Note
o Java doesn't support default arguments like C++.
o Java does not support header files like C++. Java uses the import keyword to include different
classes and methods.
Created By: Krishna Patel Page 8
Bhagwan Mahavir University Java Programming

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM?

It is:

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


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 Architecture

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.

Created By: Krishna Patel Page 9


Bhagwan Mahavir University Java Programming

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.

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.

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.

Created By: Krishna Patel Page 10


Bhagwan Mahavir University Java Programming

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.

What is Java Bytecode?


Java bytecode is the instruction set for the Java Virtual Machine.

As soon as a java program is compiled, java bytecode is generated.

java bytecode is the machine code in the form of a .class file.

With the help of java bytecode we achieve platform independence in java.

How does it works?

When we write a program in Java, firstly, the compiler compiles that program and a bytecode is generated for that
piece of code.

When we wish to run this .class file on any other platform, we can do so.

After the first compilation, the bytecode generated is now run by the Java Virtual Machine.

This essentially means that we only need to have basic java installation on any platforms that we want to run our code
on

Created By: Krishna Patel Page 11


Bhagwan Mahavir University Java Programming

Advantages of bytecode:

• It helps in achieving the platform-independent goal with the help of bytecode.


• The set of instructions for JVM may differ from one system to another but all systems can run the bytecode.
• Bytecode runs only when the interpreter is available.
• It runs on the Java virtual machine only.
• It gives flexibility by giving a quote ‘Write code once, run code anywhere’.
• It also saves a lot of time for a programmer.
• It is of low cost however it gives a high return.

Disadvantages of Bytecode:

• It takes more time to run the bytecode that the machine code which is machine specific.
• It is difficult to use some platform-specific features because java is platform-independent.
• Mandatory installation of Java interpreter to run the byte code.

Difference between JDK, JRE, and JVM


JVM

JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically exist.

It is a specification that provides a runtime environment in which Java bytecode can be executed.

It can also run those programs which are written in other languages and compiled to Java bytecode.

However, Java is platform independent. There are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

• Loads code • Executes code


• Verifies code • Provides runtime environment

Created By: Krishna Patel Page 12


Bhagwan Mahavir University Java Programming

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. 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.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

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:

• Standard Edition Java Platform


• Enterprise Edition Java Platform
• Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an interpreter/loader (java),
a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the development of a Java
Application.

Created By: Krishna Patel Page 13


Bhagwan Mahavir University Java Programming

Java - Environment Setup


Steps for setting the environment in Windows operation system are as follows:

Step 1: Java8 JDK is available at Download Java 8. Click the second last link for Windows(32 bit) and the last link
for Windows(64 bit) as highlighted below.

Step 2: After download, run the .exe file and follow the instructions to install Java on your machine. Once you
installed Java on your machine, you have to set up the environment variable.

How to set path in Java


There are two ways to set the path in Java:

1. Temporary
2. Permanent

1) How to set the Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow the following steps:

• Open the command prompt


• Copy the path of the JDK/bin directory
• Write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

Let's see it in the figure given below:

Created By: Krishna Patel Page 14


Bhagwan Mahavir University Java Programming

(2) How to set Permanent Path of JDK in Windows

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

❖ Create the Java program / Compile and run the Java program

Creating Hello World Example

Let's create the hello java program:

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

Save the above file as Simple.java.

Created By: Krishna Patel Page 15


Bhagwan Mahavir University Java Programming

To compile: javac Simple.java

To execute: java Simple

Output:

Hello Java

Compilation Flow:

When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.

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 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. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument

System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.

To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shown below:

Created By: Krishna Patel Page 16


Bhagwan Mahavir University Java Programming

As displayed in the above diagram, write the simple program of Java in notepad and saved it as
Simple.java. In order to compile and run the above program, you need to open the command prompt
by start menu -> All Programs -> Accessories -> command prompt. When we have done with all
the steps properly, it shows the following output:

Created By: Krishna Patel Page 17


Bhagwan Mahavir University Java Programming

1. 5 Java Program Structure


Javan is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a wide
variety of applications. So, before diving in depth, it is necessary to understand the basic structure of
Java program in detail. In this section, we have discussed the basic structure of a Java program.

Let's see which elements are included in the structure of a Java program. A typical structure of
a Java program contains the following elements:

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

Created By: Krishna Patel Page 18


Bhagwan Mahavir University Java Programming

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:

//First Java Program


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

/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:

/**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 must be defined before any class and interface declaration. 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:

package SYBCA; //where SYBCA is the package name


package bmu.sybca; //where bmu is the root directory and sybca is the subdirectory
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:
Created By: Krishna Patel Page 19
Bhagwan Mahavir University Java Programming

import java.util.Scanner; //it imports the Scanner class only


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:

interface car
{
void start();
void stop();
}
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. A Java program may contain more than one class definition. We use
the class keyword to define the class. The class is a blueprint of a Java program. 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:

class Student //class definition


{
}
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:

class Student //class definition


{
String sname; //variable
int id;
double percentage; }

Created By: Krishna Patel Page 20


Bhagwan Mahavir University Java Programming

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:

public static void main(String args[])


{
}

For example:

public class Student //class definition


{
public static void main(String args[])
{
//statements
}
}
Methods and behavior

In this section, we define the functionality of the program by using the methods. The methods are the
set of instructions that we want to perform. These instructions execute at runtime and perform the
specified task. For example:

public class Demo //class definition System.out.println("Welcome to BMU");


{
public static void main(String args[]) }
{ //statements
void display() }
{ }
When we follow and use the above elements in a Java program, the program looks like the
following.

Created By: Krishna Patel Page 21


Bhagwan Mahavir University Java Programming

Java Command Line Arguments


The java command-line argument is an argument i.e. passed at the time of running the java
program.

The arguments passed from the console can be received in the java program and it can be used
as an input.

So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.

class CommandLineExample{

public static void main(String args[]){

System.out.println("Your first argument is: "+args[0]);

}}

compile by > javac CommandLineExample.java

run by > java CommandLineExample BMU

Output: Your first argument is: BMU

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.

1. class A{ compile by > javac A.java

public static void main(String args[]){ run by > java BMU BMEF 123 DS DK

for(int i=0;i<args.length;i++) Output: BMU

System.out.println(args[i]); }} BMEF

123 DS CS

Created By: Krishna Patel Page 22


Bhagwan Mahavir University Java Programming

System.out.println() in Java
In Java, System.out.println() is a statement which prints the argument passed to it. The println()
method display results on the monitor. Usually, a method is invoked by objectname.methodname().

PrintStream obj.print("Hello");

But you cannot create the object to PrintStream class directly as above. So, Java provides an
alternative way to create the object of PrintStream class that is System.out.

Where System is the class name, it is declared as final. The out is an instance of the System class
and is of type PrintStream. Its access specifiers are public and final. It is an instance of
java.io.PrintStream. When we call the member, a PrintStream class object creates internally.

So, we can call the print() method, as shown below:

System.out.print();

It creates the PrintStream class object. This object, by default, represents the output device, i.e., the
monitor.

Example

In the following example, we have used two print() methods, which gives the result in one line. It
means the first print() method displays the string "Hello!" and retains the cursor at the same line.
The second print() method also displays the string "Java" at the same line adjacent to the previous
string.

class Demo {
public static void main(String args[]) { output:
System.out.print("Hello!"); Hello!Java
System.out.print("Java");
} }

Created By: Krishna Patel Page 23


Bhagwan Mahavir University Java Programming

Java println() method

The println() method is similar to print() method except that it moves the cursor to the next line
after printing the result. It is used when you want the result in two separate lines. It is called with
"out" object.

If we want the result in two separate lines, then we should use the println() method. It is also an
overloaded method of PrintStream class. It throws the cursor to the next line after displaying the
result.

Example

The following example, the println() method display the string in two separate lines.

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

Output

Hello!
Java
Difference between print() and println() methods

Both methods are used to display the results on the monitor. The print() method displays the result
on the console and retains the cursor in the same line. It works only with an argument. The
println() method also displays the result on the console but moves the cursor to the next line. It can
also work without arguments.

Created By: Krishna Patel Page 24

You might also like