0% found this document useful (0 votes)
12 views14 pages

module1

Java is a versatile programming language created in 1995, widely used for mobile, desktop, and web applications, and known for its portability and security features. Key characteristics include being object-oriented, robust, platform-independent, and having a strong community support. The document also covers the Java Virtual Machine (JVM) architecture, the process of starting a Java program, and the concept of Java packages for organizing classes and interfaces.

Uploaded by

mrpctechnologies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

module1

Java is a versatile programming language created in 1995, widely used for mobile, desktop, and web applications, and known for its portability and security features. Key characteristics include being object-oriented, robust, platform-independent, and having a strong community support. The document also covers the Java Virtual Machine (JVM) architecture, the process of starting a Java program, and the concept of Java packages for organizing classes and interfaces.

Uploaded by

mrpctechnologies
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

1.

INTRODUCTION TO JAVA
What is Java?

Java is a popular programming language, created in 1995.

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

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

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 is secure, fast and powerful
 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

https://www.w3schools.com/java/java_intro.asp
FEATURES OF JAVA
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that
played an important role in moulding out the final form of this outstanding language. Those
features are :

1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand.The
confusing and ambiguous concepts of C++ are either left out in Java or they have been re-
implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C+
+.
2) Object Oriented
In java, everything is an object which has some data and behaviour. Java can be easily
extended as it is based on Object Model. Following are some basic concept of OOP's.

i. Object
ii. Class
iii. Inheritance
iv. Polymorphism
v. Abstraction
vi. Encapsulation

3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.

4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide security.
Any machine with Java Runtime Environment can run Java Programs.

5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable
us to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources
to execute multiple threads at the same time, like While typing, grammatical errors are
checked along.

7) Architectural Neutral
Compiler generates byte codes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to interpret on any machine.

8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types

9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C+
+. But, Java enables high performance with the use of just-in-time compiler.

10) Distributed
Java is also a distributed language. Programs can be designed to run on computer networks.
Java has a special class library for communicating using TCP/IP protocols. Creating network
connections is very much easy in Java as compared to C/C++.

New Features of JAVA 8


Below mentioned are some of the core upgrades done as a part of Java 8 release. Just go
through them quickly, we will explore them in details later.

 Enhanced Productivity by providing Optional Classes feature, Lamda Expressions,


Streams etc.
 Ease of Use
 Improved Polyglot programming. A Polyglot is a program or script, written in a form
which is valid in multiple programming languages and it performs the same
operations in multiple programming languages. So Java now supports such type of
programming technique.
 Improved Security and performance.

New Features of JAVA 11


Java 11 is a recommended LTS version of Java that includes various important features.
These features includes new and upgrades in existing topic. Just go through them quickly, we
will explore them in details later.
 includes support for Unicode 10.0.0
 The HTTP Client has been standardized
 Lazy Allocation of Compiler Threads
 Updated Locale Data to Unicode CLDR v33
 JEP 331 Low-Overhead Heap Profiling
 JEP 181 Nest-Based Access Control
 Added Brainpool EC Support (RFC 5639)
 Enhanced KeyStore Mechanisms
 JEP 332 Transport Layer Security (TLS) 1.3
 JEP 330 Launch Single-File Source-Code Programs

https://www.studytonight.com/java/features-of-java.php

3. THE JAVA VIRTUAL MACHINE

JVM (Java Virtual Machine) Architecture


1. Java Virtual Machine
2. Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java byte code 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. 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 class loader, memory area,
execution engine etc.
1) Class loader

Class loader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the class loader. There are three built-in class loaders 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 classloader
12. System.out.println(String.class.getClassLoader());
13. }
14. }

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.

https://www.javatpoint.com/jvm-java-virtual-machine

 3.STARING A JAVA PROGRAM


The basic steps to create the Hello World program are: write the program in Java, compile the
source code, and run the program.

Write the Java Source Code

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

All Java programs are written in plain text — therefore you don't need any special software.
For your first program, open up the simplest text editor you have on your computer, likely
Notepad.

The entire program looks like this:

While you could cut and paste the above code into your text editor, it’s better to get into the
habit of typing it in. It will help you learn Java more quickly because you will get a feel for
how programs are written, and best of all, you will make mistakes! This may sound odd, but
each mistake you make helps you to become a better programmer in the long run. Just
remember that your program code must match the example code, and you’ll be fine.

Note the lines with "//" above. These are comments in Java, and the compiler ignores them.

1. Line //1 is a comment, introducing this program.


2. Line //2 creates a class HelloWorld. All code needs to be in a class in order for the
Java runtime engine to run it. Note that the entire class is defined within enclosing
curly braces (on line /2 and line //6).
3. Line //3 is the main() method, which is always the entry point into a Java program. It
also is defined within curly braces (on line //3 and line //5). Let's break it down:
public: This method is public and therefore available to anyone.
static: This method can be run without having to create an instance of the class
HelloWorld.
void: This method does not return anything.
(String[] args): This method takes a String argument.
4. Line //4 writes "Hello World" to the console.

Save the File

Microsoft product screen shot(s) reprinted with permission from Microsoft


Corporation.

Save your program file as "HelloWorld.java". You might consider creating a directory on
your computer just for your Java programs.

It’s very important that you save the text file as "HelloWorld.java". Java is picky about
filenames. The code has this statement:
This is an instruction to call the class "HelloWorld". The filename must match this class
name, hence the name "HelloWorld.java". The extension ".java" tells the computer that it’s
a Java code file.

Open a Terminal Window

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

Most programs that you run on your computer are windowed applications; they work inside a
window that you can move around on your desktop. The HelloWorld program is an example
of a console program. It does not run in its own window; it has to be run through a terminal
window instead. A terminal window is just another way of running programs.

To open a terminal window, press the "Windows key" and the letter “R”.

You will see the "Run Dialog Box". Type "cmd" to open the command window, and press
"OK".

A terminal window opens on your screen. Think of it as a text version of Windows Explorer;
it will let you navigate to different directories on your computer, look at the files they
contain, and run programs. This is all done by typing commands into the window.

The Java Compiler

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

Another example of a console program is the Java compiler called "javac." This is the
program that will read the code in the HelloWorld.java file, and translate it into a language
your computer can understand. This process is called compiling. Every Java program you
write will have to be compiled before it can be run.

To run javac from the terminal window, you first need to tell your computer where it is. For
example, it might be in a directory called "C:\Program Files\Java\jdk\1.6.0_06\bin". If you
don’t have this directory, then do a file search in Windows Explorer for "javac" to find out
where it lives.

Once you’ve found its location, type the following command into the terminal window:

E.g.,

Press Enter. The terminal window will just return to the command prompt. However, the path
to the compiler has now been set.

Change the Directory


Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

Next, navigate to the location your HelloWorld.java file is saved.

To change the directory in the terminal window, type in the command:

E.g.,

You can tell if you’re in the right directory by looking to the left of the cursor.

Compile Your Program

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

We’re now ready to compile the program. To do so, enter the command:

Press Enter. The compiler will look at the code contained within the HelloWorld.java file,
and attempt to compile it. If it can’t, it will display a series of errors to help you fix the code.

Hopefully, you should have no errors. If you do, go back and check the code you’ve written.
Make sure it matches the example code and re-save the file.

Tip: Once your HelloWorld program has been successfully compiled, you will see a new file
in the same directory. It will be called “HelloWorld.class”. This is the compiled version of
your program.

Run the Program

Microsoft product screen shot(s) reprinted with permission from Microsoft Corporation.

All that’s left to do is run the program. In the terminal window, type the command:

When you press Enter, the program runs and you will see "Hello World!" written to the
terminal window.

Well done. You’ve written your very first Java program!

https://www.thoughtco.com/creating-your-first-java-program-2034124

4.JAVA IMPORT CLASSES


Java Import Classes: A package is the style of Java to group the classes and interfaces
together, or to say, a package is a collection of related predefined classes and interfaces.
Packages are sets of classes and interfaces built into Java Development Kit (JDK). A package
places restrictions (to the classes of other packages) to access its enclosed classes. Access
specifiers work on package boundaries (between the classes of different packages).

Java Import Classes: Definition and Importance

A package is a group of related classes and interfaces. The JDK software is organized
through packages. It is equivalent to a header file of C-lang and module of Modula language
(Modula is a descendent of Pascal). Packages can be compressed into JAR files (refer xxxx)
so that they can be downloaded or sent across the network fast.

Java Import Classes: Advantages of Packages

1. With a simple import statement, all the classes and interfaces can be imported. 2. Java
includes a provision to import only one class from a package. 3. It avoids namespace
problems (name conflicts). Two classes with the same name cannot be put in the same
package but can be put in two different packages because a package creates its own
namespace (folder). 4. Access for the classes can be controlled. 5. Classes and interfaces of
same functionality can be grouped together. 6. Because functionally all the classes are
related, later their identification and determining the location become easier. 7. Java packages
are used to group and organize the classes.

Java Import Classes: Importing All/Single Class

Java permits to import all the classes or only one class from a package. C-lang does not have
this facility of including only one function from a header file.

importjava.util.*; // imports all the classes and interfaces


importjava.awt.event.*;// imports all the classes and interfaces

importjava.util.Stack;// imports only Stack class


importjava.awt.event.ActionEvent;// imports only ActionEvent class
// observe, no asterisk, *

Importing Classes – Different Approaches

There are three ways to access a class or an interface that exits in a different package.

1. Using fully qualified name 2. Importing only one class 3. Importing all the classes

1. Using Fully Qualified Name

Fully qualified name includes writing the names of the packages along with the class name as
follows.

java.awt.event.ActionListenerjava.util.Stack
Objects can be created as follows.

java.util.Stackst = new java.util.Stack();

This way of using may not look nice when we use the same class a number of times in the
code as readability becomes boredom. This will be a nice approach and justified when the
class is used only once.

2. Importing Only One Class

Java permits to import only one class also from a package as follows.

importjava.awt.event.ActionListener; import java.util.Stack;

After importing, the objects of the classes can be created straightaway.

Stack st = new Stack();

This type of approach is the best and beneficial when only one class is required from the
same package. Importing one class (when other classes are not required) saves a lot of RAM
space usage on the client's machine.

3. Importing All The Classes

One of the advantages of packages is to include all the classes and interfaces of a package
with a single import statement.

importjava.awt.event.*; import java.util.*;

The asterisk (*) mark indicates all the classes and interfaces of the package. After importing,
the objects of the cl asses can be created straightaway.

Stack st = new Stack();

This type of approach is beneficial when many classes and interfaces are required from a
package.

https://way2java.com/java-general/java-import-classes/

5.FORMATTED OUTPUT IN JAVA

 String provides format() method can be used to print formatted output in java.
 System.out.printf() method can be used to print formatted output in java.
Following example returns a formatted string value by using a specific locale, format and
arguments in format() method
Example

importjava.util.*;

publicclassStringFormat{

publicstaticvoid main(String[]args){

double e =Math.E;

System.out.format("%f%n", e);

System.out.format(Locale.GERMANY,"%-10.4f%n%n", e);

Output
The above code sample will produce the following result.

2.718282
2,7183

The following is an another sample example of format strings.


Example

publicclassHelloWorld{

publicstaticvoid main(String[]args){

String name ="Hello World";

String s1 =String.format("name %s", name);

String s2 =String.format("value %f",32.33434);

String s3 =String.format("value %32.12f",32.33434);

System.out.print(s1);

System.out.print("\n");

System.out.print(s2);

System.out.print("\n");
System.out.print(s3);

System.out.print("\n");

Output
The above code sample will produce the following result.

name Hello World


value 32.334340
value 32.334340000000

https://www.tutorialspoint.com/Formatted-Output-in-Java

You might also like