0% found this document useful (0 votes)
3 views

Java book

Java is an object-oriented programming language developed by Sun Microsystems, released in 1995, and is known for its platform independence, allowing programs to run on any operating system with a Java interpreter. It is widely used in various applications, including web, standalone, enterprise, and mobile applications, and features such as security, portability, and robustness. The Java Virtual Machine (JVM) executes Java bytecode, making Java applications versatile across different platforms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java book

Java is an object-oriented programming language developed by Sun Microsystems, released in 1995, and is known for its platform independence, allowing programs to run on any operating system with a Java interpreter. It is widely used in various applications, including web, standalone, enterprise, and mobile applications, and features such as security, portability, and robustness. The Java Virtual Machine (JVM) executes Java bytecode, making Java applications versatile across different platforms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 124

1.

JAVA INTRODUCTION

Java is an object-oriented programming language with its runtime environment. It is a


combination of features of C and C++ with some essential additional concepts. Java is well
suited for both standalone and web application development and is designed to provide solutions
to most of the problems faced by users of the internet era.

What is Java?

• Java is an object-oriented programming language developed by Sun Microsystems, and it


was released in 1995.
• James Gosling initially developed Java in Sun Microsystems (which was later merged
with Oracle Corporation).
• Java is a set of features of C and C++. It has obtained its format from C, and OOP
features from C++.
• Java programs are platform independent which means they can be run on any operating
system with any processor as long as the Java interpreter is available on that system.
• Java code that runs on one platform does not need to be recompiled to run on another
platform; it's called write once, run anywhere(WORA).
• Java Virtual Machine (JVM) executes Java code, but it has been written in platform-
specific languages such as C/C++/ASM, etc. JVM is not written in Java and hence cannot
be platform independent, and Java interpreter is a part of JVM.
Where is Java being Used?

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.

Java is one of the most important programming languages in today's IT industries.

• 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

• Object-Oriented - Java supports the features of object-oriented programming. Its object


model is simple and easy to expand.
• Platform independent - C and C++ are platform dependency languages hence the
application programs written in one Operating system cannot run in any other Operating
system, but in platform independence language like Java application programs written in
one Operating system can able to run on any Operating system.
• Simple - Java has included many features of C / C ++, which makes it easy to understand.
• Secure - Java provides a wide range of protection from viruses and malicious programs.
It ensures that there will be no damage and no security will be broken.
• Portable - Java provides us with the concept of portability. Running the same program
with Java on different platforms is possible.
• Robust - During the development of the program, it helps us to find possible mistakes as
soon as possible.
• Multi-threaded - The multithreading programming feature in Java allows you to write a
program that performs several different tasks simultaneously.
• Distributed - Java is designed for distributed Internet environments as it manages the
TCP/IP protocol.
Popular Java Editors
You will need a text editor to write Java programs. There is even more sophisticated IDE
available in the market. But for now, you can consider one of the following:

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

C is a processor-oriented programming language; it is easy to execute and understand. C became


quite famous at that time because it was reliable, simple and easy to use.

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.

Java Version Release History

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.

Basic Structure of Java Programs

A Java program involves the following sections:

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

A Simple Java Program to Print "Hello Java"

Program Example:

//Name of this file will be "Hello.java"


public class Hello
{
/* Author: www.madtec.in
Date: 2023-02-01
Description:
Writes the words "Hello Java" on the screen */

public static void main(String[] args)


{
System.out.println("Hello Java");
}
}

Program Output:

Hello Java

Here are the most important points to note about the Java programs:

• You have to keep in mind that, Java code is case sensitive.


• To write a Java program, you must have to define class first.
• The name of the class in Java (which holds the main method) is the name of the Java
program, and the same name will be given in the filename. As mentioned above in the
sample program; The name of the class is "Hello" in which the main method is, then this
file will be named "Hello.Java".
Let's Look into Various Parts of the Above Java Program

public class Hello This creates a class called Hello.


All class names must start with a capital letter.
The public word means that it is accessible from any other classes.
/* Comments */ The compiler ignores comment block. Comment can be used anywhere in
the program to add info about the program or code block, which will be
helpful for developers to understand the existing code in the future easily.
Braces Two curly brackets {...} are used to group all the commands, so it is known
that the commands belong to that class or method.
public static void When the main method is declared public, it means that it can also be used
main by code outside of its class, due to which the main method is declared
public.
The word static used when we want to access a method without creating its
object, as we call the main method, before creating any class objects.
The word void indicates that a method does not return a value. main() is
declared as void because it does not return a value.
main is a method; this is a starting point of a Java program.
You will notice that the main method code has been moved to some spaces
left. It is called indentation which used to make a program easier to read and
understand.
String[] args It is an array where each element of it is a string, which has been named as
"args".

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.

All Java statement ends with a semicolon.


2. JAVA ENVIRONMENT
JAVA VIRTUAL MACHINE

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?

• JVM, i.e., Java Virtual Machine.


• JVM is the engine that drives the Java code.
• Mostly in other Programming Languages, compiler produce code for a particular system
but Java compiler produce Bytecode for a Java Virtual Machine.
• When we compile a Java program, then bytecode is generated. Bytecode is the source
code that can be used to run on any platform.
• Bytecode is an intermediary language between Java source and the host system.
• It is the medium which compiles Java code to bytecode which gets interpreted on a
different machine and hence it makes it Platform/Operating system independent.

JVM's work can be explained in the following manner

• 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)

JDK (Java SE Development Kit) Includes a complete JRE (Java Runtime


Environment) plus tools for developing, debugging, and monitoring Java applications. JDK is
required to build and run Java applications and applets.

JDK tools divided into five categories:

• Basic Tools
• Remote Method Invocation (RMI) Tools
• Internationalization Tools
• Security Tools
• Java IDL Tools

Basic JDK Tools

These tools are the foundation of the Java Development Kit.

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

JRE stands for Java Runtime Environment, which provides an environment at


runtime. It is the cause of the implementation of JVM (as discussed earlier). It contains a set of
supporting libraries combined with core classes and various other files that JVM uses at runtime.
JRE is a part of JDK (Java Development Toolkit) but can be downloaded separately.

JDK is a set of software tools for the development of Java applications.

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 Web Start and Java Plug-in.


• User Interface Toolkit includes Abstract Window Toolkit (AWT), Swing, Image Input /
Output, Accessibility, drag and drop, etc.
• Other different base libraries, including Input/Output, extension mechanisms, beans,
JMX, JNI, networking, override mechanisms, etc.
• Lang and util base libraries, including lang and util, management, versioning, collections,
etc.
• Integration libraries include Interface Definition Language (IDL), Java Database
Connectivity (JDBC), Java Naming and Directory Interface (JNDI), and Remote Method
Invocation (RMI).
3. JAVA ENVIRONMENT SETUP

JAVA INSTALLATION

Java SE(Standard Edition) is freely available on Oracle's website, and it can be


installed like any other software.

Java Development Kit (JDK)

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.

• bin - This folder contains a compiler and other development tools.


• demo - An example demo program to understand different features of Java.
• include - In this, files are integrated to integrate Java with other languages.
• jre - This folder contains runtime environment files.
• lib - This folder contains Java library files.
• src - This folder contains source code for Java API classes.

Some essential tools exist in the bin folder:

• javac - This is Java compiler.


• java - This is an interpreter.
• Appletviewer - This is used to view applet.
• javap - It is used to convert bytecode into program description.
• javah - This includes header files.
• javadoc - It is used for the HTML document.
Check Whether Java Is Installed or Not

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.

Setting up the Environment Variables

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

Set path of JDK in Windows

• Suppose you have installed Java in C:\Program Files\Java\jdk1.7.0_21\bin directory


• Right-click on My Computer icon and select Properties.
• Click on the 'Environment variables' button under the 'Advanced' or 'Advanced system
settings' tab.
• Add Path as new variable name and C:\Program Files\Java\jdk1.7.0_21\bin as variable
value.

Setting Path in Linux OS

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.

What is Path in Java?

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.

How to compile a java file using javac command.


To compile a program, execute the Java compiler by specifying the name of the file. For this,
you have to type this command at the command prompt.

Example:

c:\jdk\appdemo> javac Testfile.java

Output:

Testfile.java compile successfully.

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.

There are various tokens used in Java:

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

Java Reserved Keywords List

You can't use keyword as identifier in your Java programs, its reserved words in Java library and
used to perform an internal operation.

Abstract Assert Boolean break


Byte Case Catch char
Class Const Continue Default
Do Double Else Enum
Extends Final Finally Float
For Goto If Implements
Import Instanceof Int Interface
Long Native New Package
Private Protected Public Return
Short Static Strictfp Super
Switch synchronized This Throw
Throws Transient try Void
Volatile While true False
Null

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.

Types of operators available in Java such as:

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

Basic Arithmetic Operators


There are various arithmetic operators used in Java:

Operator Meaning Work


+ Addition To add two operands.

- Subtraction To subtract two operands.

* Multiplication To multiply two operands.

/ Division To divide two operands.

% Modulus To get the area of the division of two operands.

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 to Show Arithmetic Operators Works

Program Example:

public class arithop {


public static void main(String[] args) {
//Variables Definition and Initialization
int number1 = 12, number2 = 4;

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

Increment and decrement unary operator works as follows:

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--; Store the value of "a" in "val" then decrements.

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

Programs to Show How Assignment Operators Works

Example:

public class unaryop {


public static void main(String[] args) {
int r = 6;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);

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.

There are six types of relational operators in Java, these are:

Operator Meaning
== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or 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 to Show Relational Operators Works

Program Example:

public class relatiop {

public static void main(String[] args) {


//Variables Definition and Initialization
int num1 = 12, num2 = 4;

//is equal to
System.out.println("num1 == num2 = " + (num1 == num2) );

//is not 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) );

//Less than or equal to


System.out.println("num1 <= num2 = " + (num1 <= num2) );

}
}

Program Output:

num1 == num2 = false


num1 != num2 = true
num1 > num2 = true
num1 < num2 = false
num1 >= num2 = true
num1 <= num2 = false
JAVA LOGICAL OPERATORS

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.

Operator Meaning Work


&& Logical If both operands are true then only "logical AND operator" evaluate true.
AND
|| Logical The logical OR operator is only evaluated as true when one of its operands evaluates
OR true. If either or both expressions evaluate to true, then the result is true.
! Logical Logical NOT is a Unary Operator, it operates on single operands. It reverses the value
Not of operands, if the value is true, then it gives false, and if it is false, then it gives true.

Program to Show Logical Operators Works

Program Example:

public class logicalop {


public static void main(String[] args) {
//Variables Definition and Initialization
boolean bool1 = true, bool2 = false;

//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:

bool1 && bool2 = false


bool1 || bool2 = true
!(bool1 && bool2) = true
JAVA BITWISE OPERATORS

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.

Operator Meaning Work


& Binary AND There are two types of AND operators in Java: the logical && and the
Operator binary &. Binary & operator work very much the same as
logical && operators works, except it works with two bits instead of
two expressions. The "Binary AND operator" returns 1 if both
operands are equal to 1.
| Binary OR Like "AND operators ", Java has two different "OR" operators: the
Operator logical || and the binary |. Binary | Operator work similar to
logical || operators works, except it, works with two bits instead of two
expressions. The "Binary OR operator" returns 1 if one of its operands
evaluates as 1. if either or both operands evaluate to 1, the result is 1.
^ Binary XOR It stands for "exclusive OR" and means "one or the other", but not
Operator both. The "Binary XOR operator" returns 1 if and only if exactly one
of its operands is 1. If both operands are 1, or both are 0, then the result
is 0.
~ Binary
Complement
Operator
<< Binary Left
Shift Operator
>> Binary Right
Shift Operator
>>> Shift right zero
fill operator

Program to Show Bitwise Operators Works

Program Example:

public class bitwiseop {


public static void main(String[] args) {
//Variables Definition and Initialization
int num1 = 30, num2 = 6, num3 =0;

//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) );

//Binary Complement Operator


System.out.println("~num1 = " + ~num1 );

//Binary Left Shift Operator


num3 = num1 << 2;
System.out.println("num1 << 1 = " + num3 );

//Binary Right Shift Operator


num3 = num1 >> 2;
System.out.println("num1 >> 1 = " + num3 );

//Shift right zero fill operator


num3 = num1 >>> 2;
System.out.println("num1 >>> 1 = " + num3 );

}
}

Program Output:

num1 & num2 = 6


num1 | num2 = 30
num1 ^ num2 = 24
~num1 = -31
num1 << 1 = 120
num1 >> 1 = 7
num1 >>> 1 = 7
JAVA ASSIGNMENT OPERATORS

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:

public class ChainAssign {


public static void main(String args[]) {
int a, b, c;
a = b = c = 100; // set a, b, and c to 100
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}

Output:

a = 100
b = 100
c = 100
JAVA COMPOUND ASSIGNMENT OPERATORS

Java provides some special Compound Assignment Operators, also known


as Shorthand Assignment Operators. It's called shorthand because it provides a short way to
assign an expression to a variable.

This operator can be used to connect Arithmetic operator with an Assignment operator.

For example, you write a statement:

a = a+6;

In Java, you can also write the above statement like this:

a += 6;

There are various compound assignment operators used in Java:

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:

//Programs to Show How Assignment and Compound Assignment Operators Works


public class assignmntop {
public static void main(String[] args) {

//Simple assigns
byte bt = 24;
System.out.println("bt: " + bt);

//Increments then assigns


bt += 10;
System.out.println("bt: " + bt);

//Decrements then assigns


bt -= 2;
System.out.println("bt: " + bt);

//Multiplies then assigns


bt *= 2;
System.out.println("bt: " + bt);

//Divides then assigns


bt /= 2;
System.out.println("bt: " + bt);

//Modulus then assigns


bt %= 7;
System.out.println("bt: " + bt);

//Binary Left Shift and assigns


bt <<= 3;
System.out.println("bt: " + bt);

//Binary Right Shift and assigns


bt >>= 4;
System.out.println("bt: " + bt);

//Shift right zero fill and assigns


bt >>>= 1;
System.out.println("bt: " + bt);

//Binary AND assigns


bt &= 4;
System.out.println("bt: " + bt);
//Binary exclusive OR and assigns
bt ^= 4;
System.out.println("bt: " + bt);

//Binary inclusive OR and assigns


bt |= 4;
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.

The conditional operator is used to handling simple situations in a line.

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:

val == 0 ? you are right:you are not right;

Program to Show Conditional Operator Works

Example:

public class condiop {


public static void main(String[] args) {
String out;
int a = 6, b = 12;
out = a==b ? "Yes":"No";
System.out.println("Ans: "+out);
}
}

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:

object-reference instanceof type;

Program to Show Down casting with instance of Operator

Example:

class Company {}

public class Employee extends Company {


public void check() {
System.out.println("Success.");
}

public static void view(Company c) {


if (c instanceof Employee) {
Employee b1 = (Employee) c;
b1.check();
}
}

public static void main(String[] args) {


Company c = new Employee();
Employee.view(c);
}
}

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.

Why is the data type important?

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

Data Types in Java

Data Types available in Java are:

1. Primary Data Type


Java supports eight primitive data
types: byte, short, int, long, float, double, char and boolean.
These eight data types are further classified into four groups:
1. Integer,
2. Relational Numbers(Floating point)
3. Characters
4. Boolean(Conditional).

2. Non-Primitive Data Types


Classes, Interface, Arrays, etc.
This chapter is all about basic primitive data types in Java.

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

long Signed integer 0 64 bit or -263 to 263-1 or


8 bytes -9223,372,036,854,755,808 to
9223,372,036,854,755,807

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:

Type Contains Default Size Range


float IEEE 754 floating point 0.0f 32 bit or ±1.4E-45 to
single-precision 4 bytes ±3.40282347E+38F

double IEEE 754 floating point 0.0 64 bit or ±439E-324 to


double-precision 8 bytes ±1.7976931348623157E+308

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.

Type Contains Default Size Range


char Unicode character \u0000 16 bits or 0 to 216-1 or
unsigned 2 bytes \u0000 to \uFFFF

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 of Data Types and Variable Declarations in Java

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';

System.out.println("Value Of byte Variable is " + byteVar);


System.out.println("Value Of short Variable is " + shortVar);
System.out.println("Value Of int Variable is " + intVar);
System.out.println("Value Of long Variable is " + longVar);
System.out.println("Value Of float Variable is " + floatVar);
System.out.println("Value Of double Variable is " + doubleVar);
System.out.println("Value Of boolean Variable is " + booleanVar);
System.out.println("Value Of char Variable is " + charVar);
}
}

Program Output:

Value Of byte Variable is 5


Value Of short Variable is 20
Value Of int Variable is 30
Value Of long Variable is 60
Value Of float Variable is 20.0
Value Of double Variable is 20.123
Value Of boolean Variable is true
Value Of char Variable is W
JAVA VARIABLES

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.

Declaration of Variables in Java

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.

Rules of Declaring variables in Java

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

Scope of Variables in Java

Variable Scope means - That limit, as far as the variable can be used.

In Java there are various types of variable scope:

• 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

public static void main(String[] args) {


int age = 35; //local variable
}
}

Example:

public class Example {


int salary; // Instance Variable

public void show() {


int value = 2; // Local variable
value = value + 10;
System.out.println("The Value is : " + value);
salary = 10000;
System.out.println("The salary is : " + salary);
}

public static void main(String args[]) {


Example eg = new Example();
eg.show();
}
}
JAVA MODIFIER
Access control modifier and non-access modifier are two types of modifiers in Java.
Access control modifier
There are four access modifiers available in Java, used to set access levels for classes, variable
methods and constructor.

• Scope only inside the same package (default)


• Scope is visible to world (public)
• Scope of the package and all subclasses (protected)
• Scope only within the classes only (private)

Non-Access modifier
There are five non-access modifiers available in Java, used to achieve many other functionalities.

• Modifier to finalizing the implementations of classes, methods, and variables (final)

Example:

class Phone
{
final int PRICE_MIN = 999;
final int PRICE_MAX = 5600; //final variable

final void display() //final method


{
System.out.println("Min Price is" + PRICE_MIN);
System.out.println("Max Price is" + PRICE_MAX );
}
}

• Modifier to create class methods and variables (static)

Example:

class Programming {
public static void main(String[] args) {
display();
}
static void display() {
System.out.println("I love to programming in Java.");
}
}

• Modifier for creating abstract classes and methods (abstract)


• Modifiers for use in threads (synchronized and volatile)
JAVA NUMBERS
In most of the cases, programmers use the primary data types such as byte, int, long,
double, etc. to work with numbers. This is because these are most commonly used data types
which come in handy while creating usual programs.

Some of these are:

int g = 260;
float cgpa = 9.14;

which you have already read in data types' chapter.

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.

A hierarchical view of these wrapper classes are:


Autoboxing and Unboxing

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:

public class Example


{
public static void main(String argu[]) {
Integer g = 6; // autoboxing of int to Integer wrapper object
System.out.println(g);
g = g - 2; // unboxing done, where the Integer object value back to int
System.out.println(g);
}
}

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:

public class Multi_Example {

public static void main(String argu[]) {


Integer g = 6;
Integer d = 4;
Double c = Double.valueOf(5);
Float fl = Float.valueOf("62");
System.out.println(g.compareTo(6));
System.out.println(g.compareTo(4));

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));

Integer val = -5;


System.out.println(Math.abs(val));

double val2 = -200.456;


System.out.println(Math.ceil(val2));
System.out.println(Math.floor(val2));
}

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:

char[] chArr ={ 'k', 'a', 'r', 'l', 'o', 's' };

Character Wrapper Class

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:

Character letterFour = new Character('d');

Or

Character num = new Character('2');

'new' is a keyword of Java used here for creating a Java object which internally tells the
compiler to allocate memory on a heap.

More on Character Wrapper Class


Character letterFour = new Character('d');

Or

Character num = new Character('2');


In the above example, Java compiler internally will create Character object for the programmers.
In cases when you will be passing the primary data type (char) value to any user-defined method
which is ready to accept the argument as an object, the compiler will be going to automatically
convert your 'char' value passed to a Character value (which will be an object). This conversion
mechanism is called autoboxing & unboxing when the conversion is done the reverse way.

Example:

Character letter = 'g';


char chh = test('k');
Predefined Methods of Character Class

• isLetter(): It checks whether the particular character value is a letter or not


• isDigit(): It checks whether the specific character value is a digit or not.
• isWhitespace(): It checks whether the particular character value is a white-space or not.
White-space comes with three things:
1. spaces
2. tab and
3. new-line
• isUpperCase(): It checks whether the specific character value is in uppercase or not.
• isLowerCase(): It checks whether the particular character value is lowercase or not.
• toUpperCase(): This method is used to convert to the upper-case letter by returning the
uppercase form of the specified char value.
• toLowerCase(): This method is used to convert the specific letter to lower-case letter by
returning the lowercase form of the specified char value.
• toString(): It used to returns a String object representing the specified character value.

Program showing the example of each of them:

public class CharacterClassExample {

public static void main(String argu[]) {


System.out.println(Character.isLetter('g')); // true
System.out.println(Character.isLetter('6')); // false
System.out.println(Character.isDigit('8')); // true
System.out.println(Character.isWhitespace('\t')); // true
System.out.println(Character.isUpperCase('k')); // false
System.out.println(Character.isLowerCase('G')); // false
System.out.println(Character.toUpperCase('d')); // C
System.out.println(Character.toLowerCase('K')); // c
System.out.println(Character.toString('S')); // C
}

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

Define an Array in Java


The syntax of declaring array variables is:

Syntax:

datatype[] identifier; //preferred way


or
datatype identifier[];

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

By using new operator array can be initialized.

Example:

int[] age = new int[5]; //5 is the size of array.

Arrays can be initialized at declaration time also.

Example:

int age[5]={22,25,30,32,35};

Initializing each element separately in the loop.


Example:

public class Sample {

public static void main(String args[]) {


int[] newArray = new int[5];
// Initializing elements of array seperately
for (int n = 0; n < newArray.length; n++) {
newArray[n] = n;
}
}
}

A Pictorial Representation of Array

Accessing Array Elements in Java


Example:

public class Sample {


public static void main(String args[]) {
int[] newArray = new int[5];

// Initializing elements of array seperately


for (int n = 0; n < newArray.length; n++) {
newArray[n] = n;
}
System.out.println(newArray[2]); // Assigning 2nd element of array value
}
}

Program Output:
5. FLOW CONTROL

JAVA CONTROL STATEMENT


As you know, the statement is the instruction given to the computer that performs
specific types of work. They can make decisions and repetitive tasks.

The statements are of the following three types.

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.

There are four types of control statements:

1. Sequence Control Statement


2. Selection or Decision Control Statement
3. Repetition or Loop Control Statement
4. Case Control Statement
In the next chapter, you will study the control statement in detail.
DIFFERENCE BETWEEN BREAK AND CONTINUOUS STATEMENTS IN
JAVA
The keywords break and continue keywords are part of control structures in Java.
Sometimes break and continue seem to do the same thing but there is a difference between them.

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.

The flowchart of Decision-making technique in Java can be expressed as:

Java has such decision-making capabilities within its program by the use of following the
decision making statements:

Decision Making Statements in Java

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

The basic format of if statement is:

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.

Figure - Flowchart of if Statement:


Example of a Java Program to Demonstrate If statements

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.

The basic format of if else statement is:

Syntax:

if(test_expression)
{
//execute your code
}
else
{
//execute your code
}

Figure - Flowchart of if-else Statement:

Example of a Java Program to Demonstrate If else statements

Example:

public class Sample {

public static void main(String args[]) {


int a = 80, b = 30;

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.

The basic format of else if statement is:

Syntax:

if(test_expression)
{
//execute your code
}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}

Example of a Java Program to Demonstrate else If statements

Example:

public class Sample {


public static void main(String args[]) {
int a = 30, b = 30;
if (b > a) {
System.out.println("b is greater");
}
else if(a > b){
System.out.println("a is greater");
}
else {
System.out.println("Both are equal");
}
}
}

Program Output:
JAVA SWITCH STATEMENTS
Java switch statement is used when you have multiple possibilities for the if statement.

The basic format of the switch statement is:

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 of a Java Program to Demonstrate Switch Statement

Example:

public class Sample {

public static void main(String args[]) {


int a = 5;

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.

Java supports following types of loops:

• while loops
• do while loops
• for loops

All are slightly different and provides loops for different situations.

Figure - Flowchart of Looping:


Java Loop Control Statements

Loop control statements are used to change the normal sequence of execution of the loop.

Statement Syntax Description

break break; Is used to terminate loop or switch statements.


statement

continue continue; Is used to suspend the execution of current loop


statement iteration and transfer control to the loop for the next
iteration.

goto goto labelName;labelName: It transfers current program execution sequence to


statement statement; some other part of the program.
WHILE LOOPS

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.

The basic format of while loop statement is:

Syntax:

While (condition)
{
statement(s);
Incrementation;
}

Figure - Flowchart of while loop:

Example of a Java Program to Demonstrate while loop

Example:

public class Sample {


public static void main(String args[]) {
/* local variable Initialization */
int n = 1, times = 5;
/* while loops execution */
while (n <= times) {
System.out.println("Java while loops:" + n);
n++;
}
}
}

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.

The basic format of do-while loop statement is:

Syntax:

do
{
statement(s);
}while( condition );

Figure - Flowchart of the do-while loop:


Example of a Java Program to Demonstrate "do while" loop

Example:

public class Sample {


public static void main(String args[]) {
/* local variable Initialization */
int n = 1, times = 0;

/* do-while loops execution */


do {
System.out.println("Java do while loops:" + n);
n++;
} while (n <= times);
}

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.

The basic format of for loop statement is:

Syntax:

for ( init; condition; increment )


{
statement(s);
}

Figure - Flowchart of for loop:

Example of a Java Program to Demonstrate for loop

Example:

public class Sample {


public static void main(String args[]) {
/* local variable Initialization */
int n = 1, times = 5;
/* for loops execution */
for (n = 1; n <= times; n = n + 1) {
System.out.println("Java for loops:" + n);
}
}
}

Program Output:
8. MISCELLANEOUS

JAVA STRINGS CLASS

A string is a sequence of character in Java, widely used as an object.

Strings Initialization in Java

There are two ways to declare a string in Java, and the most common way to create a string is to
write:

Example:

String name = "Alex";

Through char array:

public class Sample {


public static void main(String args[]) {
char[] nameArray = {'A', 'l', 'e', 'x'};
String name = new String(nameArray);
System.out.println(name);
}
}

Program Output:

Concatenating Strings

concat() method can be used to attach strings.


Example:

public class Sample {


public static void main(String args[]) {
String str1 = "Hello ", str2 = "World!";
System.out.println(str1.concat(str2));
}
}
+ operator is more commonly used to attach strings.

"Hello," + " world" + "!"

Program Output:

Java String Case


Java toUpperCase() and toLowerCase() method is used to change string case.

Example:

public class Sample {

public static void main(String args[]) {


String str1 = "Hello";
System.out.println(str1.toUpperCase());
System.out.println(str1.toLowerCase());
}
}

Program Output:
Java Trim String
Java trim() method is used to eliminates white spaces before and after a string.

Example:

public class Sample {

public static void main(String args[]) {


String str = " Hello ";
System.out.println(str.trim());
}
}

Program Output:

Java String length


Java length() method is used to get the length of the string.

Example:

public class Sample {

public static void main(String args[]) {


String str = "Cloud";
System.out.println(str.length());
}
}

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.

Instantiate a java.util.Date instance:

Example:

java.util.Date date = new java.util.Date();

or

public class DisplayDate {


public static void main(String args[]) {
// Instantiate an object
Date date = new Date();
}
}
Current timestamp
Date time timestamp in milliseconds is accessible by using Date object with getTime() method.

Example:

import java.util.Date;

public class DisplayDate {


public static void main(String args[]) {
// Instantiate an object
Date date = new Date();

// display current timestamp


System.out.println(date.getTime());
}
}

Program Output:

1444194469602

Current Date & Time

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();

// display time and date


System.out.println(date.toString());
}
}

Program Output:

Wed Oct 07 05:16:16 UTC 2015

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.*;

public class DisplayDate {


public static void main(String args[]) {
Date date = new Date( );
SimpleDateFormat dateFormat = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a
zzz");

System.out.println("Current Date: " + dateFormat.format(date));

}
}

Program Output:

Current Date: Wed 2015.10.07 at 05:48:19 AM UTC


JAVA METHODS
Java is one of the popular general-purpose programming languages which is
concurrent, have classes & objects and also provide codes to set up in modules so that some
codes can be re-used and specifically intended to let your applications "write once, run
anywhere" (WORA) feature.

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

Methods can be of two broad categories. These are:

• Standard Library Methods


• User-defined 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.

Some examples of Standard libraries are:

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

The syntax for Creating methods in Java

Syntax:

modifier returnType NameofMethod(Parameter List) {


// method body
}
Example:

public static int funie(int g, int d) {


// body of the method
}

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.

Calling Methods in Java

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:

• Ex: System.out.println("Hello, Methods, I do not return anything");


• int output = fun(2, 6);

Example:

public class Example {


public static void main(String argu[]) {
int val1 = 62;
int val2 = 8;
int res = fun(val1, val2);
System.out.println("Result is: " + res);
}

public static int fun(int g1, int g2) {


int ans;
ans = g1 + g2;
return ans;
}
}
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:

public void swapping(int s1, int s2) {


int temp = s1;
s1 = s2;
s2 = temp;
}
Alternatively other than pass by value, you can use pass by reference which represents the
aliasing of data and changes done in aliased value gets reflected your original value. In case of
passing by reference, any changes done on a value within different scope gets preserved even
when the scope is exited.

Example:

public class AnotherExample {


public void printOut(StringBuffer str2) {
str2.append("Reference");
System.out.println(str2); // prints passBy reference
}
public static void main(String argu[]) {
AnotherExample ae = new AnotherExample();
StringBuffer str1 = new StringBuffer("passBy ");
ae.printOut(str1);
System.out.println(str1); // prints passBy reference
}
}

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:

• Local - Method Inner class


• Anonymous Inner class

Local method Inner class

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:

public class classA {


void fun() {
int val = 84;
// local-method inner class
class InnerMeth {
public void disp() {
System.out.println("Inner class method: "+val);
}
} // end of inner class
// Accessing the inner class
InnerMeth in = new InnerMeth(); in .disp();
}

public static void main(String argu[]) {


classA out = new classA();
out.fun();
System.out.println("Program done….");

}
}

Output:

Inner class method: 84


Program done….

Anonymous Inner class

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:

abstract class anonInner {


public abstract void fun();
}

public class outerA {


public static void main(String argu[]) {
anonInner in = new anonInner() {
public void fun() {
System.out.println("Anonymous Inner class executed….");
}
}; in .fun();
}
}

Output:

Anonymous Inner class executed….


9. JAVA OBJECT OREINTED

JAVA OBJECT OREINTED PROGRAMMING (OOPs)

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

Java is purely under the category of Object-oriented 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.

i.e. Object = data + method


Figure - Object Representation:

In the above figure, a circle is an object, and it comprises of data and methods where methods
surround the data.

Major Objectives of Object-Oriented Programming

• The emphasis is on the data rather than the procedures.


• Methods that operate on data are tied together in a data structure.
• Programs are divided into small instance called Objects.
• Data remains hidden and cannot be accessed by external functions.
• Objects may communicate with each other through methods.
• The programs follow the bottom-up approach.
• New data and methods can be easily added whenever necessary.

Basic Terms and Features that are used and provided by OOP

• Classes and Objects


• Data Abstraction
• Data encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
Advantages of OOP

• Code recycle and reuse.


• Wrapping up of data into a single unit.
• Easy to partition the work in a project based on objects.
• Message passing technique between objects for communication makes interface
description with external systems much more straightforward.
• Software Complexity can be easily handled and managed.
• Possible to map objects in a problem domain within a program.
• Data hiding is possible.
• Use of inheritance can eliminate redundant codes in a program.
JAVA OBJECT AND CLASS

This lesson mainly focused on Java object and class and described the features of
Java object-oriented programming.

Java has following OOPS features:

• 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?

• A class is a template or blueprint that is used to create objects.


• Class representation of objects and the sets of operations that can be applied to such
objects.
• A class consists of Data members and methods.

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:

public class class_name


{
Data Members;
Methods;
}

Example:

public class Car


{
public:
double color; // Color of a car
double model; // Model of a car
}

• Private, Protected, Public is called visibility labels.


• The members that are declared private can be accessed only from within the class.
• Public members can be accessed from outside the class also.

Class Members

Data and functions are members.

Data Members and methods must be declared within the class definition.

Example:

public class Cube


{
int length; // length is a data member of class Cube
int breadth; // breadth is a data member of class Cube
int length ; // Error redefinition of length
}

• A member cannot be redeclared within a class.


• No member can be added elsewhere other than in the class definition.
JAVA METHOD OVERLOADING
This lesson mainly focused on Java object and class and described the features of Java
object-oriented programming.

Java has following OOPS features:

• 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?

• A class is a template or blueprint that is used to create objects.


• Class representation of objects and the sets of operations that can be applied to such
objects.
• A class consists of Data members and methods.

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:

public class class_name


{
Data Members;
Methods;
}
Example:

public class Car


{
public:
double color; // Color of a car
double model; // Model of a car
}

• Private, Protected, Public is called visibility labels.


• The members that are declared private can be accessed only from within the class.
• Public members can be accessed from outside the class also.

Class Members

Data and functions are members.

Data Members and methods must be declared within the class definition.

Example:

public class Cube


{
int length; // length is a data member of class Cube
int breadth; // breadth is a data member of class Cube
int length ; // Error redefinition of length
}

• A member cannot be redeclared within a class.


• No member can be added elsewhere other than in the class definition.
JAVA CONSTRUCTORS
As you all know that all objects that are created must be given initial values which can
be done in two ways. The first way of doing this is to use the dot operator to access the instance
variable and then to assign values to them individually. It can be a tedious approach to initialize
all the variables of the object in this manner.

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.

What are Constructors?

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.

Characteristics of Java Constructors

• An interface cannot have the constructor.


• Constructors cannot be private.
• A constructor cannot be abstract, static, final, native, strictfp, or synchronized
• A constructor can be overloaded.
• Constructors cannot return a value.
• Constructors do not have a return type; not even void.
• An abstract class can have the constructor.
• Constructors name must be similar to that of the class name inside which it resides.
• Constructors are automatically called when an object is created.

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

There are two types of constructors:

• Default constructor (no-arg constructor)


• Parameterized constructor

Default Constructor

A constructor having no parameter is known as default constructor and no-arg constructor.

The structure of a default constructor is like this:

class Demo
{
public Demo()
{
System.out.println("This is a default constructor");
}
}
The syntax of default constructor:

Syntax:

<class_name>(){

Parameterized Constructor

A constructor having an argument list is known as a parameterized constructor. Parameterized


constructors are used to supply dissimilar values to the distinct objects.

The structure of a parameterized constructor in Java is:

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();
}
}

Program for Parameterized Constructor

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

What is static in Java?

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

Static keyword is unacceptable to the following

• 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:

public class egStatic {


static int x = 60;
static void fun() {
System.out.println("Within Static");
}
public static void main(String[] args) {
egStatic.fun();
System.out.println(egStatic.x);
egStatic S1 = new egStatic();
egStatic S2 = new egStatic();
System.out.println(S1.x);
S1.fun();
}
}

Rules for using Static Variables

• Variables or methods belong to class rather than to any particular instance


• A static method cannot access a non-static variable of a class nor can directly invoke non-
static method
• Static members can be applied without creating or referencing an instance of the class
• A static variable will be shared by all instances of that class which will result in only one
copy

What is this keyword in Java?

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;

Emp(int e_id, String name) {


this.e_id = e_id;
this.name = name;
}
void show() {
System.out.println(e_id + " " + name);
}
public static void main(String args[]) {
Emp e1 = new Emp(1006, "Karlos");
Emp e2 = new Emp(1008, "Ray");
e1.show();
e2.show();
}
}
JAVA SUPER AND FINAL KEYWORD
super and final keywords are two popular and useful keywords in Java. They also
play a significant role in dealing with Java programs and their classes. In this chapter, you will
learn about how to use super and final within a Java program.

What is super in Java?


Super is a keyword of Java which refers to the immediate parent of a class and is used inside the
subclass method definition for calling a method defined in the superclass. A superclass having
methods as private cannot be called. Only the methods which are public and protected can be
called by the keyword super. It is also used by class constructors to invoke constructors of its
parent class.

Syntax:

super.<method-name>();

Usage of superclass

• Super variables refer to the variable of a variable of the parent class.


• Super() invokes the constructor of immediate parent class.
• Super refers to the method of the parent class.

Here is an example of Java program which uses the super keyword

Example:

class employee {
int wt = 8;
}

class clerk extends employee {


int wt = 10; //work time
void display() {
System.out.println(super.wt); //will print work time of clerk
}

public static void main(String args[]) {


clerk c = new clerk();
c.display();
}
}
Output:

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.

What is final in Java?


Final is a keyword in Java that is used to restrict the user and can be used in many respects. Final
can be used with:

• Class
• Methods
• Variables

Class declared as final

When a class is declared as final, it cannot be extended further. Here is an example what happens
within a program

Example:

final class stud {


// Methods cannot be extended to its sub class
}
class books extends stud {
void show() {
System.out.println("Book-Class method");
}
public static void main(String args[]) {
books B1 = new books();
B1.show();
}
}

This will show an error that:

error: cannot inherit from final stud


class books extends stud{
^
This is because classes declared as final cannot be inherited.

Method declared as Final

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();
}
}

Variable declared as final

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.

There are two types of polymorphism

• Static Polymorphism
• Dynamic Polymorphism.

Polymorphism is another special feature of object-oriented programming (OOPs). The approach


which lies beneath this concept is "single interface with multiple implementations." It offers a
single interface for controlling access to a general class of actions.

Polymorphism can be achieved in two of the following ways:

• Method Overloading(Compile time Polymorphism)


• Method Overriding(Run time Polymorphism)

• Static Polymorphism is in other words termed as compile-time binding or early binding.


• Static binding occurs at compile time. Method overloading is a case of static binding and
in this case binding of method call to its definition happens at the time of compilation.

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.

Variations in Overloading a Method

Overloading method's argument lists might differ in:

• Number of parameters passed


• Data type of actual parameters
• Sequence of data type of actual parameters

Program for Method Overloading in Java

Example:

class Mltply {
void mul(int a, int b) {
System.out.println("Sum of two=" + (a * b));
}

void mul(int a, int b, int c) {


System.out.println("Sum of three=" + (a * b * c));
}
}
class Polymorphism {
public static void main(String args[]) {
Mltply m = new Mltply();
m.mul(6, 10);
m.mul(10, 6, 5);
}
}
Method Overriding

Rules of method overriding in Java

• 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();
}
}

Advantage of method overriding

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.

Likewise in Object-oriented programming, abstraction is a process of hiding the implementation


details from the user, only the functionality will be provided to the user. In other words, the user
will have the information on what the object does instead of how it does it.

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 class cycle {


abstract void work();
}

class HeroCycle extends cycle {


void work() {
System.out.println("Selling good");
}

public static void main(String argu[]) {


cycle o = new HeroCycle();
o.work();
System.out.println("Code executed");
}

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

• The keyword abstract is used for declaring abstract method


• The abstract keyword needs to be implemented before the name of method
• Abstract method does not contain any method body
• If there are no curly braces given, there should have to be semicolon put at the end of the
abstract method

Program for Abstract Method

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:

public abstract class professor

public abstract class professor {


private String str;
private float sal;
private int regnNo;
public abstract double salaryCompute();
// abstract metho body here
}
JAVA ENCAPSULATION
The concept of encapsulation is one of the four elementary concepts of Object
Oriented Programming Language.

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:

• Declare class variables as private or protected (if inheritance is used)


• Assign setters and getters a public access specifier methods for modifying and viewing
values of the variables

Example:

// Here's an example how how encapsulation can be achieved


public class EncapsulationEg {
private String str;
private String num;
private int roll;

public int getRoll() {


return roll;
}

public String getCode() {


return str;
}

public String getVal() {


return num;
}

public void setRoll(int regn) {


roll = regn;
}

public void setCode(String codeName) {


str = codeName;
}

public void setVal(String id) {


num = id;
}
}
Here, first, you have defined a class name EncapsulationEg. Then assign three variables within
the class by the name str and num, having a type as String and roll as integer type having private
as access specifier to make the data hiding possible. Then you have to add set methods and get
methods as public as access points of those instance variables. A name categorizes these methods
as getters and setters.

Advantages of Encapsulation

1. Class fields can be made read-only or write-only


2. Programmers can have full control over what data storage and manipulation within the
class
JAVA INHERITANCE
Inheritance is one of the significant features of an object-oriented programming
language. This is a special feature as it reduces programmers' re-writing effort. This tutorial will
teach you about inheritance and its uses and types.

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
}
}

Inheritance in Java - Video Tutorial

Please watch this video tutorial to understand "Java Inheritance" in more depth.

Why does Java not provide multiple inheritances?

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:

class X extends Y extends Z


{
......
}

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

The interface keyword is used to declare an interface.

Here is a simple program to declare an interface:

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

1. The bytecode of an interface appears in a .class file


2. An Interface is written in a file with .java extension
3. Interfaces may contain any number of methods
4. Interfaces can be arranged in packages and the file can be in a directory structure that
matches the name of the package
Usage of Interface in Java

• For achieving full data abstraction


• Using Interface, you can use the concept of multiple inheritances
• Interfaces can also be used to achieve loose coupling

Properties of Interfaces in Java

1. Interfaces are implicitly abstract


2. Every method within an interface is also implicitly abstract
3. For the above reason, they do not need to be declared abstract
4. All methods of an interface are implicitly public

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();
}

class shapeG implements shapeY {


public String base = "shape3";
public void Draw() {
System.out.println("Drawing Circle here:" + base);
}
@Override
public void Draw2() {
System.out.println("Drawing Circle here:" + base);
}
}

public class Main {


public static void main(String[] args) {
shapeG circleshape = new shapeG();
circleshape.Draw();
circleshape.Draw();
}
}
MULTITHREADING IN JAVA
Unlike many other programming languages, Java provides built-in support for
multithreaded programming. Multithreaded programming contains two or more parts that can run
concurrently. Each piece of such a program is called a thread, and each thread defines a separate
path of execution. Thus multithreading can be said as a particular version of multitasking. In this
chapter, you will learn about how multithreading can be performed in Java and how they are
useful to programmers.

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.

Life Cycle of a Thread

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.

Here is a simple Program to demonstrate Multithreading in Java

Example:

class MultiThread extends Thread{


public void run(){
System.out.println("Running Thread Name: "+ this.currentThread().getName());
System.out.println("Running Thread Priority: "+ this.currentThread().getPriority());
}
}
public class MultiThrd {
public static void main(String[] args) {
MultiThread multiThread1 = new MultiThread();
multiThread1.setName("First Thread");
multiThread1.setPriority(Thread.MIN_PRIORITY);

MultiThread multiThread2 = new MultiThread();


multiThread2.setName("Second Thread");
multiThread2.setPriority(Thread.MAX_PRIORITY);

MultiThread multiThread3 = new MultiThread();


multiThread3.setName("Third Thread");

multiThread1.start();
multiThread2.start();
multiThread3.start();
}
}

Suspending, Resuming, and Stopping Threads

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.

What are packages?

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.

Here's are the benefits of organizing classes:

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

javac -d Destination_folder file_name.java


After that, a folder is created with the given package name in a specific location, and the
compiled class files will be placed in that folder.

The general form of creating a package is:

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 of Java Program implementing Package

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();
}
}

Now compile the java files as shown below:

$ 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:

import package1 [.package2] [.package3].classname;

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.

Why do Programmers use Aggregation in Java?

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:

Student Has-A id (Has-a relationship between student and id)

Staff Has-A id (Has-a relationship between staff and id)

teachers Has-A id (Has-a relationship between teachers and id)


JAVA METHOD OVERRIDING
Declaring a method in the subclass which already exists there in the parent class is
known as method overriding. When a class is inheriting a method from a superclass of its own,
then there is an option of overriding the method provided it is not declared as final. The
advantage of using overriding is the ability to classify a behavior that's specific to the child class,
and the child class can implement a parent class method based on its necessity.

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.

Java Program to Demonstrate Method Overriding

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();
}
}

Method Overriding in Java - Video Tutorial

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.

What is boxing in Java?

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.

What are Wrappers in Java?

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

What are Autoboxing and Auto unboxing?

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.

Autoboxing / Unboxing in Expressions

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;

When programmers perform incrementing of variables/objects of type integers, automatic boxing


and unboxing are done by JVM, where the object is first unboxed then incremented and then
again reboxed into integer type object.

Advantages of autoboxing and auto-unboxing

There are some benefits that this new feature of Java provides us. They are:

• Less code to write


• The code looks cleaner and easily readable
• Programmers do not have to perform Explicit typecasting
• The best method for conversion is automatically chosen
• It helps prevent errors but may lead to unexpected results sometimes.

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.

Autoboxing / Auto unboxing Occurs in Expressions

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.

Here is a simple program showing the working of autoboxing and auto-unboxing:

Example:

public class Main {


public static void main(String args[]) {
Integer iOb = 60, iOb2; // autobox an int
int i = iOb; // auto-unbox
System.out.println(i + " " + iOb);
iOb2 = iOb+(iOb/3);
System.out.println(i + " " + iOb2);
}
}
What is an annotation in Java?

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.

Here is the declaration of annotation named FirstAnno:

Example:

// A simple annotation type


@interface FirstAnno{
String str();
int val();
}

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:

// an enumeration of varieties of programming languages


enum PLtypes
{
highlevel, machinelevel, assembly, middlelevel
}

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:

// use enum to control Switch cases


switch (lang)
{
case assembly:
// . . . . . . . .
Case middlelevel:
// . . . . . . . .
// ....
}
Values() and valuesOf() methods

All enumerations automatically contain two predefined methods: values() and valuesOf(). The
general forms of these statements are:

public static enum-type[ ] values()


public static enum-types valuesOf (string str)

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);
}
}

You might also like