0% found this document useful (0 votes)
3 views36 pages

Chapter 1 Introduction

Java is a general-purpose, object-oriented programming language developed by Sun Microsystems in 1996, known for its platform independence and extensive application across various domains including desktop, web, and mobile applications. It features a robust architecture that supports security, portability, and high performance, and has evolved through numerous versions since its inception. The document also compares Java with C++, highlighting key differences and outlining the Java development environment, including the Java Development Kit (JDK) and Java Standard Library (API).
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Chapter 1 Introduction

Java is a general-purpose, object-oriented programming language developed by Sun Microsystems in 1996, known for its platform independence and extensive application across various domains including desktop, web, and mobile applications. It features a robust architecture that supports security, portability, and high performance, and has evolved through numerous versions since its inception. The document also compares Java with C++, highlighting key differences and outlining the Java development environment, including the Java Development Kit (JDK) and Java Standard Library (API).
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 1

Introduction to JAVA
Introduction

Java is a general-purpose, object-oriented programming language and a


plateform developed by Sun Microsystems of USA in the year 1996. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since
Oak was already a registered company, so James Gosling and his team
changed the Oak name to Java.

Platform: Any hardware or software environment in which a program runs, is


known as a platform. Since Java has a runtime environment (JRE) and API, it
is called a platform.

Now it is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

� Desktop Applications such as acrobat reader, media player, antivirus,


etc.
� Web Applications such as reservation sites etc.
� Enterprise Applications such as banking applications.
� Mobile
� Embedded System
� Smart Card
� Robotics
� Games.
� Database connection
� And much, much more!

1.1 Why Use Java?

� Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,


etc.)
� It is one of the most popular programming language in the world.
� It is easy to learn and simple to use
� It is open-source and free
� It has a huge community support (tens of millions of developers)
� Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
� As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 1
1.2 Java History:

James Gosling is a famous Canadian software developer who has


been with Sun Microsystems since 1984 and is considered as father of Java
programming language. Gosling did the original design of Java and
implemented its original compiler and virtual machine.

� In 1991, Project Manager James Gosling and his team members Patrick
Naughton, Mike Sheridan, Chris Wrath, and Ed Frank of Sun Micro
Systems Inc.(US) were conceived a project to develop software (which
should be portable and machine independent) for consumer electronic
devices such set-top boxes, televisions etc that could be controlled by a
remote. This small team of sun engineers called Green Team.

� Gosling thought C and C++ would be used to develop the project. But the
problem he faced with them is that they were system dependent languages.
The trouble with C and C++ (and most other languages) is that they are
designed to be compiled for a specific target and could not be used on
various processors, which the electronic devices might use.

� James Gosling with his team started developing a new language,


which was completely system independent. This language was initially
called OAK (Oak is a symbol of strength and chosen as a national tree of
many countries like U.S.A., France, Germany, Romania etc.). Since this
name was registered by some other company, later it was changed to Java.

� James Gosling and his team members were consuming a lot of coffee while
developing this language. Good quality of coffee was supplied from a place
called “Java Island’. Hence they fixed the name of the language as Java. The
symbol for Java language is cup and saucer.

� Sun formally announced Java at Sun World conference in 1995. On


January 23rd 1996, JDK1.0 version was released. Bill Joy, Arthur van Hoff,
Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to
the maturing of the original prototype.

� Latest version of Java is Java 15 or JDK 15.1.0 released on 15th


Sept'2020. With Java 8 release, java provided supports for functional
programming, new JavaScript engine, new APIs for date time
manipulation, new streaming API etc.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 2
1.3 Java Version History

From the first version released in 1996 to the latest Standard Edition (SE)
version 15 released in Sept 2020.

Java SE
Version Version Release Date
Number

JDK 1.0 1.0 January 1996


(Oak)

JDK 1.1 1.1 February 1997

J2SE 1.2 1.2 December 1998


(Playground)

J2SE 1.3 1.3 May 2000


(Kestrel)

J2SE 1.4 1.4 February 2002


(Merlin)

J2SE 5.0 1.5 September 2004


(Tiger)

Java SE 6 1.6 December 2006


(Mustang)

Java SE 7 1.7 July 2011


(Dolphin)

Java SE 8 1.8 March 2014

Java SE 9 9 September, 21st


2017

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 3
Java SE 10 10 March, 20th 2018

Java SE 11 11 September, 25th


2018

Java SE 12 12 March, 19th 2019

Java SE 13 September, 17th


13
2019

Java SE 14 14 March, 17th 2020

Java SE 15 15 September, 15th


2020

Java SE 16 16 March 2021

Java SE 17 17 September, 2021

Java SE 18 18 March 2022

1.4 JAVA FEATURES:

Features of Java

Features of a language are nothing but the set of services or facilities provided
by the language vendors to the industry programmers. Some
important features of java are:

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 4
Figure 1.1 Shows the features of Java

� Simple: Learning and practicing java is easy because of resemblance


with c and C++.
� Object Oriented Programming Language: Unlike C++, Java is purely
OOP.
� Secure: Java achieves this protection by confining a Java program to
the Java execution environment and by making it inaccessible to other
parts of the computer. It is a more secure language compared to other
language; In this language, all code is covered in byte code after
compilation which is not readable by human or machine except JVM.

� Plate-form Independent & Architectural Neutral: Java development


team work on the philosophy of write once; run anywhere, anytime,
forever” and as a result the Java Virtual Machine (JVM) was developed.
� Only the JVM can execute the bytecode. Java byte code is not machine
dependent; it can run on any machine with any processor and with any
OS.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 5
In the Java programming language, all source code is first written in
plain text files ending with the .java extension. Those source files are
then compiled into .class files by the javac compiler. A .class file does not
contain code that is native to your processor; it instead
contains bytecodes — the machine language of the Java Virtual
Machine (Java VM).

Because the Java VM is available on many different operating systems,


the same .class files are capable of running on Microsoft Windows, Mac
OS or Linux etc.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 6
� Portable: In Java, many types of computers and operating system are in
use throughout the world and are connected to the Internet. For
downloading programs through different platforms connected to the
Internet, some portable, executable code is needed. Java does not have
implementation dependent aspects and it yields or gives same result
on any machine.

� 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

� Distributed: In distributed application multiple client system depends on


multiple server systems so that even problem occurred in one server will
never be reflected on any client system. In java we can create distributed
applications using RMI (Remote Method Invocation), EJB (Enterprises
Java Beans) and has extensive set of library which works in agreement
with TCP/IP to designed network based application.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 7
� Robust (Strong/ Powerful): Most programs in use today fail for one of
the two reasons: memory management or exceptional conditions. Thus,
the ability to create robust programs was given a high priority in the
design of Java. Java forces the user to find mistake in the early stages of
program development. Java checks code at compilation time. However, it
also checks the code at run time also. Java programs will not crash
because of its exception handling and its memory management
features.

� Interpreted: Java programs are compiled to generate the byte code.


This byte code can be downloaded and interpreted by the interpreter.
.class file will have byte code instructions and JVM which contains an
interpreter will execute the byte code.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 8
� High Performance:
It has high performance because of following reasons:
� Garbage collector, collect the unused memory space and improve the
performance of the application.
� It support multithreading, because of this time consuming process
can be reduced to executing the program.
� Along with interpreter there will be JIT (Just In Time) compiler which
enhances the speed of execution.
� Multithreaded: Executing different parts of program simultaneously is
called multithreading. This is an essential feature to design server side
programs.
� Dynamic: We can develop programs in Java which dynamically
change on Internet (e.g.: Applets).

1.5 COMPARISON IN JAVA AND C++

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-


Java is platform-independent.
independent dependent.

Java is mainly used for


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

Java was designed and created as


C++ was designed for an interpreter for printing
systems and applications systems but later extended as a
Design Goal programming. It was an support network computing. It
extension of the C was designed to be easy to use
programming language. and accessible to a broader
audience.

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


Goto
statement. statement.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 9
Java doesn't support multiple
Multiple C++ supports multiple inheritance through class. It can
inheritance inheritance. be achieved by using interfaces in
java.

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


Overloading overloading. overloading.

Java supports pointer internally.


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

Java uses both compiler and


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

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

Structure and C++ supports structures Java doesn't support structures


Union and unions. and unions.

C++ doesn't have built-in


support for threads. It
Thread Support relies on third-party Java has built-in thread support.
libraries for thread
support.

Java supports documentation


C++ doesn't support
Documentation comment (/** ... */) to create
documentation
comment documentation for java source
comments.
code.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 10
Java has no virtual keyword. We
C++ supports virtual
can override all non-static
keyword so that we can
Virtual Keyword methods by default. In other
decide whether or not to
words, non-static methods are
override a function.
virtual by default.

Java supports unsigned right


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

Java always uses a single


inheritance tree because all
C++ always creates a new classes are the child of the Object
Inheritance Tree
inheritance tree. class in Java. The Object class is
the root of the inheritance tree in
java.

C++ is nearer to Java is not so interactive with


Hardware
hardware. hardware.

Java is also an object-oriented


C++ is an object-oriented
language. However, everything
language. However, in
(except fundamental types) is an
Object-oriented the C language, a single
object in Java. It is a single root
root hierarchy is not
hierarchy as everything gets
possible.
derived from [Link].

1.6 JAVA ENVIRONMENT


Java environment includes a large number of development tools and thousands
of classes and methods. The development tools are part of the system known as
Java Development Kit (JDK) and classes and methods are part of the Java
standard Library (JSL), also known as the Application Programming
Interface (API).

1.6.1 JAVA DEVELOPMENT KIT

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 11
The Java Development Kit comes with a collection of tools that are used for
developing and running Java programs. They include:

Appletviewer (for running Java applets) : Enable us to run Java


Applets(without actually using a Java-compatible browser).

Javac (Java compiler) : Which translates Java sourcecode to bytecode files


that interpreter can understand.

Java (Java Interpreter) : Which runs applets and applications by reading and
interpreting bytecode.

Javap(Java disassemble) : Which enables us to convert bytecode files into a


program description.

Javah (for C header files) : Produce header file for use with native methods.

Javadoc (for creating HTML documents): Create HTML-format


documentation from Java source code files.

Jdb(Java debugger) : Which helps use to find errors in our programs.

1.6.2 APPLICATION PROGRAMMING INTERFACE

The Java Standard Library (or API) includes thousands of classes and methods
grouped into several functional packages. Most commonly used packages are:

Language support Package: A collection of classes and methods required for


implementing basic features of Java. [Link]

Utilities packages: A collection of classes to provide utility functions such as


date and time functions. [Link]

Input/Output package: A collection of classes required for input/output


manipulation. [Link]

Networking package: A collection of classes for communicating with other


computers via internet. [Link]

Applet package: This includes as set of classes that allows us to create Java
applets. [Link]

1.6.3 JAVA RUNTIME ENVIRONMENT

The Java runtime Environment (JRE) allows the execution of programs


developed in Java. It primarily comprises of the following:

Java Virtual Machine: It converts bytecode into machine code.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 12
Runtime class libraries: These are the set of core class libraries that are
required for the execution of Java program

User Interface toolkits: AWT and Swings are the examples of toolkit the
support varied input methods for the users to interact with the application
program.

1.7 JAVA VIRTUAL MACHINE

Java Virtual Machine (JVM) is the heart of entire Java program execution
process. First of all, the .java program is converted into a .class file consisting
of byte code instructions by the java compiler at the time of compilation.
Remember, this java compiler is outside the JVM. This .class file is given to the
JVM. JVM mainly performs following operations.

� Allocating sufficient memory space for the class properties.

� Provides runtime environment in which java bytecode can be executed

� Converting byte code instruction into machine level instruction.


JVM is separately available for every Operating System while installing java
software so that JVM is platform dependent.

Note: Java is platform Independent but JVM is platform dependent because


every Operating system have different-different JVM which is install along
with JDK Software.

Following figure shows the architecture of Java Virtual Machine.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 13
Figure :The internal architecture of the Java virtual machine.

In JVM, there is a module (or program) called class loader sub system,
which performs the following instructions:

� First of all, it loads the .class file into memory.


� Then it verifies whether all byte code instructions are proper or not. If it
finds any instruction suspicious, the execution is rejected immediately.
� If the byte instructions are proper, then it allocates necessary
memory to execute the program. This memory is divided into 5 parts,
called run time memory areas, which contain the data and results
while running the program. These areas are as follows:

1. Heap Area – All the Objects and its corresponding instance


variables and arrays will be stored here.
2. Method Area – All the Class level data will be stored
here including static variables Static method and static block.
3. Java Stack Area – In which all the non-static variable of class will be
stored and whose address referred by object reference.
4. For every thread, a separate runtime stack will be created. For
every method call, one entry will be made in the stack memory which is
called as Stack Frame. All local variables will be created in the stack
memory. Stack area is thread safe since it is not a shared resource.
Stack Frame is divided into three sub-entities such as
a. Local Variable Array – Related to the method how many local
variablesare involved and the corresponding values will be stored
here.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 14
b. Operand stack – If any intermediate operation is required to
perform, operand stack act as runtime workspace to perform the
operation.
c. Frame data – All symbols corresponding to the method is stored
here. In the case of any exception, the catch block information will
be maintained in the frame data.
5. PC Registers – Each thread will have separate PC Registers, to hold
address of current executing instruction once the instruction is
executed the PC register will be updated with the next instruction. It
holds the address of next executable instruction that means that use the
priority for the method in the execution process?
6. Native Method Stacks: When a Java application invokes a native
method, that application does not only use Java Stacks but also uses
the native method stack for the execution of native methods (for example
C/C++ functions). To execute the native methods, generally native
method libraries (for example C/C++ header files) are required. The
libraries required for the execution of native methods are available to the
Java Virtual Machine through Java Native Interface.

7. Execution Engine Which contains Interpreter and JIT


compiler whenever any java program is executing at the first time
interpreter will comes into picture and it converts one by one byte code
instruction into machine level instruction JIT compiler (just in time
compiler) will comes into picture from the second time onward if the
same java program is executing and it gives the machine level instruction
to the process which are available in the buffer memory. JVM will
identify the Hot spots in the .class files and it will give it to JIT
compiler where the normal instructions and statements of Java
program are executed by the Java interpreter.

Note: The main aim of JIT compiler is to speed up the execution of java
program.
Generally, any language (like C/C++, pascal, cobol, etc.) will use either an
interpreter or a compiler to translate the source code into a machine code.
But in JVM, we got interpreter and JIT compiler both working at the same
time on byte code to translate it into machine code. Now, the main question is
why both are needed and how both work simultaneously? To understand this,
let us take some sample code. Assume these are byte code instructions:
print a;
print b;
Repeat the following 10 time by changing i value from 1 to 10.
When, the interpreter starts execution from 1 st instruction, it converts print
a; into machine code and gives it to the microprocessor, For this, say the
interpreter has taken 2 nanoseconds time. The processor takes it, executes it,
and the value of a is displayed.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 15
Now the interpreter comes back into memory and reads the 2 nd instruction
print b;. To convert this into machine code, it takes another 2 nanoseconds.
Then the instruction is given to the processor and it execute it.
Next, the interpreter comes to the 3 rd instruction, which is a looping
statement print a; This should be done 10 times and this is known to the
interpreter. Hence, the first time it converts print a; into machine code, it
takes 2 nanosecond. After giving the instruction to the processor, it comes
back to the memory and reads the print a instruction the 2 nd time converts it
to machine code. This will take another 2 nanoseconds. This will given to the
processor to execute. Like this, the interpreter will convert the print a
instruction for 10 times, consuming a total of 10 x 2 = 20 nanoseconds. This
procedure is not efficient in terms of time. That is the reasons why JVM does
not allocate this code to the interpreter. It allows this code to the JIT compiler.
Let us see how JIT compiler will execute the looping instruction. First of all,
the JIT compiler reads the print a instruction and converts that into machine
code. For this, say, it is taking 2 nanoseconds. Then the JIT compiler allots a
block of memory and pushes this machine code instruction into that memory.
For this, say, it is taking another 2 nanoseconds. This means JIT compiler
has taken a total of 4 nanoseconds. Now, the processor will fetch this
instruction from memory and execute it 10 times. Just observe that the JIT
compiler has taken only 4 nanoseconds for execution; whereas to execute the
same loop, the interpreter needs 20 nanoseconds. Thus, JIT compiler increase
the speed of execution.

Byte Code: It is the unique characteristic property of the Java programming


language. It is something like a normal text file. Therefore, it cannot be affected
by virus. It is an intermediate between a human readable source and machine
readable source. Byte codes are plateform-independent. Therefore, JVM is
plateform dependent to make Java programming plateform independent.

1.7 Process of Compiling and Running a Java Application


Program
All Java source code is written in text editor and saved with the .Java
extension. Source code file are compiled into .class file by the java compiler. A
.class file contains byte codes (plate-form independent intermediate code
between a human readable source and machine readable source).

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 16
Figure Abstract view of Java program execution.

JVM works on different operating systems. The .class files (bytecode) can run
on various operating systems. JVM converts bytecode into computer-readable
machine code that can be executed.

Compiling: is the process of translating source code written in a particular


programming language into computer-readable machine code that can be
executed.

C:\> javac [Link]

This command will produce a file ‘[Link]’, which is used for running the
program with the command ‘java’.

Running: is the process of executing program on a computer.

C:\> java Sample

1.8 Java divided into three categories, they are


� J2SE (Java 2 Standard Edition) J2SE is used for developing client side
applications.
� J2EE (Java 2 Enterprise Edition) J2EE is used for developing server side
applications.
� J2ME (Java 2 Micro or Mobile Edition) J2ME is used for developing mobile or
wireless application by making use of a predefined protocol called WAP(wireless
Access / Application protocol).

1.9 How to Set Path and Classpath in Java

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 17
Setting path and classpath in Java is very simple but before do this process
you need to know about path variable and classpath variable. Here I will
show you how to set path and classpath in Java in very simple and easy
way.

Path Variable
Path variable is set for providing path for all Java tools like java, javac,
javap, javah, jar, appletviewer which are used in java programming. All these
tools are available in bin folders so we set path upto bin folders.

Classpath Variable
Classpath variable is set for providing a path for predefined Java classes
which is used in our application. All classes are available in lib/[Link] so we
set classpath upto lib/[Link].

JDK Folder Hierarchy

Why set path ?


The following programming error is generally for all Java programmers when
they compile any Java program.
'javac' is not recognized as an internal or external command, operable
program or batch file.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 18
When you get this type of error, then your operating system cannot find the
Java compiler (javac). To solve this error you need to set the PATH variable.
Javac is a tool which is available in bin folder so you must set the PATH
upto bin folder. In a bin folder all tools are available like javap, javah, jar,
javac, java, appletviewer etc. All these tools are used for different-different
purpose.

set the path and classpath


Go on my computer icon and right click, after that click on properties option.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 19
Now click on advance setting

Click on advance

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 20
Click on Advance variables

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 21
Click on new button which is below the first box.

Now one dilog box is appear, now ignore this but do not close.

Now open my computer open c:/ > Programs Files > java > java1.6.0 > bin
copy this path

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 22
Now come back on previous open dilogbox and write variable
name 'path' and for variable value paste all copied path upto the bin folder.
Put .; at the end. It (.) selects all the tools from the bin folder.

Now open my computer open c:/ > Programs Files > java > java1.6.0 > jre >
lib > [Link] copy this path
Note: [Link] is available in lib folder this jar files contains all classes of jdk.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 23
Now again come back on Environment variable dilogbox and click on new.
Now one box is open and write path variable as 'classpath' and for variable
value paste all copied paths upto [Link]. Put .; at the end. It (.) selects all the
classes from lib folder.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 24
Note: Finally after set classpath restart your system, or you can re-open
command prompt.

1.10 Structure of the Java Program:

As all other programming languages, Java also has a structure.


� There could be only one public class per source code file but it can have
multiple non public class.
� In case there is any public class present in source code file, name of the
file should be the class name.
� Sequence of difference statement in source code file would be package
>> import >> Class declaration.
� No Sequence rule is applied for Comments. Comments can be there in any
part of the source code file at any location.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 25
� File with no public class can have any name there is no rule applied for
the same.
� Import and package statements applied to all the classes in same
source code file.

1.11 Rules Applied on Java Source Code File


Classes are written in Java source file. A source file can contain more than one
Java class. Below are the rules related to Java source code file?

� The first line of the C/C++ program contains include statement. For
example, <stdio.h> is the header file that contains functions, like
printf (), scanf () etc. So if we want to use any of these functions, we
should include this header file in C/ C++ program.
� Similarly in Java first we need to import the required packages. By
default [Link].* is imported. Java has several such packages in its
library.
� A package is a kind of directory that contains a group of related classes
and interfaces. A class or interface contains methods.
� Since Java is purely an Object Oriented Programming language,
we cannot write a Java program without having at least one class or
object.
� So, it is mandatory to write a class in Java program. We should use
class keyword for this purpose and then write class name.
� In C/C++, program starts executing from main method similarly in
Java, program starts executing from main method. The return type of
main method is void because program starts executing from main
method and it returns nothing.

1.12 Naming Conventions


Naming conventions specify the rules to be followed by a Java
programmer while writing the names of packages, classes, methods etc.

� Package names are written in small letters.

e.g.: [Link], [Link], [Link] etc

� Each word of class name and interface name starts with a capital

e.g.: Sample, AddTwoNumbers

� Method names start with small letters then each word start with a
capital

e.g.: sum (), sumTwoNumbers (), minValue ()

� Variable names also follow the same above method rule

e.g.: sum, count, totalCount

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 26
� Constants should be written using all capital letters

e.g.: PI, COUNT

� Keywords are reserved words and are written in small letters.

e.g.: int, short, float, public, void

1.13 First Java Program

Save the above file as [Link].


To compile: javac [Link]
To execute: java Sample

� Since Java is purely an Object Oriented Programming language, without


creating an object to a class it is not possible to access methods and
members of a class.
� But main method is also a method inside a class, since program
execution starts from main method we need to call main method without
creating an object.
� Static methods are the methods, which can be called and executed
without creating objects.
� Since we want to call main() method without using an object, we
should declare main() method as static. JVM calls main() method
using its [Link]() at the time of running the program.

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.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 27
� JVM is a program written by Java Soft people (Java development
team) and main() is the method written by us. Since, main () method
should be available to the JVM, it should be declared as public. If we
don’t declare main () method as public, then it doesn’t make itself
available to JVM and JVM cannot execute it.
� JVM always looks for main() method with String type array as
parameter otherwise JVM cannot recognize the main() method, so we
must provide String type array as parameter to main () method. Main()
method having signature with default variable arguments.

� A class code starts with a {and ends with a}.


� A class or an object contains variables and methods (functions). We
can create any number of variables and methods inside the class.
� This is our first program, so we had written only one method called
main().
� Our aim of writing this program is just to display a string “Hello
world”.
� In Java, print() or write() method is used to display something on the
monitor.
� A method should be called by using [Link](). So, to
call print() method, create an object to PrintStream class then call
[Link]() method.
� An alternative is given to create an object to PrintStream Class i.e.
[Link].
� Here, System is the class name and out is a static variable in System
class out is called a field in System class.
� When we call this field a PrintStream class object will be created
internally. So, we can call print() method as: [Link] (“Hello
world”);
� println() is also a method belonging to PrintStream class. It throws the
cursor to the next line after displaying the result.
� In the above Sample program System and String are the classes present
in [Link] package.

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with
OS) and converts the java code into bytecode.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 28
What happens at runtime?

At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.


Bytecode Verifier: checks the code fragments for illegal code that can violate
access right to objects.
Interpreter: read bytecode stream then execute the instructions.

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

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 29
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.

Example
1. class CommandLineExample{
2. public static void main(String args[]){
3. [Link]("Your first argument is: "+args[0]);
4. }
5. }

compile by > javac [Link]

run by > java CommandLineExample Do Good

Output: Your first argument is: Do

Example
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{
2. public static void main(String args[]){
3.
4. for(int i=0;i<[Link];i++)
5. [Link] (args[i] + “ ”);
6.
7. }
8. }

compile by > javac [Link]

run by > java A Do 10 Good 20 Have 30 Good

Output:
Do 10 Good 20 Have 30 Good

1.15. Recommended Reading


The Java Platform
A platform is the hardware or software environment in which a program runs.
We've already mentioned some of the most popular platforms like Microsoft
Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as
a combination of the operating system and underlying hardware. The Java

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 30
platform differs from most other platforms in that it's a software-only platform
that runs on top of other hardware-based platforms.
The Java platform has two components:
� The Java Virtual Machine
� The Java Application Programming Interface (API)

Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:

To compile: javac [Link]


To execute: java Simple

Q) Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 31
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. 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.
The JVM performs the following main tasks:

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

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.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 32
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:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o 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.

What is Java?

Java is the high-level, object-oriented, robust, secure programming language,


platform-independent, high performance, Multithreaded, and portable
programming language. It was developed by James Gosling in June 1991. It
can also be known as the platform as it provides its own JRE and API.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 33
If I don't provide any arguments on the command line, then what will the
value stored in the String array passed into the main() method, empty or
NULL?

It is empty, but not null.

What if I write static public void instead of public static void?

The program compiles and runs correctly because the order of specifiers
doesn't matter in Java.
Difference between Java and C++

Please refer to the topic 1.5 COMPARISON IN JAVA AND C++

What do you understand by Java virtual machine?


Please refer to the topic 1.7 JAVA VIRTUAL MACHINE

What is Core Java?

Java SE is also called Core Java. It is the set of libraries that are part of
standard java installation. For example, the Collections framework is part of
Core Java. But, Servlet/JSP is part of Java Enterprise Edition.

Who Created Java?

Java was first created by James Gosling at Sun Microsystems. The first public
version was released in 1996.

What is the latest version of Java?

Java 15 is the latest version, released on Sept 15, 2020. Now, Oracle releases a
new java version every 6 months.

Why is Java known as the Platform Independent Programming Language?

The ease of executing the code on any platform makes this language a
Platform Independent Programming Language. Just by installing JDK
software on a system, JVM also gets installed automatically. This JVM (Java
virtual machine) is the one that can execute Java bytecode. Each Java source
file is compiled into a bytecode file, which is later executed by the JVM. Java
was designed with a motto to allow the programs to be run on any platform,
without the need of rewriting or compiling them each time recompile for
different platforms.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 34
Define the Java’s WORA nature?
WORA means Write Once Run Anywhere. Java is compiled to a bytecode
which does not platform specific. This bytecode is the intermediate language
between the source code and the machine code. As the bytecode is not
platforming specific, so it can be used to any platform. Sometimes, it is also
called WORE – Write Once Run Everywhere.

How can we execute any code even before the main method?
If we want to execute any statements before the even creation of objects at
load time of class, we can use a static block of code in the class. Any
statements inside this static block of code will get executed once at the time
of loading the class even before the creation of objects in the main method.

What is classloader?

The classloader is a subsystem of JVM that is used to load classes and


[Link] are many types of classloaders e.g. Bootstrap classloader,
Extension classloader, System classloader, Plugin classloader etc.

Prepared by: Dr. Mahesh Manchanda Department of CSE, Graphic Era Hill University, Dehradun 35
This document was created with the Win2PDF “Print to PDF” printer available at
[Link]
This version of Win2PDF 10 is for evaluation and non-commercial use only.
Visit [Link] for a 30 day trial license.
This page will not be added after purchasing Win2PDF.
[Link]

You might also like