Introduction to Java
14.1 Introduction to Java
Java is a programming language created by James Gosling from Sun Microsystems (Sun)
in 1991. The target of Java is to write a program once and then run this program on
multiple operating systems. The first publicly available version of Java (Java 1.0) was
released in 1995.
C (1969) > C++ (1979) > Java (1995)
Sun Microsystems was acquired by the Oracle Corporation in 2010. It is owned by
Oracle, and more than 3 billion devices run Java. In 2006 Sun started to make Java
available under the GNU General Public License (GPL). Oracle continues this project
called OpenJDK Over time new enhanced versions of Java have been released.
Currently Java 1.8 is the latest version, but within a month Java 1.9 will release. As of
March 2019, Javal2 is the latest version of Java. It includes new String features and a
new Switch expression among other changes.
Java is defined by a specification and consists of a programming language, a compiler,
core libraries and a runtime (Java virtual machine) The Java runtime allows software
developers to write program code in other languages than the Java programming language
which still runs on the Java virtual machine. The Java platform is usually associated with
the Java virtual machine and the Java core libraries.
The Java language was designed with the following properties:
. Platform independent: Java programs use the Java virtual machine as abstraction
and do not access the operating system directly. This makes Java programs highly
portable. A Java program (which is standard-compliant and follows certain rules) can
run unmodified on all supported platforms, e.g., Windows or Linux.
. Object-orientated programming language: Except the primitive data types, all
elements in Java are objects.
° Strongly-typed programming language: Java is strongly-typed, e.g., the types
of the used variables must be pre-defined and conversion to other objects is relatively
strict, e.g., must be done in most cases by the programmer.
350In
. terpreted and compiled | Introduction to Java
bytecode format which do ‘Anguage: Java source code is transfe i
instructions will be interpre wr abend on the 7 Thea bat
target platfc
F eted by . Platform. These bytecod
contains a so called Hotspot-Conry Java Virtual machine (VM). ne WM
bytecode instructions into native aa er which translates performance critical
inst
ee a ructions.
utomatic mi "
‘i 12 emory management: Java manages th
allocation for creating new obj ges the memory allocation and de-
the memory. ‘The so-call ‘ Jects. The program does not have direct access to
: 3 called garbage coll i , °
which no active pointer exists, gi ‘ctor automatically deletes objects to
The Java syntax i imi i
eee y is similar to C++ Java is case-sensitive, e.g., variables
called myvalue and myvalue are treated as different variables,
Itis used for:
¢ Mobile applications (specially Android apps)
¢ Desktop applications
° Web applications
© Web servers and application servers
« Games
© Database connection
Hello world Java program
h a class name, and that class must match the
led MyClass.java, which can be done in any
e, which is
egins with
Java file, ca! eh
file should contain a "Hello World" messag
In Java, every application b
filename. Let's create our firs
text editor (like Notepad). The
Written with the following code:
MyClass java
Public class MyClass { s) {
Public static void main(String aSystem.out. printin("Hello World"),
}
}
Output: :
| eae Sem 2 RS
14.2 Java Virtual Machine(JVM)
Ve
The Java virtual machine (JVM) is a software implementation of a computer that
executes programs like a real machine,
The Java virtual machine is written specifically for a specific operating system, e.g, for
Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Javacompiler into bytecode. The Java virtual machine
interprets this bytecode and executes the Java program.
352i Int jc
ava Runtime Environment VS. Java Developme: t Kit eee
int Kit
istribution typical i
Java distri pi 'Y comes in two flavors, th
: ees : » the Java Runtime Environment JRE
a va i scones Kit JDK).The JRE Consists of the JVM and the rove
jiavies. e necessary functionality to start Java programs.
the JDK additionally contains the development tools neces ram
. :
the JDK therefore consists of a Java hte ache tae fe Jon
iss libraries compiler, the Java virtual machine and the Java
dass libraries.
Development Process Java
ka source files are written as plain text documents. The
Programmer typically writes
hava source code in an Jntegi
rated Development Environment (IDE) for programming. An
IDE supports the programmer in the task of writing code, e.g., it provides auto-formating
ofthe source code, highlighting of the important keywords, ete,
Atsome point the programmer (or the IDE) calls the Java compiler ( javac ). The Java
compiler creates the bytecode instructions. These instructions are stored in .class files
ad can be executed by the Java Virtual Machine.
Before going into the detail, first you have to understand what is the mean of platform?
Platform ave of the computer hardware (mainly architecture of the microprocessor)
and Os, = e + Operating System :
‘ayting oo sa eiapsaa can run on any operating system and hardware.
is pl
i ; Wn any operating system and hardware.
‘va is platform independent so jaya can run on any op
: ion i iti independent? i ;
i (an se now th a of Byte Code which is OS independent. When java
ecause of ie
de not the machine native code
‘ompi : it generate the byte co: 3
me compile any code vat ae need an interpreter to execute ona deand
i ge, Compiler). Now this vir ad that byte code (that is machine indepen fe) and
beats et : Pee Peis for different OS and byte code is able to
.. “le it. Different JVM is
Aten Os
erent ©;Introduction to Java
14.3 Comparison between Java and C++
wie
Java
C++
1. | Java is a true and complete
object oriented language.
C++ is an extension of C with object
oriented behavior. C++ is not a
complete object oriented language as
that of Java.
2. | Java does not support global
variables, pointers, templates,
unions, operator overloading,
structures etc.
C++ supports global variables,
structures, unions, templates, operator
overloading, pointers and pointer
arithmetic.
3. | Java support automatic garbage
collection. It does not support
destructors as C++ does.
C++ support destructors, which is
automatically invoked when the object
is destroyed.
4.| Java does not ~— support
Conditional inclusion (#ifdef -#ifndef | -
conditional compilation and | type) is one of the main features of
inclusion. C/C++.
5. | Java does not support default | C++ supports default arguments.
arguments.
6. | There is no goto statement in
Java. The keywords const and
goto are reserved, even though
they are not used.
C++ has goto statement. However, it
is not considered good practice to use
of goto statement.
7. | Java doesn't provide multiple
inheritance, at least not in the
same sense that C++ does.
CH does support multiple
inheritance. The keyword virtual .is
used to resolve ambiguities during
multiple inheritance if there is any.
8. | Exception handling in Java is
different because there are ‘no
destructors. Also, in Java,
try/catch must be defined if the
function declares that it may
throw an exception.
While in C++, you may not include
the try/catch even if the function
throws an exception,
9. | Java is interpreted for the most
part” and hence _ platform
C++ generates object code and the
same code may not run on different
independent._*
latforms,
354
OBJECT C44 24-8,comparison of Java and C44. using Basic p, "Introduction to Java
ic Progra :
5 mming:
java
le CH
This isa simple Java Program
| a this file "Example java",
class Examiple {
// Your Program begins with a call
to main().
public static void main(String
args[]) {
System.out.printIn("This is a
simple Java program.");
}
}
#include
void main()
cout<<” This is a simple Java
Pprogram.";
}
se
2
Here is another short example.
Call this file "Example2.java".
*/
class Example2 {
public static void main(String
args[]) { /
int num; // this declares a variable
called num.
-num = 100; // this assigns num the
value 100 .
System.out printin("This is num:
+num);
num = num * 2;
System.out.print("The value of
num * 2 is");
System.out.printin(aum)s
#include
void main()
int num; // this declares a variable
called num
num = 100; // this assigns num the
value 100
cout<<"This is num: ", num);
num = num * 2;
cout<<"The value of num * 2 is",
num;
3
LL
355Introduction to Java
}
Output:
This is num: 100
The value of num * 2 is 200
3.1 #include
Demonstrate the if.
Call this file "IfSample.java".
*/
class IfSample {
public static void main(String
args[}) {
int x, y; cout<<"x is less than y";
x=10; x=x*2;
y =20; if(x == y)
if(x < y) System.out.printin("x is cout<<"x now equal to y";
less than y"); x=x*2;
x=x*2: if(x > y)
if(x == y) System.out.printin("x cout<<"x now greater than y";
now equal to y"); //this won't display anything
x=x*2; if(x == y)
if(x > y) System.out.printin("x cout<<"you won't see this";
now greater than y"); }
// this won't display anything
if(x == y) System.out.printin("'you
won't see this");
}
}
Output:
x is less than y
x now equal to y
x now greater than-y
alr #include
356of
—
(| Demonstrate the for loop. ~
Call this file "ForTest jaya"
+/ :
class ForTest {
public static void main(String
args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is xi"
x).
}
}
Output:
This is x:
This is x:
This is x:
This is x:
This is x:
This is x:
This is x:
This is x:
This is x:
This is x: 9
OIDAHDAWNHO
void main()
int x;
for(x = 0; x<10; x= xt1)
Cout<<""This is x: %q" x);
}
1 Compute distance light travels
using long variables.
class Light {
Public static void main(String
args[]) '{
int lightspeed;
long days;
long seconds;
long distance; i
/ approximate speed of light in
Miles per second
lightspeed = 186000;
i f
days = 1000; // specify number ©
#include
void main()
{
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in
miles per second
ightspeed = 186000;
ia : 1000; // specify number of
days here
357Introduction to Java
days here
seconds = days * 24 * 60 * 60; //
convert to seconds
distance = lightspeed * seconds; //
compute distance
System.out.print("In " + days);
System.out.print(" days light will
travel about "); .
System.out.printin(distance + "
miles."),
}
}
Output:
In 1000 days light will travel
about 16070400000000 miles.
seconds = days * 24 * 60*60;// |
convert to seconds
distance = lightspeed * seconds; //
compute distance
cout<<"In %ld", days);
cout<<" days light will travel
about "); :
cout<<(“%ld miles.",distance);
}
// Compute the area of a circle.
class Area {
public static void main(String
args[]) {
double pi, r, a; ,
r= 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a=pi*r*r;// compute area
System.out.printin("Area of circle
is" +a);
}
}
Output:
#include
void main()
{ double pi, r, a;
t= 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a=pi*r*r, // compute area
cout<<"Area of circle is %d", a);
}Introduction to Java
14.4 Java Packages and APT
a package in Java is used to roup related cl;
girectOFY- We use packages to avoid name
cod Packages are divided into two catego
asses. Think of it as a folder ina file
conflicts, and to write a better maintainable
les:
«Built-in Packages (packages from the Java API)
« User-defined Packages (create your own packages)
Built-in Packages
The Java APLis a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much
much more. The library is divided into packages and classes. Meaning you'can either
import a single class (along with its methods and attributes), or a whole package that
contain all the classes that belong to the specified package.
Touse a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class; // Import a single class
import package.name.*, // Import the whole package
Import a Class
Ifyou find a class you want to use, for example, the Scanner class, which is used to ge
User input, write the following code:
Example
Import java.util.Scanner;
i i f
Ih the example above, java.util is @ package, while Scanner is a class 0!Oe eg ee
To use the Scanner class, create an object of the class and use ay of the ee
methods found in the Scannerclass documentation. In our example, we will use
the nextLine() method, which is used to read a complete line:
Example
Using the Scanner class to get user input:
import java.util.Scanner,
class MyClass {
public static void main(String[] args) {
Scanner myObj-= new Scanner(System.in);
System.out.printin("Enter username");
String userName = myObj.nextLine();
System.out.println("Username is: "+ userName);
3
3
Import a Package
There are many packages to choose from. In the Previous example, we used
the scanner class from the java.util package. This package also contains date and
time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.utii package:
Example
import java.util;
User-defined Packages
To create your own package, you need to understand that Java use a file system directory
to store them. Just like folders on your computer:
Example
L— root
L— mypack
L— MyPackageClass.java
To create a package, use the package keyword:yyPackageClass java Introduction to Java
poskage mypack;
cless MyPackageClass {
public static woud main(String[] args) {
The 5
system.out.println("This is my package!"),
}
ee the file as MyPackageClass java, and compile it:
CAUsers\Y our Name>javac MyPackageClass java
Then compile the package:
C\Users\Your Name>javac -d . MyPackageClass.java
This forces the compiler to create the "mypack" package.
The -d keyword specifies the destination for where to save the class file. You can use
any directory name, like c:/user (windows), or, if you want to keep the package within
the same directory, you can use the dot sign ".", like in the example above.
Note: The package name should be written in lower case to avoid conflict with class
names,
When we compiled the package in the example above, a new folder was created, called
“mypack", . following:
Torun the MyPackageClass.java file, write the p lowing:
ClUsers\Your Name>java mypack.MyPackageClass
The output will be:
This is my package!
Javautil Package in Java ;
legacy collection classes, event model, date an¢
at I ue : onizan,
‘ peas ie cca framework miscellaneous utility classes (a string tokeniz
On ein, and
time facilities, jnternationalization, i array).
4tandom-number generator, and 4
il package : inkedLi so
Some Important Classes in-Javatil PRET vo, Enumset ee
Curren'
AbstractCollection, Arrays
TimerJava.lang package in Java
Provides classes that are fundamental to the design of the Java programming language.
The most important classes are Object, which is the root of the class hierarchy, and
Class, instances of which represent classes at run time. :
Some Important Classes in Java.lang package are
Boolean, Byte, Character, Double. Float, Package, Thread etc.
Java.io Package in Java
This package provides for system input and output through data streams, serialization
and the file system. Unless otherwise noted, passing a null argument to a constructor or
method in any class or interface in this package will cause a NullPointerException to be
thrown.
Some important classes in Java.io package are:
¢ _ BufferedInputStream, BufferedOutputStream, BufferedReader, FileInputStream,
FileOutputStream etc.
14.5 Applet and Servlet in Java
Definition of Applet
Applet is a small Java program that is embedded in an HTML code for its execution, and
it is executed on the client-side machine. Java ‘s API library contain a package called
“applet”, which contains a class called “Applet”, Any applet you create should be a
subclass of the class Applet, and that subclass must be declared “4
i Public” as its code will
be accessed by the code that lies outside the program. Now, let us understand the
creation of applet with the help of a siniple example.
1. import java.awt.*;
import java.applet.*;
3 public class Hello extends Applet {
4, _ public void paint(Graphics g) {
5, g.drawString("Hello Applet", 20, 20);
6. 3
1. 3
In above code, two import Statements are package “awt” and package “applet” which are
required in the creation of any applet. The paint( ) method in the code is defined in the
cage awt, which is overridden by the applet created. As you can see the class Hello,
packag' 362jos extended the class Applet, which j ; Introduction to Java
. Execute applet in a Java-compatible web browser.
Execute using appletviewer whi , ,
. cae ich is also the fastest method of executing the
the first method of executing an applet in a Java-
‘compatible web browser requires
creating an HTML program that embeds the applet created in Hello.java file. ‘
1. //htm! code
2.
3.