Java Programming Language Tutorial
Name:
University Name:
Date:
Submitted To:
Java
Java, developed by Sun Microsystems, a company best known for its high-end Unix
workstations. It is referred as an object-oriented programming language. The Java language,
modelled after C++, was designed to be lightweight, easy and versatile throughout major
operating systems, at both the source and binary level. Java is sometimes listed in the same
breath as HotJava, like Netscape or Mosaic, a World Wide Web browser from the Sun. What
differentiates HotJava from most other browsers is that it can also download and play applets on
the reader's system, in addition to all its simple Web features. Applets look almost the same as
images on a web page, but applets are dynamic and interactive in comparison to images.
While the first World Wide Web browser to be willing to perform Java applets was HotJava,
Java support in other browsers is increasingly becoming available. Support for Java applets is
offered by Netscape 2.0, and other browser developers have confirmed support for Java in
upcoming products as well. You write it in the Java language to build an applet, compile it using
a Java compiler, and link to the applet in your HTML Web pages. The subsequent HTML and
Java files are placed on a website in just the same way as regular HTML and image files are
made available. Therefore, whenever someone reads your page with an integrated applet using
the HotJava browser, the browser installs and runs the applet on the local device, and afterwards
the reader can display and communicate with your applet. The key thing to understand about
Java is that, apart from making applets, you can do so much more with it. Java has been written
as a full-fledged programming language in which you can perform the same kinds of tasks in
other programming languages, such as C or C++, and solve the same kinds of problems as you
can.
Benefits of Java
The technique of object-oriented programming (OOP) is merely a way to organize programs, and
can be achieved using any language. However, dealing in a true object-oriented language and
programming environment helps you to take maximum benefits of object-oriented methodology
and the ability to build versatile, scalable applications and reuse code. Almost all of the object-
oriented ideas of Java are derived from C++, the language it is built on, but many concepts are
still borrowed from other object-oriented languages. Java provides a set of class libraries to also
include simple data types, framework input and output functionality, and other utility features,
much as most object-oriented programming languages. Java is object oriented.
One of the original design aims of Java, in addition to its portability and object-orientation, was
to be small and quick, and thus easier to code, easier to compile, easier to debug, and, best of all,
easy to understand. Holding the language tiny also makes it more stable, since programmers are
less likely to make errors that are impossible to find. However, Java still has a great deal of
strength and versatility, considering its size and basic architecture.
Though Java looks identical to C and C++, Java has omitted much of the more abstract parts of
those languages, rendering the language simpler despite losing any of its strength. In Java, there
are no pointers, nor are there arithmetic pointers. In Java, strings and arrays are true objects.
Regulation of memory is easy.
JAVA Terminologies
It can be represented as a series of objects that interact by invoking each other's methods when
we view a Java program. Let us now look quickly at what the definition of class, object,
methods, and instance variables is.
Declaring Variables
int n = 1;
char ch = ‘X’;
String s = “GoodMorning”;
Long L = new Long (1000000);
Boolean done = false;
final double pi = 3.14159265358979323846;
Employee joe = new Employee ();
char [] a = new char [3];
Vector v = new Vector ();7
Class
For several objects with identical attributes, a class is a blueprint. All the attributes of a given
group of objects are embodied by classes. You don't describe individual objects when you write a
program in an object-oriented language. You describe object classes.
Classes in Java
public class Programming Language {
String programming language name;
int version;
String compiler;
void C++ () {
}
void Java () {
}
void C# () {
}
Object
Another term for an individual entity is an instance of a class. An example is its concrete
representation, if classes are a conceptual representation of an object. But what's the distinction,
specifically, between an instance and an object? Really, none. Object is by far the more common
term, but the precise expression of a class is both instances and objects. In truth, in the OOP
language, the words example and object are sometimes used interchangeably. Both a tree and a
tree object are the same example.
public class Cub {
public Cub(String name) {
// This constructor has one parameter, name.
[Link]("Passed Name is :" + name );
}
public static void main (String []args) {
// Following statement would create an object myPuppy
Cub myCub = new Cub ("Rexy");
}
}
Output
Passed Name is: Rexy
Constructors
Once it is created, a constructor initializes an entity. It has the same name as its type and is
equivalent to a process in syntactic words. Constructors do not have an explicit return form,
however. Usually, you use a constructor to assign initial values to the class-defined instance
variables, or to execute any other start-up operations needed to build a fully formed entity. All
classes have constructors, whether or not you implement one, since the default constructor is
automatically supplied by Java.
Types Of Constructors
Parameterized Constructors
No argument Constructors
Parameterized Constructors usually accepts one or even more parameters.
// A simple constructor.
class MyClass {
int n;
// Following is the constructor
MyClass(int m ) {
n = m;
}
}
No argument Constructors does not accept any parameters
Public class MyClass {
Int num;
MyClass() {
num = 100;
}
}
Data types
The operating system allocates memory on the basis of a variable's data type and determines
what should be stored in the allocated memory. Consequently, you can preserve integers,
decimals, or characters in these variables by specifying different data types to just the
parameters.
There are two type of data types
Primitive data types
Reference data types
Primitive Data Types
They are normally predefined by the language and termed by a keyword. They are eight
primitive data types.
Reference Data Types
Reference variables are generated using the classes' specified constructors. They are used for
object access. These variables are known to be of a certain form and cannot be modified eg cub.
Basic Operators
The set of operators can be categorized as they are numerous in Java.
1. Arithmetic Operators
They are normally utilized in Algebra as well as mathematical expression. Commonly
used arithmetic operation are:
+ Addition, -Subtraction, * Multiplication, / Division, % Modulus, ++ Increment
-- Decrement
2. Relational Operators
== refers to equal to, < refers to less than, > refers to greater than, >= refers to greater than or
equal, <= refers to less than or equal to.
[Link] Operators
& Bitwise AND, | Bitwise OR, ^ Bitwise XOR, ~ Bitwise compliment, << left shift, >> right
shift, >>> zero fill right shift
4. Logical Operators
&& logical and
|| logical or
! logical not
Regular Expressions
Besides pattern matching with regular expressions, Java offers the [Link] package. Java
regular expressions are really comparable to and very simple to understand from the Perl
programming language. A regular expression is a special sequence of characters that, using a
specialized syntax kept in a pattern, lets you complement or locate other strings or string sets.
They can also be used for text and data scanning, editing, or manipulation.
The [Link] module consists mostly of the three classes that follow,
Pattern Type − The compiled representation of a regular expression is a Pattern entity. No public
constructors are given by the Pattern class. You must first invoke one of its public static compile)
(methods to construct a template, which will then return the Pattern item. A normal expression is
recognized by these approaches as the first statement. Matcher Class − The mechanism that
defines the pattern and executes match operations against such an input string is a Matcher
entity. Matcher does not describe any public constructors, much like the Pattern class. By calling
the matcher) (function on the Pattern object, you receive a Matcher object.
PatternSyntaxException − An unregulated exception is a PatternSyntaxException entity that
reveals a syntax error in a normal expression pattern.
Example of java program for regular expression
import [Link];
import [Link];
public class RegexMatches {
public static void main( String args[] ) {
// String to be scanned to find the pattern.
String line = "Is BBQ! OK?";
String pattern = "(.*)(\\d+)(.*)";
// Create a Pattern object
Pattern r = [Link](pattern);
// Now create matcher object.
Matcher m = [Link](line);
if ([Link]( )) {
[Link]("Regular value: " + [Link](0) );
[Link]("Regular value: " + [Link](1) );
[Link]("Regular value: " + [Link](2) );
}else {
[Link]("NO MATCH");
}
}
}
The java code above will give the following results;
Output
Regular value: Is BBQ! OK?
Regular value: BBQ
Regular value: 0
Methods
A Java method is a series of statements to execute an action that are grouped together. For eg,
when you call the [Link]) (function, the system immediately executes several
statements to show a message on the [Link] used methods calling are:
int − return type
int a, int b − list of parameters
public static − modifier
a, b − formal parameters
methodName − name of the method
Example of the use of methods
public class Java Tutorials {
// Instance variable num
int num = 10;
Java Tutorials () {
[Link]("This is an object oriented programming");
}
Java Tutorials (int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable
num
[Link] = num;
}
public void greet() {
[Link]("Hi Welcome to Java Programming Class”)
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
[Link]("value of local variable num is : "+num);
// Printing the instance variable
[Link]("value of instance variable num is :
"+[Link]);
// Invoking the greet method of a class
[Link]();
}
public static void main(String[] args) {
// Instantiating the class
Java Tutorials obj1 = new Java Tutorials ();
// Invoking the print method
[Link]();
// Passing a new value to the num variable through
parametrized constructor
Java Tutorials obj2 = new Java Tutorials (50);
// Invoking the print method again
[Link]();
}
Output
This is an object oriented programming program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Java Programming Class
This is an example program on keyword this
value of local variable num is : 40
value of instance variable num is : 50
Hi Welcome to Java Programming Class
Arrays
Java includes a data structure, an array that stores a sequential set of elements of the same kind in
a fixed-size shape. An array is used to store a collection of data, but thinking of an array as a
collection of variables of the same kind is much more beneficial. Array is an object and is fixed.
Example of an Array
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.5, 2.5, 3.9, 5.5};
// Print all the array elements
for (int i = 0; i < [Link]; i++) {
[Link](myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];
}
[Link]("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max) max = myList[i];
}
[Link]("Max is " + max);
}
}
This will produce the following result −
Output
1.5
2.5
3.9
5.5
Total is 13.4
Max is 5.5
File and I/O
Nearly any class you would ever use to perform input and output (I / O) in Java is in the [Link]
package. These sources both show an input source and a destination for the output. Many data
such as primitives, objects, localized characters etc. are provided by the stream in the [Link]
package. A sequence of data is what is defined as a stream. They are two types of stream: Byte
stream and character stream.
Byte stream
Java byte streams are used to provide 8-bit bytes of input and output. Although there are several
classes relating to byte streams, FileInputStream and FileOutputStream are the most commonly
used classes.
Example of Byte stream
import [Link].*;
public class GrandFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link](); }
if (out != null) {
[Link]();}}}}
Output
$java [Link]
$java GrandFile
Character Stream
Java Byte streams are used to execute 8-bit byte input and output, while Java Character streams
are being used to execute 16-bit unicode input and output. While there are several classes
connected to character streams, FileReader and FileWriter are the most commonly used classes.
Even though FileReader uses FileInputStream internally and FileWriter uses FileOutputStream,
the key distinction here seems to be that FileReader reads two bytes at a time and FileWriter
writes two bytes at even a time.
import [Link].*;
public class GrandFile {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}}
Output
$java [Link]
$java GrandFile
Exceptions
Exception refers to an issue occurring during the execution of a program is an anomaly (or
extraordinary event). The usual flow of the program is interrupted when an exception happens
and the program terminates abnormally, which is not advised, so all exceptions must be treated.
When the user the wrong data format as programmed then exception is bound to happen.
Network connection when one is in the middle of the program can attribute to the occurrence of
exception. Physical error, programmer error and user error are the actors to the occurrence of
exceptions.
Examples of Exception
Live Demo
import [Link];
import [Link];
public class FilenotFound_Ecxeption {
public static void main(String args[]) {
File file = new File("C://[Link]");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_exception.java
FilenotFound_exception.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
Inheritance
Inheritance can be explained as the method in which one class acquires the other's properties
(methods and fields). The data is made manageable in a hierarchical order by the use of
inheritance. A class that inherits another's properties is known as a subset (derived class, child
class) and a superclass (base class, parent class) is regarded as just a class whose characteristics
are inherited.
Example of a java code in Inheritance
class Super_class {
int num = 20;
// display method of superclass
public void display() {
[Link]("This is the display method of
superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
[Link]("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
[Link]();
// Invoking the display() method of superclass
[Link]();
// printing the value of variable num of subclass
[Link]("value of the variable named num in sub
class:"+ [Link]);
// printing the value of variable num of superclass
[Link]("value of the variable named num in super
class:"+ [Link]);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}
Another good example of inheritance in Java
Class Transport {
}
class Air extends Transport {
}
class Road extends Transport {
}
class Water extends Transport {
}
public class Bus extends Road {
public static void main(String args[]) {
Transport a = new Transport ();
Road m = new Road();
Bus d = new Bus ();
[Link](m instanceof Transport);
[Link](d instanceof Transport);
[Link](d instanceof Transport);
}
}
Types of Inheritance
Polymorphism
Polymorphism is an object 's capacity to adopt multiple types. When a reference to the
parent class is used to refer to a child class object, the most frequent use of polymorphism in
OOP occurs. It is considered that every Java object that can pass more than one IS-A test is
polymorphic. In Java, all Java objects are polymorphic, since any object passes the IS-A
examination from its own type as well as object class. It is necessary to realize that a reference
variable is the only conceivable means of accessing an entity. A variable relation may only be of
one kind. Once declared, it is difficult to modify the form of a reference variable. You may
reassign the reference variable to other objects, providing that it is not considered final. The
reference variable type can specify the methods it will execute on the object. An object of its
declared type or any subtype will be referred to by a reference variable.
Example of Polymorphism
public interface Carnivorous {}
public class Mammal {}
public class Lion extends Animal implements Carnivorous {}
Encapsulation
One of the four basic OOP principles is Encapsulation. Inheritance, polymorphism, and
abstraction are the remaining three. Java encapsulation is a process for combining data
(variables) as well as code together as a single entity, operating on the data (methods). In
encapsulation, a class's variables are shielded from all classes and can only be reached through
their current class's methods. It is also, thus, known as data hiding.
Examples of Encapsulation
/* File name : [Link] */
public class EncapDemo {
private String StudentName;
private String AdmID;
private int Class;
public int getClass () {
return Class;
}
public String getStudentName () {
return StudentName;
}
public String getAdmID () {
return AdmID;
}
public void setClass( int newClass) {
age = newClass;
}
public void setStudentName (String newStudentName) {
name = newStudentName;
}
public void setAdmID ( String newAdmID) {
AdmID = newAdmID;
}
}
The public setXXX) (and getXXX) (methods are the points of entry of the EncapDemo
class's instance variables. These strategies are generally referred to as Getters and Setters.
Consequently, through all these Getters and Setters, any class who wants to use the variables can
reach them.
Abstraction
Abstraction is, as per the dictionary, the consistency of coping with emotions instead of
events. For example, as you consider the case of e-mail, nuanced information including what
happens to the recipient are shielded from the protocol used by the e-mail server as soon as you
send an e-mail. Therefore, you only need to insert the information to send an e-mail, note the
recipient's address, and press send. Similarly, abstraction is a way of removing the design
specifics from the user in object-oriented programming, only the interface would be given to the
user. In other words, regardless of everything it does, the user will also have the details about
what the object does. In java interfaces and classes are the only means to achieve abstraction. To
construct an abstract class, only use the abstract parameter in the class declaration prior to the
class keyword.
Example of Abstraction in Java
/* File name : Studentjava */
public abstract class Student {
private String name;
private String Class;
private int AdmNumber;
public Student(String name, String class, int AdmNumber) {
[Link]("Constructing a Student");
[Link] = name;
[Link]= Class;
[Link] = AdmNumber;
}
public double Exam Results() {
[Link]("Inside Student Exam Results");
return 0.0;
}
public void mailCheck() {
[Link]("Mailing a check to " + [Link] + " " +
[Link]);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getClass() {
return Class;
}
public void setClass(String newClass) {
Class = newClass;
}
public int getAdmNumber() {
return number;
}
}