Java book
Java book
JAVA INTRODUCTION
What is Java?
Earlier Java was only used to design and program small computing devices, but it was later
adopted as one of the platform-independent programming languages, and now according to
Sun, 3 billion devices run Java.
• JSP - In Java, JSP (Java Server Pages) is used to create dynamic web pages, such as in
PHP and ASP.
• Applets - Applets are another type of Java programs that are implemented on Internet
browsers and are always run as part of a web document.
• J2EE - Java 2 Enterprise Edition is a platform-independent environment that is a set of
different protocols and APIs and is used by various organizations to transfer data between
each other.
• JavaBeans - This is a set of reusable software components that can be easily used to
create new and advanced applications.
• Mobile - In addition to the above technology, Java is widely used in mobile devices
nowadays, many types of games and applications are being made in Java.
Types of Java Applications
1. Web Application - Java is used to create server-side web applications. Currently, Servlet,
JSP, Struts, JSF, etc. technologies are used.
2. Standalone Application - It is also known as the desktop application or window-based
application. An application that we need to install on every machine or server such as
media player, antivirus, etc. AWT and Swing are used in java for creating standalone
applications.
3. Enterprise Application - An application that is distributed in nature, such as banking
applications, etc. It has the advantage of high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.
4. Mobile Application - Java is used to create application software for mobile devices.
Currently, Java ME is used for building applications for small devices, and also Java is a
programming language for Google Android application development.
Features of Java
• Notepad - On Windows machine, you can use any simple text editor like Notepad
(Recommended for this tutorial), TextPad.
• Netbeans - is a Java IDE that is open source and free which can be downloaded
from http://www.netbeans.org/index.html
• Eclipse - is also a java IDE developed by the Eclipse open source community and can be
downloaded from http://www.eclipse.org/
EVOLUTION OF JAVA
The development of each programming language is based on a fact: there is a need to
solve a problem that was not resolved by previous programming languages. Early programmers
had to choose different programming languages, usually for various tasks, such as a specific
language for a type of field. A certain language was sufficient to solve the problems of its field
but was not able to solve the problems of other fields. For example, Fortran could have been
used to write efficient programs for scientific problems, but it was not good for system code.
Similarly, Basic was easy to understand but was not robust to write big programs; While the
assembly language was powerful for writing efficient programs, but it was not easy to remember
and execution.
Programming languages such as Cobol, Fortran do not have structural principles. They use the
Goto statement to control the flow of the program. Therefore, programs using this type of code
are made up of many jumps and conditional statements that make it difficult to understand.
Therefore, C was invented in 1970, to replace the assembly language and to create a structured,
effective and high-level language. The development of C was the result of the development
process started with BCPL by Dennis Ritchie. BCPL is an old language developed by Martin
Richard. Ken Thompson developed a language called B, which was influenced by BCPL.
Though C was a quite efficient and successful programming language, the complexity of the
program was seeking more efficient language to solve problems. When we write a program in C,
it has a limit, such as a maximum of 25000 lines of code, beyond which it can not handle the
complexity. But writing and managing large programs was a demand at that time. So a new
concept came.
C++ came with object-oriented programming features. C++ is the extension of C language which
has been used extensively. It is a powerful modern language that includes the power and
simplicity of C and the characteristics of OOP. C++ provides more functional software benefits
than C.
C ++ with OOP became quite famous but then a new problem arose, to control the software on
different machines, a separate compiler is required for that CPU. But building a C++ compiler
was quite expensive. Therefore, an efficient and easy solution was needed, and this requirement
became the reason for the creation of Java, which is a portable and platform-independent
language.
HISTORY OF JAVA TECHNOLOGY
The history of the Java programming language is usually associated with origin predates
of the web. James Gosling, Patrick Naughton, Chris Warth, Mike Sheridan, and Ed Frank
initiated the Java language project in June 1991. The idea was to develop a platform-independent
language and create embedded software for consumer electronic devices. It took 18 months to
develop and had an initial name as Oak which was renamed to Java in 1995 due to copyright
issues.
Java was originally developed by James Gosling at Sun Microsystems(which has since merged
into Oracle Corporation) and released in 1995. JDK 1.0 released in(January 23, 1996). Java SE
10 is a current stable release of Java, and many other previous Java versions are also available.
Version Released on
JDK1.0 23 Jan 1996
JDK1.1 19 Feb 1997
J2SE 1.2 8 Dec 1998
J2SE 1.3 8 May 2000
J2SE 1.4 6 Feb 2002
J2SE 5.0 30 Sept 2004
Java SE 6 11 Dec 2006
Java SE 7.0 28 July 2011
Java SE 8.0 18 March 2014
Java SE 9.0 Sept 2017
Java SE 10 (18.3) 2018
JAVA PROGRAM STRUCTURE
It is necessary to know the exact structure of the Java program, and this lesson contains
a detailed description of it. This lesson is essential for you before proceeding to learn more
advanced lessons of Java programming. Here, in this chapter, you will study the structure of the
Java program. Such as how to create a simple Java program and what its different sections mean.
Java program structure means - the way to write a java program or general format.
• Documentation Section
• Package Statement
• Import Statements
• Interface Statement
• Class Definition
• Main Method Class
o Main Method Definition
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are optional,
but we suggest you use them because they are useful to understand the
operation of the program, so you must write comments within the program.
Package You can create a package with any name. A package is a group of classes that
statement are defined by a name. That is, if you want to declare many classes within one
element, then you can declare it within a package. It is an optional part of the
program, i.e., if you do not want to declare any package, then there will be no
problem with it, and you will not get any errors. Here, the package is a keyword
that tells the compiler that package has been created.
It is declared as:package package_name;
Import This line indicates that if you want to use a class of another package, then you
statements can do this by importing it directly into your program.
Example:import calc.add;
Interface Interfaces are like a class that includes a group of method declarations. It's an
statement optional section and can be used when programmers want to implement
multiple inheritances within a program.
Class Definition A Java program may contain several class definitions. Classes are the main and
essential elements of any Java program.
Main Method Every Java stand-alone program requires the main method as the starting point
Class of the program. This is an essential part of a Java program. There may be many
classes in a Java program, and only one class defines the main method.
Methods contain data type declaration and executable statements.
Here is an example of the Hello Java program to understand the class structure and features.
There are a few lines in the program, and the primary task of the program is to print Hello
Java text on the screen.
Program Example:
Program Output:
Hello Java
Here are the most important points to note about the Java programs:
If your Java program is run through the console, you can pass the input
parameter, and main() method takes it as input.
System.out.println(); This statement is used to print text on the screen as output, where the
system is a predefined class, and out is an object of the PrintWriter class
defined in the system.
The method println prints the text on the screen with a new line. You can
also use print() method instead of println() method.
The Java Virtual Machine is called JVM, is an abstract computing machine or virtual
machine interface that drives the java code.
When we talk about the Java applications, then it works only on those machines which have
JVM.
What is JVM?
• Reading Bytecode.
• Verifying bytecode.
• Linking the code with the library.
Diagram of JVM
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have
in OS because JVM is platform dependent.
Platform Independent
Java is called platform independent because of Java Virtual Machine. As different computers
with the different operating system have their JVM, when we submit a .class file to any operating
system, JVM interprets the bytecode into machine level language.
• JVM is the main component of Java architecture, and it is the part of the JRE (Java
Runtime Environment).
• A program of JVM is written in C Programming Language, and JVM is Operating
System dependent.
• JVM is responsible for allocating the necessary memory needed by the Java program.
• JVM is responsible for deallocating memory space.
JAVA SE DEVELOPMENT (KIT)
• Basic Tools
• Remote Method Invocation (RMI) Tools
• Internationalization Tools
• Security Tools
• Java IDL Tools
javac
javac is the compiler for the Java programming language; it's used to compile .java file. It
creates a class file which can be run by using java command.
Example:
c:javac TestFile.java
java
When a class file has been created, the java command can be used to run the Java program.
Example:
c:java TestFile.class
Both run using the command prompt. .java is the extension for java source files which are simple
text files. After coding and saving it, the javac compiler is invoked for creating .class files. As
the .class files get created, the Java command can be used to run the java program.
javadoc
JavaDoc is an API documentation generator for the Java language, which generates
documentation in HTML format from Java source code.
applet viewer
applet viewer run and debug applets without a web browser, its standalone command-line
program to run Java applets.
jar
The jar is (manage Java archive) a package file format that contains class, text, images and sound
files for a Java application or applet gathered into a single compressed file.
JAVA RUNTIME ENVIRONMENT
You need JRE to execute your program, which includes two things:
• JVM
• Java Library
o Static - Functions that are required at compile time.
o Dynamic - Functions that are required at runtime and not at compile time.
In detail, the JRE consists of various components; these are listed below:
JAVA INSTALLATION
JDK (Java SE Development Kit) Includes a complete JRE (Java Runtime Environment) plus
tools for developing, debugging, and monitoring Java applications. After downloading the SDK,
follow the instructions of the installation package.
NetBeans IDE (Integrated development environment) also comes with JDK, and it's also freely
available on Oracle's website.
After the JDK installation, some folders will be created on your hard drive. These are - bin,
demo, include, jre, lib, src.
At the command prompt enter command javac. If you see a screen like below, it means Java is
Installed.
javac command is used to compile a Java program; it creates a class file which can be run by
using java command.
Once you installed Java on your machine, it is required to Set the PATH environment variable to
conveniently run the executable (javac.exe, java.exe, javadoc.exe, and so on) from any directory
without having to type the full path of the command, such as:
C:\javac TestClass.java
Otherwise, you need to specify the full path every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac TestClass.java
Setting the path in Linux OS is the same as setting the path in the Windows OS. But here we use
the export tool rather than set. Let's see how to set path in Linux OS:
Example:
export PATH=$PATH:/home/jdk1.7.0_21/bin/
Here, we have installed the JDK in the home directory under Root (/home).
DIFFERENCE BETWEEN PATH AND CLASSPATH
Path and Classpath look similar but is a big difference between them.
Once you installed Java on your machine, it is required to Set the PATH environment variable to
conveniently run the executable (javac.exe, java.exe, javadoc.exe, and so on) from any directory
without having to type the full path of the command, such as:
C:\javac TestClass.java
Otherwise, you need to specify the full path every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac TestClass.java
What is Classpath?
Classpath is system environment variable used by the Java compiler and JVM.
Java compiler and JVM is used Classpath to determine the location of required class files.
C:\Program Files\Java\jdk1.6.0\bin
See Java installation to know more about How to set the path in Windows and Linux.
Difference between path and classpath
Path classpath
path variable is used to set the path for all Java software tools like classpath variable is used to set the
javac.exe, java.exe, javadoc.exe, and so on. path for java classes.
HOW TO COMPILE A JAVA FILE USING JAVAC
javac command is used to compile a .java file. You can directly run javac in
command prompt if the environment variable is set correctly.
Example:
Output:
javac compiler creates a class file. This file holds the bytecode of the program which contains the
instructions to be executed by the Java interpreter.
3. JAVA FUNDAMENTALS
JAVA TOKENS
Java Tokens are the smallest individual building block or smallest unit of a Java
program; the Java compiler uses it for constructing expressions and statements. Java program is a
collection of different types of tokens, comments, and white spaces.
When we write a program, we need different important things. We require language tokens,
white spaces, and formats.
• Reserved Keywords
• Identifiers
• Literals
• Operators
• Separators
White space is also considered as a token.
JAVA KEYWORDS
Keywords are words that have already been defined for Java compiler. They have
special meaning for the compiler. Java Keywords must be in your information because you can
not use them as a variable, class or a method name.
You can't use keyword as identifier in your Java programs, its reserved words in Java library and
used to perform an internal operation.
true, false and null are not reserved words but cannot be used as identifiers, because it is literals
of built-in types.
JAVA OPERATORS
Java operators are symbols that are used to perform mathematical or logical
manipulations. Java is rich with built-in operators.
Operators are tokens that perform some calculations when they are applied to variables.
• Arithmetic Operators
• Unary Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
o Compound Assignment Operators
• Conditional Operator
• Instance of Operator
• Member Selection or Dot Operator
JAVA ARITHMETIC OPERATORS
The way we calculate mathematical calculations, in the same way, Java
provides arithmetic operators for mathematical operations. It provides operators for all necessary
mathematical calculations.
Arithmetic operators are applied on integer and floating-point and not on boolean types. But you
can use them on the characters' because, in Java, Char is sub-set of the integer.
Program Example:
//Addition Operation
int sum = number1 + number2;
System.out.println("Sum is: " + sum);
//Subtraction Operation
int dif = number1 - number2;
System.out.println("Difference is : " + dif);
//Multiplication Operation
int mul = number1 * number2;
System.out.println("Multiplied value is : " + mul);
//Division Operation
int div = number1 / number2;
System.out.println("Quotient is : " + div);
//Modulus Operation
int rem = number1 % number2;
System.out.println("Remainder is : " + rem);
}
}
Program Output:
Sum is: 16
Difference is : 8
Multiplied value is : 48
Quotient is : 3
Remainder is : 0
JAVA UNARY ARITHMETIC OPERATORS
In Java, unary arithmetic operators are used to increasing or decreasing the value of an
operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator
decreases a value.
Syntax:
val++;
val--;
These two operators have two forms: Postfix and Prefix. Both do increment or decrement in
appropriate variables. These two operators can be placed before or after of variables. When it is
placed before the variable, it is called prefix. And when it is placed after, it is called postfix.
Following example table, demonstrates the work of Increment and decrement operators with
postfix and prefix:
Example Description
val = a++; Store the value of "a" in "val" then increments.
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".
Example:
int x = 6;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);
int y = 6;
System.out.println("y=: " + ++y);
int p = 6;
System.out.println("p=: " + --p);
}
}
Output:
r=: 6
r=: 7
x=: 6
x=: 5
y=: 7
p=: 5
JAVA RELATIONAL OPERATORS
The Java Relational operators compare between operands and determine the relationship
between them.
Operator Meaning
== Is equal to
!= Is not equal to
These operators are mainly used when applying control statements in the program.
The output of the relational operator is (true/false) boolean value, and in Java, true or false is a
non-numeric value that is not related to zero or one.
Program Example:
//is equal to
System.out.println("num1 == num2 = " + (num1 == num2) );
//Greater than
System.out.println("num1 > num2 = " + (num1 > num2) );
//Less than
System.out.println("num1 < num2 = " + (num1 < num2) );
//Greater than or equal to
System.out.println("num1 >= num2 = " + (num1 >= num2) );
}
}
Program Output:
The Java Logical Operators work on the Boolean operand. It's also called Boolean
logical operators. It operates on two Boolean values, which return Boolean values as a result.
Program Example:
//Logical AND
System.out.println("bool1 && bool2 = " + (bool1 && bool2));
//Logical OR
System.out.println("bool1 || bool2 = " + (bool1 | bool2) );
//Logical Not
System.out.println("!(bool1 && bool2) = " + !(bool1 && bool2));
}
}
Program Output:
The Java Bitwise Operators allow access and modification of a particular bit inside a
section of the data. It can be applied to integer types and bytes, and cannot be applied to float and
double.
Program Example:
//Bitwise AND
System.out.println("num1 & num2 = " + (num1 & num2));
//Bitwise OR
System.out.println("num1 | num2 = " + (num1 | num2) );
//Bitwise XOR
System.out.println("num1 ^ num2 = " + (num1 ^ num2) );
}
}
Program Output:
The Java Assignment Operators are used when you want to assign a value to the
expression. The assignment operator denoted by the single equal sign =.
In a Java assignment statement, any expression can be on the right side and the left side must be
a variable name. For example, this does not mean that "a" is equal to "b", instead, it means
assigning the value of 'b' to 'a'. It is as follows:
Syntax:
variable = expression;
Example:
int a = 6;
float b = 6.8F;
Java also has the facility of chain assignment operators, where we can specify a single value for
multiple variables.
Example:
Output:
a = 100
b = 100
c = 100
JAVA COMPOUND ASSIGNMENT OPERATORS
This operator can be used to connect Arithmetic operator with an Assignment operator.
a = a+6;
In Java, you can also write the above statement like this:
a += 6;
Operator Meaning
+= Increments then assigns
-= Decrements then assigns
*= Multiplies then assigns
/= Divides then assigns
%= Modulus then assigns
<<= Binary Left Shift and assigns
>>= Binary Right Shift and assigns
>>>= Shift right zero fill and assigns
&= Binary AND assigns
^= Binary exclusive OR and assigns
|= Binary inclusive OR and assigns
While writing a program, Shorthand Operators saves some time by changing the large forms into
shorts; Also, these operators are implemented efficiently by Java runtime system compared to
their equivalent large forms.
\Programs to Show How Assignment Operators Works
Example:
//Simple assigns
byte bt = 24;
System.out.println("bt: " + bt);
Output:
bt: 24
bt: 34
bt: 32
bt: 64
bt: 32
bt: 4
bt: 32
bt: 2
bt: 1
bt: 0
bt: 4
bt: 4
JAVA CONDITIONAL OPERATORS
The Java Conditional Operator selects one of two expressions for evaluation, which is
based on the value of the first operands. It is also called ternary operator because it
takes three arguments.
Syntax:
expression1 ? expression2:expression3;
The above syntax means that if the value given in Expression1 is true, then Expression2 will be
evaluated; otherwise, expression3 will be evaluated.
Example:
Example:
Output:
Ans: No
In the above example, the condition given in expression1 is false because the value of a is not
equal to the value of b.
JAVA INSTANCE OF OPERATOR
The Java instance of Operator is used to determining whether this object belongs to
this particular (class or subclass or interface) or not.
This operator gives the boolean values such as true or false. If it relates to a specific class, then it
returns true as output. Otherwise, it returns false as output.
Syntax:
Example:
class Company {}
Output:
Success.
JAVA DATA TYPES
Data types are the means for the tasks related to identifying and assessing the type of
data. Java is rich in data types which allows the programmer to select the appropriate type
needed to build variables of an application.
• Every variable in Java has a data type which tells the compiler what type of variable it as
and what type of data it is going to store.
• Data type specifies the size and type of values.
• Information is stored in computer memory with different data types.
• Whenever a variable is declared, it becomes necessary to define a data type that what will
be the type of data that variable can hold.
Integer Types
Integer is the whole number without any fractional point. It can hold whole numbers such as 196,
-52, 4036, etc. Java supports four different types of integers, these are:
Type Contains Default Size Range
byte Signed integer 0 8 bit or -27 to 27-1 or
1 byte -128 to 127
short Signed integer 0 16 bit or -215 to 215-1 or
2 bytes -32,768 to 32767
int Signed integer 0 32 bit or -231 to 231-1 or
4 bytes -2147,483,648 to 2147,483,647
Rational Numbers
It is used to hold whole numbers containing fractional part such as 36.74, or -23.95 (which are
known as floating point constants). There are two types of floating point storage in java. These
are:
Characters
It is used to store character constants in memory. Java provides a character data type called char
whose type consumes a size of two bytes but can hold only a single character.
Conditional
Boolean type is used to test a particular condition during program execution. Boolean variables
can take either true or false and is denoted by the keyword boolean and usually consumes one
byte of storage.
Type Contains Default Size Range
Boolean true or false false 1 bit true or false
Example:
class DataTypes{
public static void main(String args[]){
byte byteVar = 5;
short shortVar = 20;
int intVar = 30;
long longVar = 60;
float floatVar = 20;
double doubleVar = 20.123;
boolean booleanVar = true;
char charVar ='W';
Program Output:
Variables are the identifier of the memory location, which used to save data
temporarily for later use in the program. During execution of a program, values can be stored in
a variable, and the stored value can be changed. In Java programming, it is necessary to declare
the variable before being used.
Declaring a variable means what kind of data it will store. Variables display named storage
locations, whose values can be changed during the execution of the program. It is the basic unit
of storage in a Java program.
Syntax:
type variable_name;
type variable_name, variable_name, variable_name;
Here's the meaning of type is a data type. It specifies what type of data the variable will hold.
Example:
// variable definition
int width, height=5;
char letter='C';
float age, area;
double d;
Initialization of Variables in Java
This means assigning a value to variables. In Java, you can assign a value to variables in two
ways:
1. Static - This means that the memory is determined for variables when the program starts.
2. Dynamic - Dynamic means that in Java, you can declare variables anywhere in the
program, because when the statement is executed the memory is assigned to them.
Example:
// actual initialization
width = 10;
age = 26.5;
The variable name needs to be chosen by the programmer in a meaningful way so that it reflects
what it is representing a program.
• A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and
two special characters such as underscore and dollar Sign.
• The first character must be a letter.
• Blank spaces cannot be used in variable names.
• Java keywords cannot be used as variable names.
• Variable names are case-sensitive.
Variable Scope means - That limit, as far as the variable can be used.
• Local variables
• Instance variables
• Class/Static variables
Local variables
A variable that is declared within the method that is called local variables. It is defined in method
or other statements, such as defined and used within the cache block, and outside the block or
method, the variable cannot be used.
Instance variables
A non-static variable that is declared within the class but not in the method is called instance
variable. Instance variables are related to a specific object; they can access class variables.
Class/Static variables
A variable that is declared with static keyword in a class but not in the method is called static or
class variable.
Example:
class A {
int amount = 100; //instance variable
static int pin = 2315; //static variable
Example:
Non-Access modifier
There are five non-access modifiers available in Java, used to achieve many other functionalities.
Example:
class Phone
{
final int PRICE_MIN = 999;
final int PRICE_MAX = 5600; //final variable
Example:
class Programming {
public static void main(String[] args) {
display();
}
static void display() {
System.out.println("I love to programming in Java.");
}
}
int g = 260;
float cgpa = 9.14;
But there may arise some situations where the programmers have to deal with objects rather than
the fundamental data types used on a regular basis. To achieve such scenarios programmers' have
to use the wrapper class. Each of Java's primary data types has a class devoted to it termed as a
wrapper class. These are termed so because they can wrap up the fundamental data types into an
object, of such classes. These wrapper classes come under the java.lang package that gets usually
imported as a default package for every Java program.
The various wrapper classes which provide additional power to numbers in Java are:
• Integer
• Short
• Byte
• Float
• Long
• Double
All of these wrapper classes come under of the umbrella of abstract class Number.
The automatic conversion done by Java compiler for making a between the primitive types with
their equivalent object wrapper classes is termed as Autoboxing. We can take the basic example
of converting an int -> Integer or a float -> Float. In other words, the conversion from primary
data type to their respective Wrapper class objects is called boxing and is done entirely by the
compiler without programmer's intervention.
The conversion back from Wrapper object to primary data type, i.e., reversing of Autoboxing
mechanism is known as Unboxing.
Here's a simple example of how automatically this Autoboxing and Unboxing takes place:
Example Program:
Here are the lists of instance methods used by all subclasses of Number class:
Methods and Their Uses
• compareTo(): The approach compares the Number item that invoked the method to the
argument. It is possible to examine Byte, Long, Integer, and so on
• equals(): This technique determines whether the Number object that invokes the method
is identical to the object that is handed as an argument
• valueOf(): The valueOf method usually returns a relevant Number Object conserving the
cost of the argument passed. The arguments are of primitive data type or String. This
method provides static approach. The approach can take two arguments; wherein one can
be String while the other is a radix.
• toString(): The method is used for getting a String object representing the value of the
Number Object.
• abs(): The method offers the absolute value of any given argument. The argument can be
any of the listed primitive type - int, float, long, double, short or byte.
• ceil(): The ceil() method provides the smallest integer by transforming, which is greater
than or equal to the specified argument.
• floor(): The floor() method provides the largest integer by transforming, which is less
than or equal to the specified argument.
Example Program:
System.out.println(g.equals(d));
System.out.println(c);
System.out.println(fl);
Integer h = 22;
System.out.println(h.toString());
System.out.println(Integer.toString(22));
Program Output:
0
1
false
5.0
62.0
22
22
5
-200.0
-201.0
JAVA CHARACTERS
Characters are considered among the essential data type in every programming language.
For Java also, basic text-based computations are done using 'char' data type which is the primary
data type for Java.
Example:
But at times you may come across situations in development where you might require
implementing objects in place of fundamental data type (char). For achieving this facility, Java
programmers can make use of wrapper class which has a 'Character' class replacement of char
data type. This class provides a wide variety of functional class and methods that come in handy
for dealing with characters in complex programs, making the manipulation of characters easier
for programmers. Programmers have to implement Character object of the wrapper class using
the Character constructor, something like this:
Or
'new' is a keyword of Java used here for creating a Java object which internally tells the
compiler to allocate memory on a heap.
Or
Example:
}
JAVA ARRAYS
An array is a one of the data structure in Java, that can store a fixed-size sequential
collection of elements of the same data type.
For many large applications, there may arise some situations that need a single name to store
multiple values. To process such significant amount of data, programmers need strong data types
that would facilitate the efficient contiguous bulk amount of storage facility, accessing and
dealing with such data items. So, arrays are used in Java. In this tutorial, you will learn about
what arrays are and what the types are and how they are used within a Java program.
Syntax:
The syntax used for instantiating arrays within a Java program is:
Example:
char[] refVar;
int[] refVar;
short[] refVar;
long[] refVar;
int[][] refVar; //two-dimensional array
Initialize an Array in Java
Example:
Example:
int age[5]={22,25,30,32,35};
Program Output:
5. FLOW CONTROL
Statement Description
Type declaration Statement To declare the type of variables being used in the program.
Arithmetic Statement To complete the arithmetic operation between constants and variables.
Control Statement To control the sequence of execution of different statements of the program.
Control Statement
The statements that control the execution flow of the program are known as control statements.
In a program, we modify and repeat the data several times. We need some tools for these
modifications that will control the flow of the program, and to perform this type of tasks Java
Provides control statements.
The break keyword is used to breaks(stopping) a loop execution, which may be a for loop, while
loop, do while or for each loop.
The continue keyword is used to skip the particular recursion only in a loop execution, which
may be a for loop, while loop, do while or for each loop.
Example:
class BreakAndContinue
{
public static void main(String args[])
{
// Illustrating break statement (execution stops when value of i becomes to 4.)
System.out.println("Break Statement\n....................");
for(int i=1;i<=5;i++)
{
if(i==4) break;
System.out.println(i);
}
// Illustrating continue statement (execution skipped when value of i becomes to 1.)
System.out.println("Continue Statement\n....................");
for(int i=1;i<=5;i++)
{
if(i==1) continue;
System.out.println(i);
}
}
}
Program Output:
Break Statement
....................
1
2
3
Continue Statement
....................
2
3
4
5
5. DECISION CONTROL STRUCTURES
DECISION MAKING
Java decision-making statements allow you to make a decision, based upon the result of a
condition.
All the programs in Java have set of statements, which are executed sequentially in the order in
which they appear. It happens when jumping of statements or repetition of certain calculations is
not necessary. However, there may arise some situations where programmers have to change the
order of execution of statements based on certain conditions which involve kind of decision-
making statements. In this chapter, you will learn about how the control flow statements work.
Java has such decision-making capabilities within its program by the use of following the
decision making statements:
• if Statement
o if statement
o if-else statement
o else-if statement
• Conditional Operator
• switch statement
JAVA IF STATEMENTS
If statements in Java is used to control the program flow based on some condition,
it's used to execute some statement code block if the expression evaluated to true; otherwise, it
will get skipped. This statement is the simplest way to modify the control flow of the program.
Syntax:
if(test_expression)
{
statement 1;
statement 2;
...
}
'Statement n' can be a statement or a set of statements, and if the test expression evaluated
to true, the statement block will get executed, or it will get skipped.
Example:
class Sample{
public static void main(String args[]){
int a=20, b=30;
if(b>a)
System.out.println("b is greater");
}
}
Program Output:
IF-ELSE STATEMENTS
If else statements in Java is also used to control the program flow based on some
condition, only the difference is: it's used to execute some statement code block if the expression
is evaluated to true, otherwise executes else statement code block.
Syntax:
if(test_expression)
{
//execute your code
}
else
{
//execute your code
}
Example:
if (b > a) {
System.out.println("b is greater");
} else {
System.out.println("a is greater");
}
}
}
Program Output:
ELSE-IF STATEMENTS
else if statements in Java is like another if condition, it's used in the program when if
statement having multiple decisions.
Syntax:
if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}
Example:
Program Output:
JAVA SWITCH STATEMENTS
Java switch statement is used when you have multiple possibilities for the if statement.
Syntax:
switch(variable)
{
case 1:
//execute your code
break;
case n:
//execute your code
break;
default:
//execute your code
break;
}
After the end of each block it is necessary to insert a break statement because if the
programmers do not use the break statement, all consecutive blocks of codes will get executed
from each case onwards after matching the case block.
Example:
switch (a) {
case 1:
System.out.println("You chose One");
break;
case 2:
System.out.println("You chose Two");
break;
case 3:
System.out.println("You chose Three");
break;
case 4:
System.out.println("You chose Four");
break;
case 5:
System.out.println("You chose Five");
break;
default:
System.out.println("Invalid Choice. Enter a no between 1 and 5");
break;
}
}
}
Program Output:
When none of the cases is evaluated to true, the default case will be executed, and break
statement is not required for default statement.
7. LOOP CONTROL STRUCTURES
JAVA LOOPS
Sometimes it is necessary for the program to execute the statement several times,
and Java loops execute a block of commands a specified number of times until a condition is
met. In this chapter, you will learn about all the looping statements of Java along with their use.
What is Loop?
A computer is the most suitable machine to perform repetitive tasks and can tirelessly do a task
tens of thousands of times. Every programming language has the feature to instruct to do such
repetitive tasks with the help of certain form of statements. The process of repeatedly executing a
collection of statement is called looping. The statements get executed many numbers of times
based on the condition. But if the condition is given in such logic that the repetition continues
any number of times with no fixed condition to stop looping those statements, then this type of
looping is called infinite looping.
Java supports many looping features which enable programmers to develop concise Java
programs with repetitive processes.
• while loops
• do while loops
• for loops
All are slightly different and provides loops for different situations.
Loop control statements are used to change the normal sequence of execution of the loop.
Java while loops statement allows to repeatedly run the same block of code until a
condition is met.
while loop is the most basic loop in Java. It has one control condition and executes as long the
condition is true. The condition of the loop is tested before the body of the loop is executed;
hence it is called an entry-controlled loop.
Syntax:
While (condition)
{
statement(s);
Incrementation;
}
Example:
Program Output:
DO-WHILE LOOPS
Java do-while loops are very similar to the while loops, but it always executes the
code block at least once and furthermore as long as the condition remains true. This loop is
an exit-controlled loop.
Syntax:
do
{
statement(s);
}while( condition );
Example:
Program Output:
FOR LOOPS
Java for loops is very similar to Java while loops in that it continues to process a block
of code until a statement becomes false, and everything is defined in a single line.
Syntax:
Example:
Program Output:
8. MISCELLANEOUS
There are two ways to declare a string in Java, and the most common way to create a string is to
write:
Example:
Program Output:
Concatenating Strings
Program Output:
Example:
Program Output:
Java Trim String
Java trim() method is used to eliminates white spaces before and after a string.
Example:
Program Output:
Example:
Program Output:
JAVA DATE AND TIME
Java Date class is one of the Java's oldest class, and most of the methods in the class
are deprecated, but we can still use it to represent a date though.
Date and time contained in a java.util.Date instance, and accessible by using predefined
methods.
Example:
or
Example:
import java.util.Date;
Program Output:
1444194469602
Date time timestamp in milliseconds is accessible by using Date object with toString() method.
Example:
import java.util.Date;
public class DisplayDate {
public static void main(String args[]) {
// Instantiate an object
Date date = new Date();
Program Output:
Comparing Dates
Compare between two dates in Java
Date Formatting
SimpleDateFormat() method is used for formatting and parsing dates in a locale-sensitive
manner. It's returning date-time formatting by the user-defined pattern.
Example:
import java.util.Date;
import java.text.*;
}
}
Program Output:
Methods in Java
Java methods are an assortment of statements clustered together for performing an operation.
When you call any pre-defined function such as toString(), a series of logical stepwise set of
codes run in the background which is already stored and made ready in the library. In other
words, methods in Java are containers in which you can put, for different operations on different
data (which are variables) to carry out a specific task in your Java code. Also, you can group
Java operations providing a name which will be the name of the method.
It is to be noted that Java methods must have to be located within a Java class. Java methods are
similar to what you call functions and procedures in languages like JavaScript, C, Pascal, etc.). A
Java method is a single or a collection of Java statement(s) performing some action or tasks on
some data (variables) which may or may not return any end result.
Types of Methods
These classifications are being made based on whether the Java method is defined by the
programmer or available and pre-existing in Java's standard library or additional libraries.
• print() method comes under java.io.PrintSteam which prints the string that is written
within the quotation.
• sqrt() is a method of Math class which returns the square root of that specific number.
Syntax:
Here, public static are modifiers where: public sets the visibility of the method, statics used so
that this method is shared among all instances of the class it belongs to; int specifies the type of
value method will return, i.e. the return type; funie is the name of method used here, g and d is
the formal parameters' list of type integer.
Methods won't be going to perform anything until and unless you call them on a specific part of
your program to do some action. In other words, to use method(s), programmers should call them
by the method name. Two approaches are there to call a method. One, where a method returns a
value and the other where methods do not return anything (i.e., no return value). Here are two
examples shows two different ways of calling methods:
Example:
Result is: 70
Passing Parameters
Parameters can be passed in two ways: by value or by reference. In this section, you will study
about this:
Passing Parameters by Value
In the above example, you have seen the arguments having values are passed the unction. These
arguments must have to be in the same sequence as their respective parameters defined in
method specification. Passing parameters using value(s) means calling a method with the help of
parameter.
Example:
Example:
Value of reference-object in str1 is passed to str2. Now, the reference value of str1 and str2 refers
to the same object.
JAVA INNER CLASSES
Java allows a programmer to write a class within another. Inner classes in Java are
formed from nesting of one or more classes within another class. Like that of methods, variables
of any class also have the possession of another class as its' component or member. The concept
of the writing of classes within another is called nested classes. There are two components in a
nested class; the class that clings to an inner class is the outer class.
Here's how nesting of the class is done and inner classes can e formed:
Syntax:
class Outer_class {
// body of outer class
class Inner_class {
// body of inner class
}
}
Types of Inner Class
Programmers can write inner classes in two different types. These are:
Java programmers have provision to create or define a class inside a method, and its type will
be local. Like that of local variables, the inner class has a scope restricted within the curly braces
of the method.
Example:
}
}
Output:
An inner class having no class name of its own is termed as an anonymous inner class. For
anonymous inner classes, you have to state them, i.e.define and instantiate these classes at the
same time. These type of anonymous classes comes handy where programmers need to override
methods of a class or interface within a program.
Example:
Output:
One prime characteristic that is constant in the world of software is the change and
advancement in software. That change is one of the most critical aspects of software
development. Development of new tools and techniques is common for everyday technology
users. For software engineers, the most important thing is the maintainability, portability,
reusability, integrity, security, and user-friendliness. So to build today's sophisticated software it
is just not enough to put together a sequence of programming statements or procedures.
Programmers need to use sound construction techniques and program structures that are easy to
figure out implement and modify in a wide variety of situations. It is possible and efficient to use
with Object-oriented Programming techniques.
Since the inventions of the computer and programming languages, many approaches have been
tried. These includes:
• Modular Programming
• Top-down Programming
• Structured Programming
• Bottom-up programming
Object-Oriented Paradigm
The primary objective of the object-oriented technique is to eliminate some flaws encountered in
the procedural approach. OOP handles and treats data as a critical element and never allows
these data to move freely around the system. It binds data more closely to the functions and
protects them from unintentional alteration by other functions.
OOP allows programmers to break down a problem into the number of entities called Objects
and then build data and functions around these entities. The combination of data and methods
make up an object.
In the above figure, a circle is an object, and it comprises of data and methods where methods
surround the data.
Basic Terms and Features that are used and provided by OOP
This lesson mainly focused on Java object and class and described the features of
Java object-oriented programming.
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
• Classes
• Objects
• Instance
• Method
• Message Parsing
In real-world an entity that has state and its behavior is known as an object.
For Example:
• A Car is an object. It has states (name, color, model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is silver etc. known as its state. It is used to
write, so writing is its behavior.
In real-world object and software object have conceptually similar characteristics. In terms of
object-oriented programming, software objects also have a state and behavior.
What is a class?
The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.
The member functions determine the behavior of the class, i.e. provide a definition for
supporting various operations on data held in the form of an object.
Syntax:
Example:
Class Members
Data Members and methods must be declared within the class definition.
Example:
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
• Classes
• Objects
• Instance
• Method
• Message Parsing
In this lesson our primary focus on Objects and Classes.
What is Object?
In real-world an entity that has state and its behavior is known as an object.
For Example:
• A Car is an object. It has states (name, color, model) and its behavior (changing gear,
applying brakes).
• A Pen is an object. Its name is Parker; color is silver etc. known as its state. It is used to
write, so writing is its behavior.
In real-world object and software object have conceptually similar characteristics. In terms of
object-oriented programming, software objects also have a state and behavior.
What is a class?
The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.
The member functions determine the behavior of the class, i.e. provide a definition for
supporting various operations on data held in the form of an object.
Defining a Class in Java
Syntax:
Class Members
Data Members and methods must be declared within the class definition.
Example:
The second approach takes the help of method like getData() or init() etc., to initialize each
object individually using statements like:
val1.getdata(12,25);
Here, in this chapter, you will be dealing with constructors of Java, and learn about how they are
used within a Java program and how they are useful Object Oriented Programming concept.
Constructors are special member functions whose task is to initialize the objects of its class. It is
treated as a special member function because its name is the same as the class name. Java
constructors are invoked when their objects are created. It is named such because, it constructs
the value, i.e., provide data for the object, i.e., they are used to initialize objects. Every class has
a constructor when we don't explicitly declare a constructor for any java class the compiler
creates a default constructor for that class which does not have any return type. The constructor
in Java cannot be abstract, static, final or synchronized and these modifiers are not allowed for
the constructor.
Instance variables and methods of a class are known as members of a class. Constructors are not
members. For this reason, constructors cannot be inherited; but can be accessed by a subclass.
Java constructors do not get inherited; only their members (variables and methods) get inherited.
So declaring a constructor as final is useless and has no meaning as constructors cannot be
overridden. Again, Java constructors should not be synchronized as it locks the object when
created and hence, as long as the object is not created any other object can be instantiated.
Types of Java Constructors
Default Constructor
class Demo
{
public Demo()
{
System.out.println("This is a default constructor");
}
}
The syntax of default constructor:
Syntax:
<class_name>(){
Parameterized Constructor
class Demo
{
public Demo(int num, String str)
{
System.out.println("This is a parameterized constructor");
}
}
Program for Default Constructor
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
class clerk{
int roll=101;
String grade="Manager";
void display(){System.out.println(roll+" "+grade);}
public static void main(String args[]){
clerk c1=new clerk();
clerk c2=new clerk();
c1.display();
c2.display();
}
}
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
class paramC{
paramC(int a, int b){
System.out.print("Parameterized Constructor");
System.out.println(" having Two parameters");
}
paramC(int a, int b, int c){
System.out.print("Parameterized Constructor");
System.out.println(" having Three parameters");
}
public static void main(String args[]){
paramC pc1 = new paramC(12, 12);
paramC pc2 = new paramC(1, 2, 13);
}
}
JAVA STATIC AND THIS KEYWORD
There are various reserve words that Java provides to do different types of
operations. Keywords are reserved words whose meanings are already known to Java compiler.
There are two essential keywords in Java that are used for very special purposes.
In this chapter we will learn about the two special types of keywords:
• static
• this
Static is a keyword that acts as a non-access modifier in Java that is used mainly to manage
memory. The variable or Method that are marked static belongs to the Class rather than to any
particular instance. A Static method cannot access an instance variable. If a Class contains any
static blocks, then that block will be executed only when the Class is loaded in JVM.
Programmers can apply the Java keyword static with different programming objects like:
• variables
• methods
• initialization - block
• nested class
• Class
• Constructor
• Local inner classes
• Inner class methods
• Instance variables
• Local Variables
• Interfaces
Static variables or methods can be invoked without having an instance of the class. Only a class
is needed to call up a static method or a static variable. If you declare any variable as static, it is
known static variable. The static variable can refer to a common property of all objects (that is
not unique for each object), e.g. company name of employees, college name of students, etc.
Memory in a static variable is reserved only once in a class area at the time of class loading. One
advantage of using static is that it increases the efficiency of the memory.
Program for Static in Java
Example:
this is another Java keyword which as a reference to the current object within an instance method
or a constructor — the object whose method or constructor is being called. By the use of this
keyword, programmers can refer to any member of the current object within an instance method
or a constructor. This keyword can be used to refer to the current object, and it always acts as a
reference to an object in which method was invoked. There are the various uses of this keyword
in Java. These are:
• For referring current class instance variable, this keyword can be used
• To invoke current class constructor, this() is used
• this can be passed as message argument in a method call
• In a constructor call, this can be passed as argument
• For returning current class instance, this keyword is used
Program for this in Java
Example:
class Emp {
int e_id;
String name;
Syntax:
super.<method-name>();
Usage of superclass
Example:
class employee {
int wt = 8;
}
Instance refers an instance variable of the current class by default, but when you have to refer
parent class instance variable, you have to use super keyword to distinguish between parent class
(here employee) instance variable and current class (here, clerk) instance variable.
• Class
• Methods
• Variables
When a class is declared as final, it cannot be extended further. Here is an example what happens
within a program
Example:
A method declared as final cannot be overridden; this means even when a child class can call the
final method of parent class without any issues, but the overriding will not be possible. Here is a
sample program showing what is not valid within a Java program when a method is declared as
final.
Example:
class stud {
final void show() {
System.out.println("Class - stud : method defined");
}
}
class books extends stud {
void show() {
System.out.println("Class - books : method defined");
}
public static void main(String args[]) {
books B2 = new books();
B2.show();
}
}
Once a variable is assigned with the keyword final, it always contains the same exact value.
Again things may happen like this; if a final variable holds a reference to an object then the state
of the object can be altered if programmers perform certain operations on those objects, but the
variable will always refer to the same object. A final variable that is not initialized at the time of
declaration is known as a blank final variable. If you are declaring a final variable in a
constructor, then you must initialize the blank final variable within the constructor of the class.
Otherwise, the program might show a compilation error.
Here is an example of a program in Java showing the use of the final variable
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
class stud {
final int val;
stud() {
val = 60;
}
void method() {
System.out.println(val);
}
public static void main(String args[]) {
stud S1 = new stud();
S1.method();
}
}
What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is called the blank final variable.
when you want to create a variable that is initialized at the time of creating an object and once
initialized may not be changed, use the final keyword, and it will be beneficial in this case. For
example PAN CARD number of an employee. It can be initialized only in the constructor.
JAVA POLYMORPHISM
The word polymorphism means having multiple forms. The term Polymorphism gets
derived from the Greek word where poly + morphos where poly means many
and morphos means forms.
• Static Polymorphism
• Dynamic Polymorphism.
Method Overloading
• To call an overloaded method in Java, it is must use the type and/or the number of
arguments to determine which version of the overloaded method actually to call.
• The overloaded methods may have varied return types and the return type single-
handedly is insufficient to make out two versions of a method.
• As and when Java compiler encounters a call to an overloaded method, it simply executes
the version of the method whose parameters match the arguments used in the call.
• It permits the user to obtain compile time polymorphism with name method name.
• An overloaded method can throw different kinds of exceptions.
• A method which is overloaded can contain different access modifiers.
Example:
class Mltply {
void mul(int a, int b) {
System.out.println("Sum of two=" + (a * b));
}
• Argument list: The argument list at the time of overriding method need to be same as that
of the method of the parent class. The data types of the arguments along with their
sequence must have to be preserved as it is in the overriding method.
• Access Modifier: The Access Modifier present in the overriding method (method of
subclass) cannot be more restrictive than that of an overridden method of the parent class.
• The private, static and final methods can't be overridden as they are local to the class.
• Any method which is overriding can throw any unchecked exceptions, in spite of whether
the overridden method usually method of parent class might throw an exception or not.
Program for Method Overriding in Java
Example:
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
public static void main(String argu[]) {
child c1 = new child();
c1.work();
}
}
One significant advantage of method overriding is that a class can give its specific execution to
an inherited method without having the modification in the parent class (base class).
JAVA ABSTRACTION
Data Abstraction is technique whose feature provides us the capability of
differentiating essential details that need to be displayed to the user.Stuff that should remain
hidden or unfamiliar to users or those data that acts as non-essentials units can be put away from
displaying to users. For example, A building can be viewed as a cement constructed building
rather than separate components like rods, cement, bricks etc.
Again abstraction of data can also be termed as the procedure of picking up the only the
necessary characteristics, ignoring the unrelated or extraneous details. The characteristics and
actions of an object distinguish it from other objects which are alike and leads to classification or
grouping the objects.
Java provides the concept of abstraction through Abstract classes and interfaces. A class
containing the keyword abstract in its declaration creates the abstract class. It may or may not
contain any abstract methods within it. When a class is classified as abstract, it cannot be
instantiated. For using a class as abstract, it needs to be inherited from another class which has
the abstract method implementation. It is to be noted that if a class has a minimum of one
method as abstract, then the class has to be declared as abstract.
Example:
}
Abstract Methods
When a programmer wants any class having a specific method but also want the actual execution
of that method to be resolute by its child classes, the methods can be declared in the base class in
the form of abstract methods.
This is how abstract methods get declared. You have to write the full functionality of this method
in another non-abstract class, taking the same method name.
Example:
Encapsulation can be defined as the procedure of casing up of codes and their associated data
jointly into one single component, like a medicine capsule having different components packed
as a single unit. In Java, you can construct a completely encapsulated class by making all of its
member data within a class as private (which is an access specifier). Moreover, you can
implement the setter and the getters to set and get data from within a class.
In simple terms, encapsulation is a way of packaging data and methods together into one unit.
Encapsulation gives us the ability to make variables of a class keep hidden from all other classes
of that program or namespace. Hence, this concept provides programmers to achieve data hiding.
To achieve encapsulation in Java:
Example:
Advantages of Encapsulation
What is Inheritance?
Inheritance is the procedure or mechanism of acquiring all the properties and behavior of one
class to another, i.e., acquiring the properties and behavior of a child class from the parent class.
This concept was built to achieve the advantage of creating a new class that gets built upon an
already existing class. It is mainly used for code reusability within a Java program.
Moreover, a hierarchical order of information management can also be done using this concept.
Here two types of classes build relationships: a base class and a derived class. The class inherited
by taking the properties of another class is the subclass, derived class, or child class. Again, the
class whose properties are inherited is the superclass, base class, or parent class. The
keyword extends is used to inherit the properties of the base class to the derived class. The
structure of using this keyword looks something like this:
Syntax:
class base
{
.....
.....
}
class derive extends base
{
.....
.....
}
Types of Inheritance
Let's now discuss the various types of inheritance supported by Java. Here's a block diagram of
three inheritances.
Java supports three types of inheritance. These are:
Single Inheritance
When a single class gets derived from its base class, then this type of inheritance is termed as
single inheritance. The figure drawn above has class A as the base class, and class B gets derived
from that base class.
Example:
class Teacher {
void teach() {
System.out.println("Teaching subjects");
}
}
class Students extends Teacher {
void listen() {
System.out.println("Listening to teacher");
}
}
class CheckForInheritance {
public static void main(String args[]) {
Students s1 = new Students();
s1.teach();
s1.listen();
}
}
Multi-level Inheritance
In this type of inheritance, a derived class gets created from another derived class and can have
any number of levels.
Example:
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class homeTution extends Student {
void explains() {
System.out.println("Does homework");
}
}
class CheckForInheritance {
public static void main(String argu[]) {
homeTution h = new himeTution();
h.explains();
d.teach();
d.listen();
}
}
Hierarchical Inheritance
In this type of inheritance, more than one derived class is created from one base class.
Example:
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class Principal extends Teacher {
void evaluate() {
System.out.println("Evaluating");
}
}
class CheckForInheritance {
public static void main(String argu[]) {
Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error
}
}
Please watch this video tutorial to understand "Java Inheritance" in more depth.
Let us imagine a situation with three classes: A, B, and C. The C class inherits the A and B
classes. In case class A and class B have a method with the same name and type, and as a
programmer, you have to call that method from the child class's (C) object, there-there will be
ambiguity as to which method will be called either of A or B class.
So Java reduces this hectic situation by using interfaces that implement this concept and reduce
this problem, as compile-time errors are more tolerable than runtime faults in the program.
JAVA INTERFACE
In the chapter of Inheritance, earlier you have learned about classes and how other
classes can inherit them. There, you have also learned about various types of inheritance and
pointed out an odd thing that Java does not support multiple Inheritance. That is Java classes
cannot have more than one superclass, i.e., the technique shown below is not permitted by Java.
Example:
But Java designers could not overlook the value and importance of multiple inheritances. A large
number of real-life applications need the concept of multiple inheritances. Java provides an
alternative way of using multiple inheritances know as interfaces to support this concept.
Although Java class cannot be a subclass of more than one superclass, it can implement more
than one interface. Hence this enables programmers to create classes that build upon other
classes without the problem created by multiple inheritances.
Declaring Interfaces
Example:
import java.lang.*;
//multiple import statements can be used here
public interface IntrfaceName
{
//Any number of final, static fields
//Any number of abstract method declarations
}
An interface is similar to class in the following ways
Defining Interface
An interface is defined much like a class. The general form of defining an interface is:
Example:
access interface_name{
return-type method1(parameter list);
return-type method2(parameter list);
type final-varName1=value;
// ........
}
When no access specifier is included, then the default access result along with the interface is
only available to other members of the package in which it is declared. When it is declared
as public, the interface can be used with any other code. It is to be noted that the methods
declared have no bodies. They end with a semicolon after the parameter list. They are essentially
abstract methods, and there can be no default implementation of any method specified within an
interface. Variables can be declared inside the interface declarations.
Implementing Interfaces
Once an Interface has been defined, one or more classes can implement that interface. For
implementing an interface, programmers need to use the clause 'implements' in the class
definition and then create the method defined by the interface.
If a class implements more than one interface, the interfaces are separated with a comma. In
case, a class is used to implement two interfaces that declare the same method; then the same
method will be used by clients of either interface.
Here is a Java Program for Interface
Example:
import java.util.*;
import java.lang.*;
import java.io.*;
interface shapeX {
public String base = "shape1";
public void Draw();
}
interface shapeY extends shapeX {
public String base = "shape2";
public void Draw2();
}
In thread-based multitasking, threads are considered as the smallest unit if dispatchable code. It
signifies that a single program can perform two or more tasks at a time. For example, a word
processing application can let users write a document and save it along with printing another
document, all done simultaneously. Multitasking threads require less overhead than multitasking
processes. Processes are heavyweight asks that need their own separate address space. Hence, the
interprocess communication becomes expensive and limited.
What is Multithreading?
The process of executing multiple tasks (also called threads) simultaneously is called
multithreading. The primary purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to make maximum use of CPU time. A multithreaded program
contains two or more parts that can run concurrently. It enables programmers to write in a way
where multiple activities can proceed simultaneously within a single application.
What is Multitasking?
It is the way of executing multiple tasks at a time executing them concurrently over a specified
period. Multitasking is done in two ways. These are:
1. Process-based multitasking: It is also called multiprocessing where each process has its
address in memory, i.e., each process allocates separate memory area.
2. Thread-based multitasking: This thread-based multitasking is also termed as
multithreading where threads share the same address space.
A thread goes through various stages of its life cycle. Example, first of all, a thread is born,
started its tasks, run a sequence of tasks concurrently, and then dies. Here is the diagram of the
various stages of a life cycle.
1. New Thread: A new thread begins its life cycle in the new state. The process remains in
this condition until the program starts the thread.
2. Runnable: As soon as the new thread starts, the thread status becomes Runnable. At this
stage, a thread is considered to execute its function or working.
3. Not Runnable: A Runnable thread when entered the time of waiting for the state for a
specific interval of time. That time, the thread is not in Runnable condition.
4. Dead / Terminated: The Runnable thread enters the end stage when it completes its tasks.
Thread Properties
Java assigns each thread a priority that concludes that how a thread will be treated concerning
others. Thread priorities are integers that specify the relative priority of one thread with another.
Thread priorities are used for deciding when to switch from one running thread to another. It is
called a context switch.
Example:
multiThread1.start();
multiThread2.start();
multiThread3.start();
}
}
Sometimes it is useful to suspend the execution of a thread. Example, suppose there is a thread
that is used to display the time of day. If the user of that program does not want that clock, then
the thread can be suspended. Once suspended, restarting that thread is also a simple matter,
which is called resuming the thread. Here are the lists of pre-defined functions used in Java for
performing suspending, resuming and stopping threads respectively. They are:
1. suspend()
2. resume()
3. stop()
JAVA PACKAGES
It is repeatedly said that one of the main features of the Object Oriented
Programming is the ability to reuse the code already written by the programmer. One way of
achieving is by extending class and using the interface. It has a limitation. What will you have to
do if you have to use a class from another program without physically copying them into the
program at the time of development? So another way of achieving the concept of reusability in
Java is via the use of Packages. In this chapter, you will learn about how packages are used
within a Java program.
Packages in Java are groups of similar types of classes, interface and sub packages. It is a way of
grouping a variety of classes or interfaces collectively. The grouping is usually done according to
functionality. The Java packages act as containers for Java classes.
There is also a term named sub-packages. Package inside the package is called the sub-package.
It should be created to categorize the package further.
1. The classes contained in the packages of another program can be easily reused.
2. Packages also allow programmers to separate design from coding.
3. In packages, classes can be declared uniquely compared with classes in other packages.
4. Java Packages provide a way to 'hide' classes thus preventing other programs or packages
from accessing classes that are meant for internal use only.
5. Packages provide access protection.
6. Java package removes naming collision.
For most applications, programmers need to use different sets of classes, one for the internal
representation of program's data and other for the external presentation purposes. You may build
your classes for handling your program data and use existing class libraries for designing class
libraries for designing the user interface.
Creating Packages
While creating a package, programmers must choose a name for the package and include a
package statement along with that name at the top of the source program that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the package.
There can be only one statement of the package in each source code, and it applies to all types in
the file.
To compile the Java programs with package programmers have to do used option as shown
below
package pack_name;
public class firstClass
{
. . . . . . . . //body of the class.
........
}
Here, the package name is pack_name, and the class firstClass is considered a part of this
package. This listing would be saved in as a file called firstClass.java and will be stored in the
directory named pack_name. When the file gets compiled, Java will create a .class file and store
it in the same directory.
Example:
package weapons;
interface ammo {
public void sniper();
public void rifle();
}
Now we have to implement the above interface in the same package weapons like this
Example:
Package weapons;
/* File name : arms.java */
public class arms implements Ammo {
public void sniper() {
System.out.println("Magnum Sniper");
}
public void rifle() {
System.out.println("Sub_Machinegun");
}
public int noOfBullets() {
return 0;
}
public static void main(String args[]) {
arms m = new arms();
m.sniper();
m.rifle();
}
}
$ javac -d . ammo.java
$ javac -d . arms.java
Accessing Package
There are three ways to access the package from outside the package:
• import package.*;
• import package.classname;
• fully qualified name.
You can use the import statement when there are many references to a particular package. The
same approach can be used to access the user-defined packages as well. The import statement
can be used to search a list of packages for a particular class. The general form of import
statement for searching a class is:
Here, package1 is the name of the top-level package. package2 is the name of the package that is
inside the 1st package i.e. package1 and so on. Programmers can use any number of packages in
the package hierarchy. In the end, the explicitly class name is specified.
JAVA AGGREGATION
Aggregation can be said as a relation between two classes that is best described as
a has-a and whole/part relationship. It is a more specialized version of the association
relationship. Now, what is association? In Java, when you think of a class having that has a
member of a different type, then there an association can be formed. In a Java class, where there
lies an entity reference, it becomes aggregation. Let us take a situation; Student object contains
much information such as roll, name, email_add, etc. It contains one more object named rank,
which contains its information such as subj_Name, marks, board_name, exam-type, etc. as given
below.
class Student{
int roll;
String name;
Rank ranking;
}
In this case, the Student has an entity reference ranking, so the relationship is Student HAS-A
ranking Aggregation is also used for code reusability. An aggregation is a form of association
where the relation of Association can be considered the containing class 'owning' the contained
class. The lifetime of that relationship cannot be defined. 'Owning' can be determined as a single-
direction Association.
As told earlier, for code reusability. Let us consider a case where we have used two classes,
student class, and another id class along with staff and teacher; to maintain Student id, teachers'
id, and staff id, programmers do not need to use the same code again and again. Just use the
reference of id class while defining each of these classes. This can be written as:
There are certain rules that a programmer should follow to implement overriding. These are:
• In Java, a method can only be written in the child class and not in same class.
• Argument list should be the same as that of the overridden method of that class.
• Instance methods can also be overridden if they are inherited by the child class.
• A constructor cannot be overridden.
• Final - declared methods cannot be overridden.
• Any method that is static cannot be used to override.
• The return type must have to be the same, or a subtype of the return type declared in the
original overridden method in the parent class.
• If a method cannot be inherited, then it cannot be overridden.
• A child class within the same package as the instance's parent class can override any
parent class method that is not declared private or final.
• A child class in a different package can only override the non-final methods declared as
public or protected.
Example:
class college {
public void move() {
System.out.println("College is open");
}
}
class univ extends college {
public void move() {
System.out.println("University is open too");
}
}
public class stud {
public static void main(String args[]) {
college a = new college();
college b = new univ();
a.move();
b.move();
}
}
To understand "Java Method Overriding" in more depth, please watch this video tutorial.
JAVA AUTOXING AND ANNOTATION
With the beginning of JDK 5, Java added two more important features; Autoboxing
and Auto unboxing.
These features are essential and play a significant role in dealing with primitive data types. In
this chapter, you will learn about how to use these features within a Java source code.
The automatic adaptation of primitive data types into its corresponding Wrapper type is known
as boxing, and reverse operation is known as unboxing. Since it is a new feature in Java; so Java
programmers do not need to write the conversion code. One advantage of using this feature is
that programmers do not require to convert between primitives and Wrappers manually and
hence less coding is needed.
Wrapper class in Java provides the mechanism to convert primitive into object and object into
primitive. A wrapper type/class of Java is one of 8 classes provided in the 'java.lang' The
package used for creating objects for the eight primitive types. Wrapper classes are used to
represent primitive values when an Object is required. The lists of all wrapper classes are:
• short
• byte
• integer
• long
• float
• double
• boolean
• character
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into
its equivalent type wrappers whenever an object of the type is needed. There is no need to
construct an object explicitly. Autoboxing is the process by which the value of a boxed object is
automatically extracted (unboxed) from a type wrapper when the program requires its value.
Furthermore, autoboxing and auto-unboxing significantly streamline the code of several
algorithms, removing the tedium of manually boxing and unboxing values.
Whenever we use the object of Wrapper class in an expression, automatic unboxing and boxing
are done by JVM.
Here is a simple code snippet showing the autoboxing feature of Java:
Integer iOb;
iOb = 100; //Autoboxing of int
++iOb;
There are some benefits that this new feature of Java provides us. They are:
One disadvantage of autoboxing and auto-unboxing is that when programmers mix wrappers
with primitives, there becomes a mismatch between 'equal' and '==', which becomes difficult to
recognize errors.
In general, autoboxing and auto-unboxing take place whenever a conversion into an object or
form an object is required. It applies to expressions. Within an expression, a numeric object is
automatically unboxed. The outcome of the object is automatically reboxed, when necessary.
Example:
With JDK 5, another new facility was provided that enables programmers to embed
supplemental information into a source file. This information is called an annotation which does
not change the action of a program. Thus annotation leaves the semantics of any program
unchanged.
Example:
The @ symbol preceding the keyword interface tells the compiler that an annotation type is
being declared. There are also two members str() and val(). All annotation solely consists of
method declaration and these methods act much like fields. It is to be noted that annotation
cannot include extends clause. However, it is automatic that all annotation programs extend
the Annotation interface. Thus Annotation is the superclass of all annotations.
JAVA ANNUMERATION
Before the versions of JDK 5, there lacked one feature that many programmers felt was
needed; this is the Enumeration. It is a list of named constants. Most other programming
languages support it. Though Java offers the similar type of features that provide somewhat same
functionality such as final variable, still programmers are in eager need of the concept of
enumeration. In this chapter, you will learn about what is enumeration and how it is used within
Java programming language to do different tasks.
What is Enumeration?
Enumeration is a list of named constants, and these Java enumerations define a class type. By
making enumerations into classes, the concept of enumeration is greatly expanded in Java. In the
simplest form, Java enumerations appear similar to enumerations in other languages, except that
the classes play a significant role in this concept.
Enumeration is used using the keyword enum. For example: here are the lists of various types of
programming languages declared using an enumeration.
Example:
Here, the identifiers - high-level, machine-level etc. are called enumeration constants.
Each of them is implicitly declared as public, static final members of PLtypes enumeration.
Hence, in the language of Java, these constants are referred to as self-typed, where self-refers to
enclosing enumeration. Once the enumeration is defined, programmers can create a variable of
its type. However, even though enumerations define a class type, programmers do not initiate an
enum using new. Instead, they can declare and use enumeration variable like that of primitive
data types as used before. For example, this declares lang as a variable of enum type PLtypes
like this:
PLtypes lang;
lang = PLtypes.assembly;
Two enumeration constants can be compared for checking equality by the use of the ==
relational operator. For example, this compares the value of lang as the value machine-level:
if (lang == PLtypes.machinelevel)
{
// . . . . . .
}
It is to be noted that an enumeration value can also be used to control a switch statement. It is, of
course, necessary that all of the case statements must use constants from the same enum as that
used by the switch statement. For example, below mentioned switch case statement is a valid
statement in Java:
All enumerations automatically contain two predefined methods: values() and valuesOf(). The
general forms of these statements are:
The values() method returns an array that contains a list of the enumeration constants and the
valueOf() method returns the enumeration constant whose values corresponds to the string
passed in str.
Here is a Program for enumeration
Example:
enum PLtypes {
highlevel, machinelevel, assembly, middlelevel
}
class enum {
public static void main(String args[]) {
PLtypes lang;
System.out.println(" Here are lists of constants");
PLtypes alltypes[] = PLtypes.values();
for (PLtypes a: alltypes)
System.out.println(a);
System.out.println();
lang = PLtypes.valueOf("assembly");
System.out.println("Value is:" + lang);
}
}