Unit 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 80

UNIT - I

INTRODUCTION TO OOP AND JAVA FUNDAMENTALS

1. Object Oriented Programming (OOP)

Object-oriented programming (OOP) is a programming language model organized around


objects rather than "actions" and data rather than “logic”. Historically, a program has been
viewed as a logical procedure that takes input data, processes it, and produces output data.

Object Oriented Programming (OOP) is a methodology or paradigm to design a program using


classes and objects. It simplifies the software development and maintenance by providing some
concepts:
 Object
 Class
 Abstraction
 Encapsulation
 Inheritance
 Polymorphism

Four major OOPS concepts are


1. Abstraction
2. Polymorphism
3. Inheritance
4. Encapsulation

Structure of a Java Program


Example: “Hello World” Java Program

public class Main {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

The first line defines a class called Main.


public class Main {

In Java, every line of code that can actually run needs to be inside a class. This line declares a
class named Main, which is public, that means that any other class can access it.
Notice that when we declare a public class, we must declare it inside a file with the same
name (Main.java), otherwise we'll get an error when compiling.

1
The next line is:
public static void main(String[] args) {

This is the entry point of the Java program. The main method has to have this exact signature in
order to be able to run our program.
 public again means that anyone can access it.
 static means that we can run this method without creating an instance of Main . (We do
not need to create object for static methods to run. They can run itself)
 void means that this method doesn't return any value.
 main is the name of the method.
The arguments we get inside the method are the arguments that we will get when running the
program with parameters. It's an array of strings.

System.out.println("Hello, World!");

 System is a pre-defined class that Java provides us and it holds some useful methods and
variables.
 out is a static variable within System that represents the output of our program (stdout).
 println is a method of out that can be used to print a line.

1.1 Classes and objects


Classes and Objects are basic concepts of Object Oriented Programming which revolve around
the real life entities.

1.1.1 Class

A class is a user defined blueprint or prototype a program from which objects are created. It
represents the set of properties or methods that are common to all objects of one type.

Example 2:

public class Cat {


int age;
String color;
void barking() {

}
void hungry() {

}
void sleeping() {

}
2
}
Modifiers : A class can be public or has default access.
Class name : The name should begin with an initial letter (capitalized by convention).
Body : The class body surrounded by braces, { }.
Methods : The sub functions a may have in their body.
Variables : A class can contain any number of variables.

A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.

In general, class is a collection of methods (Functions) and attributes (Variables).

1.1.2 Objects

It is a basic unit of Object Oriented Programming and represents the real life entities. A typical
Java program creates many objects, which interact by invoking methods. An object consists of :

State : It is represented by attributes of an object. It also reflects the properties


of an object.
Behavior : It is represented by methods of an object. It also reflects the
response of an object with other objects.
Identity : It gives a unique name to an object and enables one object to
interact with other objects.
Example of an object : Cat, its state is - name, color, and the behavior is - barking, wagging the
tail, running etc.

Example :
public class Point {
int x;
int y;
}

This class defined a point with x and y values (variables).

In order to create an instance of this class, we need to use the keyword new .
Point p = new Point();

Abstraction: In general, object is an instance of a class.

3
1.2 Abstraction

Abstraction is one of the major concepts behind object-oriented programming (OOP).


Abstraction is a process of hiding the implementation details from the user. Оnly the
functionality will be provided to the user. In Java, abstraction is achieved using abstract classes
and interfaces.
Data Abstraction is the property of displaying only the essential details to the user. The trivial or
the non-essentials units are not displayed to the user.
Example : A car is viewed as a car rather than its individual components.
Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.
Example:
abstract class Bike{}

Abstract method

Abstract classes may or may not contain abstract methods, i.e., methods without body (public
void get(); )

But, if a class has at least one abstract method, then the class must be declared abstract. If a class
is declared abstract, it cannot be instantiated. A method that is declared as abstract and does not
have implementation is known as abstract method.

Example:
abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method:


In this example, Bike the abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

// Abstract class declaration


abstract class Bike{
abstract void run();
}
// Class Honda4 inherits the characteristics of the abstract class
class Honda extends Bike{
void run()
{
System.out.println("running safely..");
}

4
// Main class which invokes the class Honda
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}
Understanding the real scenario of abstract class with an example:
Example 1:
File: TestAbstraction1.java
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by the end user
class Rectangle extends Shape{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape{
void draw()
{
System.out.println("drawing circle");
}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[])
{
Shape s=new Circle1();//In real scenario, object is provided through method e.g.
//getShape() method
s.draw();
}
}
Output

drawing circle

5
In the above example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden
to the end user) and object of the implementation class is provided by the factory method. (A
factory method is the method that returns the instance of the class.)
In this example, if we create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
Example 2:
File: TestBank.java
abstract class Bank{
abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest()
{
return 7;
}
}
class IOB extends Bank{
int getRateOfInterest()
{
return 8;
}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new IOB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Output
Rate of Interest is: 7 %
Rate of Interest is: 8 %

6
1.3 Encapsulation
Encapsulation in java is a process of wrapping code and data together into a single unit,
for example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the data
members of the class private. Now we can use setter and getter methods to set and get the data in
it. By providing only setter or getter method, we can make the class read-only or write-only. It
provides the control over the data.

Example :
//Student.java
public class Student{
private String name;

public String getName(){


return name;
}
public void setName(String name){
this.name=name
}
}
//Test.java
class Test{
public static void main(String[] args){
Student s=new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
Output:
vijay
Example 2:
To understand what is encapsulation in detail consider the following bank account class with
deposit and show balance methods:
7
class Account {
private int account_number;
private int account_balance;

public void show Data() {


//code to show data
}

public void deposit(int a) {


if (a < 0) {
//show error
} else
account_balance = account_balance + a;
}
}
Suppose a hacker managed to gain access to the code of our bank account. Now, he tries to
deposit amount -100 into our account by two ways. Let us see the first method or approach.
Approach 1: He tries to deposit an invalid amount (say -100) into our bank account by
manipulating the code.

Class Hacker()
{
Account a = new Account();
a.account_balance=-100;
}

Usually, a variable in a class are set as "private" as shown below. It can only be accessed with
the methods defined in the class. No other class or object can access them.

class Account {
private int account_number;
private int account_balance;

public void show Data() {


//code to show data
}

public void deposit(int a) {

8
If a data member is private, it means it can only be accessed within the same class. No outside
class can access private data member or variable of other class.
So in our case hacker cannot deposit amount -100 to our account.
Approach 2: Hacker's first approach failed to deposit the amount. Next, he tries to do deposit an
amount -100 by using "deposit" method.

Class Hacker()
{
Account a = new Account();
a.account_balance=-100;
a.deposit(-100)
}

But method implementation has a check for negative values. So the second approach also fails.

public void deposit(int a) {


Method
if (a < 0) {
implementation has
//show error
checked for negative
} else values (-100) and
account_balance = throws an exception
account_balance + a;
}

Thus, we never expose our data to an external party. Which makes our application secure.

The entire code can be thought of a capsule, and we can only communicate through the
messages. Hence the name encapsulation.

9
1.4 Inheritance

Inheritance is an important concept of OOP(Object Oriented Programming). It is the mechanism


in java by which one class is allowed to inherit the features (data and methods) of another class.

The aim of inheritance is to provide the reusability of code so that a class has to write only the
unique features and rest of the common properties and functionalities can be extended from the
another class.

Important terminology:
Super Class : The class whose features are inherited is known as super class (or a base class or
a parent class).
Sub Class : The class that inherits the other class is known as sub class (or a derived class,
extended class, or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
Reusability : Inheritance supports the concept of “reusability”, i.e. when we want to create a
new class and there is already a class that includes some of the code that we want,
we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.
The keyword used for inheritance is extends.

Syntax :

class derived-class extends base-class


{
//methods and fields
}

Example:
In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since
class PhysicsTeacher extends the designation and college properties and work() method from
base class, we need not to declare these properties and method in sub class.

Here we have collegeName, designation and work() method which are common to all the
teachers so we have declared them in the base class, this way the child classes
like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be
used directly from base class.

class Teacher {
String designation = "Teacher";
String collegeName = "XYZ College";
void does(){
System.out.println("Teaching");
}

10
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}

Output:

Beginnersbook
Teacher
Physics
Teaching

Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means that
a child class has IS-A relationship with the parent class. This inheritance is known as IS-A
relationship between child and parent class

1.4.1 Types of inheritance in Java


There are five types of Inheritance in OOP concept. However Java support only four types.

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
5. Multiple Inheritances

1. Single Inheritance: refers to a child and parent class relationship where a class extends
another class.

11
Example:
TestInheritance.java
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
2. Multilevel inheritance: refers to a child and parent class relationship where a class extends
the child class. For example class C extends class B and class B extends class A.

12
Example

TestInheritance2.java

class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:

weeping...
barking...
eating..

3. Hierarchical inheritance: refers to a child and parent class relationship where more than
one classes extends the same class. For example, classes B, C & D extends the same class A.

13
Example

TestInheritance3.java
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow(){
System.out.println("meowing...");
}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}

Output:
meowing...
eating...

14
4. Multiple Inheritance: refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both classes
A and B. Java doesn’t support multiple inheritance

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If
A and B classes have same method and we call it from child class object, there will be ambiguity
to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if we
inherit 2 classes. So whether we have same method or different, there will be compile time error
now.

class A{
void msg(){
System.out.println("Hello");
}
}

class B{
void msg(){
System.out.println("Welcome");
}
}
class C extends A,B{//suppose if it were

Public Staticvoid main(String args[]){


C obj=new C();

15
obj.msg();//Now which msg() method would be invoked?
}
}
------ Execute and see the output of this program

5. Hybrid inheritance: It is a mix of two or more of the above types of inheritance. Since
java doesn’t support multiple inheritance with classes, the hybrid inheritance is also not
possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

16
1.5 Polymorphism
Polymorphism in java is a concept by which we can perform a single action by different
ways. For example, we have a smartphone for communication. The communication mode we
choose could be anything. It can be a call, a text message, a picture message, mail, etc. So, the
goal is common that is communication, but their approach is different. This is called
Polymorphism.

Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means
many and "morphs" means forms. So polymorphism means many forms.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java,
all Java objects are polymorphic since any object will pass the IS-A test for their own type and
for the class Object.
Polymorphism is one of the OOPs feature that allows us to perform a single action in
different ways. For example, lets say we have a class Animal that has a method sound(). Since
this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had
to give a generic message.

public class Animal{


...
public void sound(){
System.out.println("Animal is making a sound");
}
}

Now lets say we two subclasses of Animal class: Horse and Cat that extends (see Inheritance)
Animal class. We can provide the implementation to the same method like this:
public class Horse extends Animal{
...
@Override
public void sound(){
System.out.println("Neigh");
}
}

and

public class Cat extends Animal{


...
@Override
public void sound(){
System.out.println("Meow");
}
}

17
Note : The @Override means that the method is overriding the parent class (in this case
createSolver ). When a method is marked with the @Override annotation, the compiler will
perform a check to ensure that the method does indeed override or implement a method in
super class or super interface.

As we can see that although we had the common action for all subclasses sound() but there were
different ways to do the same action. This is a perfect example of polymorphism (feature that
allows us to perform a single action in different ways). It would not make any sense to just call
the generic sound() method as each Animal has a different sound. Thus we can say that the
action this method performs is based on the type of object.

Polymorphism is divided into two, they are:

 Static or Compile time polymorphism (achieved by method overloading)


 Dynamic or Runtime polymorphism (achieved by method overriding)

Static polymorphism in Java is achieved by method overloading and Dynamic polymorphism in


Java is achieved by method overriding

1.5.1 Static or Compile time Polymorphism

Example:
Method Overloading on the other hand is a compile time polymorphism example.

class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;

18
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}

Here the method demo() is overloaded 3 times: first method has 1 int parameter, second method
has 2 int parameters and third one is having double parameter. Which method is to be called is
determined by the arguments we pass while calling methods. This happens at runtime so this
type of polymorphism is known as compile time polymorphism.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25

1.5.2 Dynamic or Runtime Polymorphism:

Example:
Animal.java
public class Animal{
public void sound(){
System.out.println("Animal is making a sound");
}
}

Horse.java
class Horse extends Animal{
@Override
public void sound(){
System.out.println("Neigh");
}
public static void main(String args[]){
Animal obj = new Horse();
obj.sound();
}
}
Output:
Neigh

Cat.java
public class Cat extends Animal{
@Override
public void sound(){
System.out.println("Meow");
}
public static void main(String args[]){
Animal obj = new Cat();
obj.sound();

19
}
}
Output:
Meow

1.5.3 Rules for Method Overriding


 The method signature i.e. method name, parameter list and return type have to match
exactly.
 The overridden method can widen the accessibility but not narrow it, i.e. if it is private in
the base class, the child class can make it public but not vice versa.

Difference between Static & Dynamic Polymorphism (Difference between Overloading and
Overriding)
Static Polymorphism Dynamic Polymorphism
It relates to method overloading. It relates to method overriding.
In case a reference variable is calling an
Errors, if any, are resolved at compile time. overridden method, the method to be invoked
Since the code is not executed during is determined by the object, our reference
compilation, hence the name static. variable is pointing to. This is can be only
determined at runtime when code in under
Ex: execution, hence the name dynamic.

void sum (int a , int b); Ex:


void sum (float a, double b);
int sum (int a, int b); //compiler gives //reference of parent pointing to child
error. object
Doctor obj = new Surgeon();
// method of child called
obj.treatPatient();

20
Method overriding is when one of the methods
in the super class is redefined in the sub-class.
In this case, the signature of the method
Method overloading is in the same class, remains the same.
where more than one method have the same Ex:
class X{
name but different signatures. public int sum(){
// some code
Ex: }
}
void sum (int a , int b); class Y extends X{
void sum (int a , int b, int c); public int sum(){
void sum (float a, double b); //overridden method
//signature is same
}

Important points
 Polymorphism is the ability to create a variable, a function, or an object that has
more than one form.
 In java, polymorphism is divided into two parts : method overloading and method
overriding.
 Another term operator overloading is also there, e.g. “+” operator can be used to
add two integers as well as concat two sub-strings. We cannot have our own
custom defined operator overloading in java.

21
1.6 Characteristics of Java

Simple :

 Java is Easy to write and more readable and eye catching.


 Java has a concise, cohesive set of features that makes it easy to learn and use.
 Most of the concepts are drew from C++ thus making Java learning simpler.
Secure :

 Java program cannot harm other system thus making it secure.


 Java provides a secure means of creating Internet applications.
 Java provides secure way to access web applications.

Platform Independent:
 java is platform independent
 Java is platform independent because it is different from other languages like C, C++ etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
 Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is
a platform-independent code because it can be run on multiple platforms i.e. Write Once
and Run Anywhere(WORA).
Portable:
 Java programs can execute in any environment for which there is a Java run-time
system.(JVM – Java Virtual Machine)
 Java programs can be run on any platform (Linux,Window,Mac)
 Java programs can be transferred over world wide web (e.g applets)

22
Object-oriented :
 Java programming is object-oriented programming language.
 Like C++ java provides most of the object oriented features.
 Java is pure OOP. Language. (while C++ is semi object oriented)
Robust :

 Java encourages error-free programming by being strictly typed and performing run-
time checks.
Multithreaded :

 Java provides integrated support for multithreaded programming.


Architecture-neutral :

 Java is not tied to a specific machine or operating system architecture.


 Machine Independent i.e Java is independent of hardware .
Interpreted :

 Java supports cross-platform code through the use of Java bytecode.


 Bytecode can be interpreted on any platform by JVM.
High performance :

 Bytecodes are highly optimized.


 JVM can executed them much faster .
Distributed :

 Java was designed with the distributed environment.


 Java can be transmit,run over internet.
Dynamic :

 Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time.

23
1.7 Java Runtime Environment (JRE)
The Java Runtime Environment (JRE) is a set of software tools for development of Java
applications. It combines the Java Virtual Machine (JVM), platform core classes and supporting
libraries. JRE is part of the Java Development Kit (JDK) was developed by Sun Microsystems.
Java Source File
A Java source file is a plain text file containing Java source code and having .java extension.
The .java extension means that the file is the Java source file. Java source code file contains
source code for a class, interface, enumeration, or annotation type. There are some rules
associated to Java source file. The following rules to be followed while writing Java source code.
 There can be only one public class per source code file.
 Comments can appear at the beginning or end of any line in the source code file; they are
independent of any of the positioning rules. Java comment can be inserted anywhere in a
program code where a white space can also be.
 If there is a public class in a file, the name of the file must match the name of the public
class. For example, a class declared as public class Student { } must be in a source code
file named Student.java.(i.e the file name and the class name must be same)
 If the class is part of a package, the package statement must be the first line in the source
code file, before any import statements that may be present.
 If there are import statements, they must go between the package statement (if there is
one) and the class declaration. If there isn't a package statement, then the import
statement(s) must be the first line(s) in the source code file. If there are no package or
import statements , the class declaration must be the first line in the source code file.
 import and package statements apply to all classes within a source code file. In other
words, there's no way to declare multiple classes in a file and have them in different
packages, or use different imports.
 A file can have more than one non~public class.
 Files with non~public classes can have a name that does not match any of the classes in
the file

Java Source File Structure


A Java source file can have the following elements that, if present, must be specified in the
following order:
 An optional package declaration to specify a package name.
 Zero or more import declarations.
 Any number of top-level type declarations. Class, enum, and interface declarations
are collectively known as type declarations.
 In Java, at the most one public class declaration per source file can be defined. If a
public class is defined, the file name must match this public class.

24
Example

Example Program:
package javatutorial;
/**
* My first Java HelloWorld class prints the Hello World message.
*
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World : I am learning java @ f5java.com");
}
}
1.7.2 Compile and Run Java Program
Sample Java Program

public class FirstJavaProgram {


public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

25
How to compile and run the above program

Step 1: Open a text editor, like Notepad on windows. Write the program in the text editor.

Step 2: Save the file as FirstJavaProgram.java. We should always name the file same as
the public classname. In our program, the public class name is FirstJavaProgram, that’s why our
file name should be FirstJavaProgram.java.

Step 3: In this step, we will compile the program. For this, open command prompt (cmd) on
Windows.
To compile the program, type the following command and hit enter.

javac FirstJavaProgram.java

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can
run the program. To run the program, type the following command and hit enter:

java FirstJavaProgram

Closer look to the First Java Program


Now that we have understood how to run a java program, let have a closer look at the program
we have written above.

public class FirstJavaProgram {

This is the first line of our java program. Every java application must have at least one class
definition that consists of class keyword followed by class name. When we say keyword, it
means that it should not be changed, we should use it as it is. However the class name can be
anything.
We have made the class public by using public access modifier, we will cover access modifier in
a separate post, all we need to know now that a java file can have any number of classes but it
can have only one public class and the file name should be same as public class name.

public static void main(String[] args) {

This is the next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside
the class.

static: We do not need to create object for static methods to run. They can run itself.

26
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run our
program.
(String[] args): Used for command line arguments that are passed as strings.

System.out.println("This is my first program in java");

This method prints the contents inside the double quotes into the console and inserts a newline
after.

1.8 Fundamental Programming Structure in Java


Java program consists of different sections. Some of them are mandatory but some are
optional. The optional section can be excluded from the program depending upon the
requirements of the programmer.
 Documentation Section
 Package Statement
 Import statements
 Interface Section
 Class Section

Documentation Section: It includes the comments to tell the program's purpose. It improves the
readability of the program.

Single line (or end-of line) comment : It starts with a double slash symbol (//) and
terminates at the end of the current line. The compiler ignores
everything from // to the end of the line. For example:
// Calculate sum of two numbers
Multiline Comment : Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is
ignored by the compiler. This style of comments can be used on part of a
line, a whole line or more commonly to define multi-line comment. For
example.
/*calculate sum of two numbers */
Comments cannot be nested. In other words, we cannot comment a line that already includes
traditional comment. For example,
/* x = y /* initial value */ + z; */ is wrong.

27
Package Statement : It includes statement that provides a package declaration.
For example: Suppose we write the following package declaration as the first statement
in the source code file.
package employee;
This statement declares that all classes and interfaces defined in this source file are part
of the employee package. Only one package declaration can appear in the source file.
Import statements : It includes statements used for referring classes and interfaces that are
declared in other packages.
For example:
Import java.util.Date; /* imports only the Date class in java.util package */
import java.applet.*; // imports all the classes in java applet package
Interface Section : It is similar to a class but only includes constants, method declaration.
Class Section : It describes information about user defines classes present in the
program. Every Java program consists of at least one class definition. This
class definition declares the main method. It is from where the execution
of program actually starts.
Main method :Execution of a java application starts from “main” method. In other
words, its an entry point for the class or program that starts in Java Run-
time.

28
1.9 Defining classes in Java
A class is the basic building block of an object-oriented language such as Java. The class
is a template that describes the data and the behavior associated with instances of that class.
When we instantiate a class we create an object that looks and feels like other instances of the
same class. The data associated with a class or object is stored in variables; the behavior
associated with a class or object is implemented with methods. Methods are similar to the
functions or procedures in procedural languages such as C.

In the Java language, the simplest form of a class definition is

class Name {
...
}

The keyword class begins the class definition for a class named Name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class definition
block. The "Hello World" application has no variables and has a single method named main.

In general, class declarations can include these components, in order:

1. Modifiers such as public, private, and a number of others.


2. The class name, with the initial letter capitalized by convention.
3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A
class can only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the class, if any, preceded by the
keyword implements. A class can implement more than one interface.
5. The class body, surrounded by braces, {}.

Example
public class Cat {
int age;
String color;
void barking() {

Objects
An object is a software module that has state and behavior. An object's state is contained in its
member variables and its behavior is implemented through its methods. When an object of a
class is created, the class is said to be instantiated. All the instances share the attributes and the
behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
A single class may have any number of instances.

29
1.9 Constructors

In Java, constructor is a block of codes similar to method. It is called automatically when an


instance of object is created and memory is allocated for the object.

It is a special type of method which is used to initialize the object.

Constructor
 It is called constructor because it constructs the values at the time of object creation.
 It is not necessary to write a constructor for a class.
 It is because java compiler creates a default constructor if our class doesn't have any.

1.9.1 Rules for creating java constructor

There are basically two rules defined for the constructor.


 Constructor name must be same as its class name
 Constructor must have no explicit return type
Example

public class MyClass{


//This is the constructor
MyClass(){
}
..
}

Note:the constructor name matches with the class name and it doesn’t have a return type.

When we create the object of MyClass


MyClass obj = new MyClass()

The new keyword here creates the object of class MyClass and invokes the constructor to
initialize this newly created object.

1.9.2 A simple constructor program in java

Here we have created an object obj of class Hello and then we displayed the instance
variable name of the object. As we can see that the output is Hello how are you? which is what
we have passed to the name during initialization in constructor. This shows that when we created
the object obj the constructor got invoked. In this example we have used this keyword, which
refers to the current object, object obj in this example.

30
public class Hello {
String name; Keyword this is a reference variable in
//Constructor Java that refers to the current object.
Hello(){
 It can be used to refer instance
this.name = "Hello how are you?";
variable of current class
}
public static void main(String[] args)  It can be used to invoke or initiate
{ current class constructor
Hello obj = new Hello();  It can be passed as an argument in
System.out.println(obj.name);  the method call
}  It can be passed as argument in the
} constructor call
Output  It can be used to return the current
class instance
Hello how are you?

1.9.3 Types of java constructors

There are three types of constructors in java:


1. Default constructor
2. No-arg constructor
3. Parameterized constructor

31
1. Default constructor

If we do not implement any constructor in our class, Java compiler inserts a default constructor
into our code automatically. This constructor is known as default constructor. We cannot find it
in our source code (the java file) as it would be inserted into the code during compilation and
exists in .class file. This process is shown in the diagram below:

If we implement any constructor then we no longer receive a default constructor from Java
compiler.

2. No-arg constructor:

Constructor with no arguments is known as no-arg constructor. The signature is same as default
constructor, however body can have any code unlike default constructor where the body of the
constructor is empty.
Example: no-arg constructor
class Demo
{
public Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[]) {
new Demo();
}
}
Output:
This is a no argument constructor

32
3. Parameterized constructor

Constructor with arguments (or we can say parameters) is known as Parameterized constructor.

Example: parameterized constructor

In this example we have a parameterized constructor with two parameters id and name. While
creating the objects obj1 and obj2 we have passed two arguments so that this constructor gets
invoked after creation of obj1 and obj2.

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Ragu");
obj1.info();
obj2.info();
}
}
Output:
Id: 10245 Name: Chaitanya
Id: 92232 Name: Ragu

Difference between Constructor and Methods


Constructors Methods
A constructor doesn’t have a return type. A method may or may not have a return type.
Constructor always have same name as class
Methods may have any name.
name.
Constructors are called implicitly when object
Methods need to be called explicitly
of the class is created.
Constructors are not considered members of a
Methods are considered members of a class
class

33
1.10 Methods in Java
A method is a collection of statements that perform some specific task and return result to the
caller. A method can perform some specific task without returning anything. Methods allow us
to reuse the code without retyping the code.
In general, method declarations has six components :
 Modifier-: Defines access type of the method i.e. from where it can be accessed in our
application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in our application.
 protected: accessible within the class in which it is defined and in its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within same
class and package within which its class is defined.
 The return type : The data type of the value returned by the the method or void if does not
return a value.
 Method Name : the rules for field names apply to method names as well, but the convention
is a little different.
 Parameter list : Comma separated list of the input parameters are defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, we must use
empty parentheses ().
 Exception list : The exceptions we expect by the method can throw, we can specify these
exception(s).
 Method body : it is enclosed between braces. The code we need to be executed to perform
wer intended operations.

How to call a Java Method?


Now we defined a method, we need to use it. For that, we have to call the method. Here's how:

myMethod();

This statement calls the myMethod() method that was declared earlier.

34
1. While Java is executing the program code, it encounters myMethod(); in the code.
2. The execution then branches to the myFunction() method, and executes code inside
the body of the method.
3. After the codes execution inside the method body is completed, the program returns
to the original state and executes the next statement.

35
1.11 Access Specifiers
Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes,
fields and methods in Java.These Specifiers determine whether a field or method in a class, can
be used or invoked by another method in another class or sub-class. Access Specifiers can be
used to restrict access. Access Specifiers are an integral part of object-oriented programming.

1.11.1 Types Of Access Specifiers :


In java we have four Access Specifiers and they are listed below.
1. public (Visible to the world)
2. private (Visible to the class only)
3. protected (Visible to the package and all subclasses)
4. default (no specifier- Visible to the package)
Example
protected class Test {}

public class Main {


public static void main(String args[]) {

}
}
1.11.2 Static keyword in java
static is a non-access modifier in Java which is applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
To create a static member(block,variable,method,nested class), precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object. For example, in below java program, we
are accessing static method m1() without creating any object of Test class.
// Java program to demonstrate that a static member can be accessed before
//instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating any object of class Test
m1();
}
}
Output:

from m1

36
Advantage of static variable: It makes our program memory efficient (i.e it saves memory).
Note: main method is static, since it must be accessible for an application to run, before any
instantiation takes place.

1.12 Comments in Java


In a program, comments take part in making the program become more human readable by
placing the detail of code involved and proper use of comments makes maintenance easier and
finding bugs easily. Comments are ignored by the compiler while compiling a code.
In Java there are three types of comments:
1. Single – line comments.
2. Multi – line comments.
3. Documentation comments.

1. Single-line Comments
A beginner level programmer uses mostly single-line comments for describing the code
functionality. Its the most easiest typed comments.
Syntax:

//Comments here( Text in this line only is considered as comment )

Example:
//Java program to show single line comments
class Scomment
{
public static void main(String args[])
{
// Single line comment here
System.out.println("Single line comment above");
}
}
2. Multi-line Comments
To describe a full method in a code or a complex snippet single line comments can be tedious
to write, since we have to give ‘//’ at every line. So to overcome this multi line comments can be
used.
Syntax:

/*Comment starts
continues
continues
.
.

Commnent ends*/

Example:

37
//Java program to show multi line comments
class Scomment
{
public static void main(String args[])
{
System.out.println("Multi line comments below");
/*Comment line 1
Comment line 2
Comment line 3*/
}
}
1.13 Data types in Java

Java has two categories of data:

 Primitive data (e.g., number, character)


 Non Primitive data or Object data (programmer created types)

1.13.1 Primitive data


Primitive data are only single values; they have no special capabilities. There are 8 primitive data
types
1. boolean
2. byte
3. short
4. int
5. long
6. float
7. double
8. char

38
1. boolean
boolean data type represents only one bit of information either true or false . Values of
type boolean are not converted implicitly or explicitly (with casts) to any other type. But
the programmer can easily write conversion code.
// A Java program to demonstrate boolean data type
class GeeksforGeeks
{
public static void main(String args[])
{
boolean b = true;
if (b == true)
System.out.println("Hi Geek");
}
}

2. byte
The byte data type is an 8-bit signed two’s complement integer.The byte data type is
useful for saving memory in large arrays.
 Size: 8-bit
 Value: -128 to 127
// Java program to demonstrate byte data type in Java
class Testbyte
{
public static void main(String args[])
{
byte a = 126;

// byte is 8 bit value


System.out.println(a);

a++;

39
System.out.println(a);

// It overflows here because


// byte can hold values from -128 to 127
a++;
System.out.println(a);

// Looping back within the range


a++;
System.out.println(a);
}
}
Output:

126

127

-128

-127

3. short
The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to
save memory in large arrays, in situations where the memory savings actually matters.
Size: 16 bit
Value: -32,768 to 32,767 (inclusive)

4. int
It is a 32-bit signed two’s complement integer.
Size: 32 bit
Value: -231 to 231-1
Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer,
which has value in range [0, 232-1]. Use the Integer class to use int data type as an unsigned
integer.

5. long:
The long data type is a 64-bit two’s complement integer.
Size: 64 bit
Value: -263 to 263-1.

Floating point Numbers : float and double


6. float
The float data type is a single-precision 32-bit. Use a float (instead of double) if we need to
save memory in large arrays of floating point numbers.
40
Size: 32 bits
Suffix : F/f Example: 9.8f
7. double
The double data type is a double-precision 64-bit. For decimal values, this data type is
generally the default choice.

8. char
The char data type is a single 16-bit Unicode character. A char is a single character.
Value: ‘\u0000’ (or 0) to ‘\uffff’ 65535
// Java program to demonstrate primitive data types in Java
class Testchar
{
public static void main(String args[])
{
// declaring character
char a = 'G';

// Integer data type is generally


// used for numeric values
int i=89;

// use byte and short if memory is a constraint


byte b = 4;

// this will give error as number is a larger than byte range


// byte b1 = 7888888955;

short s = 56;

// this will give error as number is larger than short range


// short s1 = 87878787878;

// by default fraction value is double in java


double d = 4.355453532;

// for float use 'f' as suffix


float f = 4.7333434f;

System.out.println("char: " + a);


System.out.println("integer: " + i);
System.out.println("byte: " + b);
System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
}
}

Output:

41
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532

1.13.2 Non Primitive Data Types

Non-primitive data types are created by programmer. It is also called as 'Reference


Variables' or 'Object reference' because it refers a memory location where data is stored. On the
other hand, primitive data types stores value.

String

It is class in java provided with several methods used to store group of characters.
For example, abcd, india123 etc.
String is not a primitive data type because it has methods and only class can have methods.
Primitive data types cannot have methods. So, String is a class which is non-primitive type.
'String' is used to represent string class.
Example: String s="World"

Objects and Array

Objects and Array are non-primitive data types because it refers to the memory location

42
1.14 Java Identifiers
In programming languages, identifiers are used for identification purpose. In Java an
identifier can be a class name, method name, variable name or a label. For example :

public class Test


{
public static void main(String[] args)
{
int a = 20;
}
}

In the above java code, we have 5 identifiers namely :


 Test : class name.
 main : method name.
 String : predefined class name.
 args : variable name.
 a : variable name.

Rules for defining Java Identifiers

There are certain rules for defining a valid java identifiers. These rules must be followed,
otherwise we get compile-time error.
The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9])
 Identifiers should not start with digits([0-9]). For example “123students” is a not a valid
java identifier.
 Java identifiers are case-sensitive.
 There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.
 Reserved Words can’t be used as an identifier. For example “int while = 20;” is an
invalid statement as while is a reserved word.

Variables in Java

A variable is the name given to a memory location. It is the basic unit of storage in a program.
 The value stored in a variable can be changed during program execution.
 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In Java, all the variables must be declared before they can be used.

43
How to declare variables?
We can declare variables in java as follows:

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable

Types of variables

There are three types of variables in Java:


 Local Variables
 Instance Variables
 Static Variables

1.15.1 Local Variables: A variable defined within a block or method or constructor is called local
variable.
 These variable are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
Sample Program 1:

public class StudentDetails


{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}

44
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}

Output:

Student age is : 5

In the above program the variable age is local variable to the function StudentAge(). If we use
the variable age outside StudentAge() function, the compiler will produce an error as shown in
below program.

Sample Program 2:
public class StudentDetails
{
public void StudentAge()
{ //local variable age
int age = 0;
age = age + 5;
}

public static void main(String args[])


{
//using local variable age outside it's scope
System.out.println("Student age is : " + age);
}
}
Output:

error: cannot find symbol


" + age);

1.15.2 Instance Variables:


 Instance variables are non-static variables and are declared in a class outside any method,
constructor or block.
 As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier then the default access specifier will be used.

45
Sample Program:
import java.io.*;
class Marks
{
//These variables are instance variables.
//These variables are in a class and are not inside any function
int engMarks;
int mathsMarks;
int phyMarks;
}

class MarksDemo
{
public static void main(String args[])
{ //first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
obj1.mathsMarks = 80;
obj1.phyMarks = 90;

//second object
Marks obj2 = new Marks();
obj2.engMarks = 80;
obj2.mathsMarks = 60;
obj2.phyMarks = 85;

//displaying marks for first object


System.out.println("Marks for first object:");
System.out.println(obj1.engMarks);
System.out.println(obj1.mathsMarks);
System.out.println(obj1.phyMarks);

//displaying marks for second object


System.out.println("Marks for second object:");
System.out.println(obj2.engMarks);
System.out.println(obj2.mathsMarks);
System.out.println(obj2.phyMarks);
}
}

Output:

Marks for first object:


50
80
90
Marks for second object:
80
60
85

46
As we can see in the above program the variables, engMarks , mathsMarks , phyMarksare
instance variables. In case we have multiple objects as in the above program, each object will
have its own copies of instance variables. It is clear from the above output that each object will
have its own copy of instance variable.

1.15.3 Static Variables: Static variables are also known as Class variables.
 These variables are declared similarly as instance variables, the difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
 Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
 Static variables are created at start of program execution and destroyed automatically
when execution ends.
 To access static variables, we need not to create any object of that class, we can simply
access the variable as:

class_name.variable_name;

Sample Program:
import java.io.*;
class Emp {

// static variable salary


public static double salary;
public static String name = "Harsh";
}

public class EmpDemo


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

//accessing static variable without object


Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}

}
output:

Harsh's average salary:1000.0

47
1.16 Operators

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-

1. Arithmetic Operators
2. Unary Operators
3. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Ternary Operators
7. Bitwise Operators
8. Shift Operators

1. Arithmetic Operators in Java

Java Arithmetic operators are used for simple math operations, they are

 Addition (+)
 Subtraction (-)
 Multiplication (*)
 Division (/)
 Modulo (%)

48
Example

public class operators


{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
String x = "Thank", y = "You";
// + and - operator
System.out.println("a + b = "+(a + b));
System.out.println("a - b = "+(a - b));
// + operator if used with strings
// concatenates the given strings.
System.out.println("x + y = "+x + y);
// * and / operator
System.out.println("a * b = "+(a * b));
System.out.println("a / b = "+(a / b));
// modulo operator gives remainder on dividing first operand
with second
System.out.println("a % b = "+(a % b));
// if denominator is 0 in division then Arithmetic exception is
thrown. Uncommenting below line would throw an exception
// System.out.println(a/c);
}
}
Output
a+b = 30
a-b = 10
x+y = ThankYou
a*b = 200
a/b = 2
a%b = 0

2. Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:

 incrementing/decrementing a value by one


 negating an expression
 inverting the value of a boolean

Example 1: ++ and --

class OperatorExample{
public static void main(String args[]){
int x=10;
49
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x--); //12 (11)
System.out.println(--x); //10
}
}

Output:
10
12
12
10

Example 2: ++ and --
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}
}

Output:

22
21

Example: ~ and !
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//11 (minus of total positive value //whi
ch starts from 0)
System.out.println(~b);//9 (positive of total minus, positive
//starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}

Output:
-11
9

50
false
true
3. Assignment Operators
Assignment operators are used to assigning values to the left operand.
Operator Name Description
To add the right and left operator and then assigning the result to the left
+=
operator
To subtract the two operands on left and right and then assign the value to
-=
the left operand
To multiply the two operands on left and right and then assign the value to
*=
the left operand
To divide the two operands on left and right and then assign the value to the
/=
left operand
^= To raise the value of left operand to the power of right operator
%= To apply modulo operator
General format is
variable = value;
Example 1:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Output:
14
16
Example 2:
class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);

51
}}

Output:

13
9
18
Example 3:
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error

After type cast:


class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
4. Relational Operators : These operators are used to check for equality and comparison.
They return Boolean (true or false) result after the comparison and are extensively used in
looping statements as well as conditional if else statements. General format is,

variable relation_operator value

Operator Name Description


== (equals to) ex. x==y True if x equals y, otherwise false
!= (not equal to) ex. x!=y True if x is not equal to y, otherwise false
< (less than) ex. x<y True if x is less than y, otherwise false
> (greater than) ex.x > y True if x is greater than y, otherwise false
True if x is greater than or equal to y, otherwise
>= (greater than or equal to) ex. x>=y
false
<= (less than or equal to) ex. x<=y True if x is less than or equal to y, otherwise false

52
Example
// Java program to illustrate
// relational operators
public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10;
String x = "Thank", y = "Thank";
int ar[] = { 1, 2, 3 };
int br[] = { 1, 2, 3 };
boolean condition = true;

//various conditional operators


System.out.println("a == b :" + (a == b));
System.out.println("a < b :" + (a < b));
System.out.println("a <= b :" + (a <= b));
System.out.println("a > b :" + (a > b));
System.out.println("a >= b :" + (a >= b));
System.out.println("a != b :" + (a != b));

// Arrays cannot be compared with


// relational operators because objects
// store references not the value
System.out.println("x == y : " + (ar == br));

System.out.println("condition==true :" + (condition == true));


}
}

Output :

a==b :false
a=b :true
a!=b :true
x==y : false
condition==true :true

5. Logical Operators :
These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function
similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second
condition is not evaluated if the first one is false, i.e. it has short-circuiting effect. Used
extensively to test for several conditions for making a decision.
Conditional operators are-

 && Logical AND : returns true when both conditions are true.
 || Logical OR : returns true if at least one condition is true.

53
// Java program to illustrate
// logical operators
public class operators
{
public static void main(String[] args)
{
String x = "Sher";
String y = "Locked";

Scanner s = new Scanner(System.in);


System.out.print("Enter username:");
String uuid = s.next();
System.out.print("Enter password:");
String upwd = s.next();

// Check if user-name and password match or not.


if ((uuid.equals(x) && upwd.equals(y)) ||
(uuid.equals(y) && upwd.equals(x))) {
System.out.println("Welcome user.");
} else {
System.out.println("Wrong uid or password");
}

}
}

Output :

Enter username:Sher
Enter password:Locked
Welcome user.

6. Ternary operator :
Ternary operator is a shorthand version of if-else statement. It has three operands and hence the
name ternary. General format is-

condition ? if true : if false

Example

minVal = (a < b) ? a : b;

The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.

7. Bitwise Operators :

These operators are used to perform manipulation of individual bits of a number. They can be
used with any of the integer types. They are used when performing update and query operations
of Binary indexed tree.

54
 & Bitwise AND operator: returns bit by bit AND of input values.
 | Bitwise OR operator: returns bit by bit OR of input values.
 ^ Bitwise XOR operator: returns bit by bit XOR of input values.
 ~ Bitwise Complement Operator: This is a unary operator which returns the one’s
compliment representation of the input value, i.e. with all bits inversed.

// bitwise operators
public class operators
{
public static void main(String[] args)
{

int a = 0x0005;
int b = 0x0007;

// bitwise and
// 0101 & 0111=0101
System.out.println("a&b = " + (a & b));

// bitwise and
// 0101 | 0111=0111
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010
System.out.println("a^b = " + (a ^ b));

// bitwise and
// ~0101=1010
System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}

Output :

a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5

55
8. Shift Operators :
These operators are used to shift the bits of a number left or right thereby multiplying or
dividing the number by two respectively. They can be used when we have to multiply or divide a
number by two. General format-
number shift_op number_of_places_to_shift;

 << Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as of multiplying the number with some power of two.
 >> Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect
as of dividing the number with some power of two.
 >>> Unsigned Right shift operator: shifts the bits of the number to the right and fills 0
on voids left as a result. The leftmost bit is set to 0.

// shift operators
public class operators
{
public static void main(String[] args)
{

int a = 0x0005;
int b = -10;

// left shift operator


// 0000 0101<<2 =0001 0100(20)
// similar to 5*(2^2)
System.out.println("a<<2 = " + (a << 2));

// right shift operator


// 0000 0101 >> 2 =0000 0001(1)
// similar to 5/(2^2)
System.out.println("a>>2 = " + (a >> 2));

// unsigned right shift operator


System.out.println("b>>>2 = "+ (b >>> 2));

}
}
Output :
a2 = 1
b>>>2 = 1073741821

Operator Precedence

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Precedence and associative rules are used when dealing with hybrid
equations involving more than one type of operator. In such cases, these rules determine which

56
part of equation to consider first as there can be many different valuations for the same equation.
Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator

Example

x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so
it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity


Postfix >() [] . (dot operator) Left toright
Unary >++ - - ! ~ Right to left
Multiplicative >* / Left to right
Additive >+ - Left to right
Shift >>> >>> << Left to right
Relational >> >= < <= Left to right
Equality >== != Left to right
Bitwise AND >& Left to right
Bitwise XOR >^ Left to right
Bitwise OR >| Left to right
Logical AND >&& Left to right
Logical OR >|| Left to right
Conditional ?: Right to left
Assignment >= += -= *= /= %= >>= <<= &= ^= |= Right to left

57
1.17 Control Flow Statements

When we write a program, we type statements into a file. Without control flow
statements, the interpreter executes these statements in the order they appear in the file from left
to right, top to bottom. We can use control flow statements in the programs to conditionally
execute statements, to repeatedly execute a block of statements, and to otherwise change the
normal, sequential flow of control.

The Java programming language provides several control flow statements, which are listed in the
following table.

Statement Type Keyword


decision making if-else, switch-case

Looping while, do-while , for

exception handling try-catch-finally, throw

branching break, continue, label:, return

1.17.1 Decision Making Statements

Decision making statement statements is also called selection statement. That is depending on
the condition block need to be executed or not while is decided by condition. If the condition is
"true" statement block will be executed, if condition is "false" then statement block will not be
executed.

In java there are three types of decision making statement.

 if
 if-else
 switch

58
if-then Statement

if-then is the most basic statement of the decision making statement. It tells to program to
execute a certain part of code only if a particular condition or test is true.

Syntax

if(condition)
{
Statement(s)
}

 Constructing the body if always optional, that is recommended to create the body when
we are having multiple statements.
 For a single statement, it is not required to specify the body.
 If the body is not specified, then automatically condition parts will be terminated with
next semicolon ;.

Else

 It is a keyword, by using this keyword we can create an alternative block for "if" part.
 Using else is always optional i.e, it is recommended to use when we are having alternate
block of condition.
 When we are working with if else among those two block at any given point of time only
one block will be executed.

59
 When if condition is false, then else part will be executed, if part is executed, then
automatically else part will be ignored.

if-else statement

In general, it can be used to execute one block of statement among two blocks, in Java language
if and else are the keyword in Java.

Syntax

if(condition)
{
Statement(s)
}
else
{
Statement(s)
}
Statement(s)

In the above syntax whenever the condition is true all the if block statement are executed
remaining statement of the program by neglecting else block statement. If the condition is false
else block statement remaining statement of the program are executed by neglecting if block
statements.

A Java program to find the addition of two numbers if first number is greater than the second
number otherwise find the subtraction of two numbers.

Example
import java.util.*;
class Num
{
public static void main(String args[])
{
int a=10,b=20, c;
System.out.println("Enter any two num");
if(a>b)
{
c=a+b;
}
else
{
c=a-b;
}
System.out.println("Result="+c);
}
}

60
3. Switch Statement

A switch statement work with byte, short, char and int primitive data type, it also works with
enumerated types and string.

Syntax

switch(expression/variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}

Rules for apply switch statement

With switch statement use only byte, short, int, char data type. We can use any number of case
statements within a switch. The value for a case must be same as the variable in a switch.

Limitations of switch statement

Logical operators cannot be used with a switch statement. For instance

Example

case k>=20:

is not allowed

Switch case variables can have only int and char data type. So float data type is not allowed. For
instance in the switch syntax given below:

Syntax

switch(ch)
{
case 1:
statement-1;
break;
case 2:
statement-2;
break;
}

In this ch can be integer or char and cannot be float or any other data type.

61
1.17.2 Looping statement

These are the statements execute one or more statement repeatedly a several number of times. In
Java programming language there are three types of loops are available, that is, while, for and
do-while.

Advantage with looping statement

 Length on the developer is reducing.


 Burden on the developer is reducing.
 Burden of memory space is reduced time consuming process to execute the program is
reduced.

Difference between conditional and looping statement

Conditional statement executes only once in the program were as looping statement executes
repeatedly several numbers of time.

1. While loop

 When we are working with while loop always pre-checking process will be occurred.
 Pre-checking process means before the evolution of statement block condition parts will
be executed.
 While loop will be repeated in clockwise direction.

Syntax

while(condition)
{
Statement(s)
Increment / decrements (++ or --);
}

Example

class whileDemo
{
public static void main(String args[])
{
int i=0;
while(i<10)
{
System.out.println(+i);
i++;
}

62
Output

1
2
3
4
5
6
7
8
9
10

2. for loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts.

 Initialization
 Condition
 Increment or Decrements

Syntax

for ( initialization; condition; increment )


{
statement(s);
}

 Initialization: step is executed first and this is executed only once when we are entering
into the loop first time. This step allows to declare and initialize any loop control
variables.
 Condition: is the next step after initialization step, if it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control goes
outside the for loop.
 Increment or Decrements: After completion of Initialization and Condition steps loop
body code is executed and then Increment or Decrements steps is executed. This
statement allows to update any loop control variables.

63
Flow Diagram

Control flow of for loop

64
 First Initialize the variable
 In second step check condition
 In third step control goes inside loop body and execute.
 At last increase the value of variable
 Same process is repeat until condition not false.

A java program to display any message exactly 10 times.

Example

class hello
{
public static void main(String args[])
{
int i;
for (i=0: i<10; i++)
{
System.out.println("Hello Friends");
}
}
}

3. do-while

65
 when we need to repeat the statement block at least 1 then go for do-while.
 In do-while loop post-checking process will be occur, that is after execution of the
statement block condition part will be executed.

Syntax

do
{
Statement(s)

increment/decrement (++ or --)


}while();

Example

class dowhileDemo
{
public static void main(String args[])
{
int i=0;
do
{
System.out.println(+i);
i++;

}
While(i<10);
}
}

Output

1
2
3
4
5
6
7
8
9
10

66
1.17.3 Exception Handling Statements

The Java programming language provides a mechanism known as exceptions to help programs
report and handle errors. When an error occurs, the program throws an exception. It means that
the normal flow of the program is interrupted and that the runtime environment attempts to find
an exception handler, which is a block of code that can handle a particular type of error. The
exception handler can attempt to recover from the error or, if it determines that the error is
unrecoverable, provide a gentle exit from the program.

Three statements play a part in handling exceptions:

 The try statement identifies a block of statements within which an exception might be
thrown.
 The catch statement must be associated with a try statement and identifies a block of
statements that can handle a particular type of exception. The statements are executed if
an exception of a particular type occurs within the try block.
 The finally statement must be associated with a try statement and identifies a block of
statements that are executed regardless of whether or not an error occurs within the try
block.

Here's the general form of these statements:

try {
statement(s)
} catch (exceptiontype name) {
statement(s)
} finally {
statement(s)
}

1.17.4 Branching Statements

The Java programming language supports three branching statements:

 The break statement


 The continue statement
 The return statement

The break statement and the continue statement, which are covered next, can be used with or
without a label. A label is an identifier placed before a statement. The label is followed by a
colon (:)
statementName: someJavaStatement;

The break statement has two forms: unlabeled and labeled. We saw the unlabeled form of the
break statement used with switch earlier. As noted there, an unlabeled break terminates the
enclosing switch statement, and flow of control transfers to the statement immediately
following the switch. We can also use the unlabeled form of the break statement to terminate a
for, while, or do-while loop.

67
// break statement for a while loop
public class BreakStatement {

public static void main(String[] args) {

Random random = new Random();

while (true) {

int num = random.nextInt(30);


System.out.print(num + " ");

if (num == 22) {

break;
}
}

System.out.print('\n');
}
}

The unlabeled form of the break statement is used to terminate the innermost switch, for,
while, or do-while.
The labeled form terminates an outer statement, which is identified by the label specified in the
break statement.

public class MainClass {


public static void main(String[] args) {

OuterLoop: for (int i = 2;; i++) {


for (int j = 2; j < i; j++) {
if (i % j == 0) {
continue OuterLoop;
}
}
System.out.println(i);
if (i == 37) {
break OuterLoop;
}
}
}
}

Output

2
3
5
7
11
13
17
19
23

68
29
31
37

Continue Statement

The continue statement is used to skip a part of the loop and continue with the next iteration of
the loop. It can be used in combination with for and while statements.

Below is a program to demonstrate the use of continue statement to print Odd Numbers between
1 to 10.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i + "\t");
}
}
}

Output

Odd Numbers
1
3
5
7
9

return keyword in Java

return is a reserved keyword in Java and we can’t use it as an identifier. It is used to exit from a
method, with or without a value.

69
return can be used with methods in two ways:

1. Methods returning a value :

For methods that define a return type, return statement must be immediately followed by return
value.

// Java program to illustrate usage


// of return keyword

class A {

// Since return type of RR method is double


// so this method should return double value
double RR(double a, double b)
{
double sum = 0;
sum = (a + b) / 2.0;
// return statement below:
return sum;
}
public static void main(String[] args)
{
System.out.println(new A().RR(5.5, 6.5));
}
}

Output:

6.0

2. Methods not returning a value :

For methods that don’t return a value, return statement can be skipped.

public class Program {

static void displayPassword(String password) {


// Write the password to the console.
System.out.println("Password: " + password);
// Return if our password is long enough.
if (password.length() >= 5) {
return;
}
System.out.println("Password too short!");
// An implicit return is here.
}

public static void main(String[] args) {


displayPassword("basketball");
displayPassword("cat");
}

70
}

Output

Password: basketball
Password: cat
Password too short!

1.18 Array

Array is a collection of similar type of elements that have contiguous memory location.

Java array is an object that contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed set of elements in a java array.

Array in java is index based, first element of the array is stored at 0 index.

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

1. Single Dimensional Array

Declaring Array Variables

To use an array in a program, we must declare a variable to reference the array, and we must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable −

Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // correct but not preferred way.

71
Example
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way.

Creating (Instating) Arrays

We can create an array by using the new operator with the following syntax −

Syntax
arrayRefVar = new dataType[arraySize];

The above statement does two things −

 It creates an array using new dataType[arraySize].


 It assigns the reference of the newly created array to the variable arrayRefVar.

Example

Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList −

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

Processing Arrays

When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG
{
public static void main (String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

72
// initialize the second elements of the array
arr[1] = 20;

//so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
}
}

Output:

Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

2. Multidimensional Array

Multidimensional arrays are arrays of arrays with each element of the array holding the
reference of other array. These are also known as Jagged Arrays. A multidimensional array is
created by appending one set of square brackets ([]) per dimension.

Examples:

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

Example

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

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();

73
}

}
}
Output:1 2 3
2 4 5
4 4 5

Passing Arrays to Methods

Like variables, we can also pass arrays to methods. For example, below program pass array to
method sum for calculating sum of array's values.

// Java program to demonstrate


// passing of array to method

class Test
{
// Driver method
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
// passing array to method m1
sum(arr);
}
public static void sum(int[] arr)
{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum+=arr[i];
System.out.println("sum of array values : " + sum);
}
}

Output :

sum of array values : 15

Returning Arrays from Methods

As usual, a method can also return an array. For example, below program returns an array from
method m1.
// Java program to demonstrate
// return of array from method
class Test
{
// Driver method
public static void main(String args[])
{

74
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i]+" ");

}
public static int[] m1()
{
// returning array
return new int[]{1,2,3};
}
}
Output:

1 2 3

1.19 Java Package

A java package is a group of similar types of classes, interfaces and sub-packages. Package in
java can be categorized in two form, built-in package and user-defined package. There are many
built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Here, we will have
the detailed learning of creating and using user-defined packages.

Advantage of Java Package

These are the reasons why we should use packages in Java:

 Reusability: While developing a project in java, we often feel that there are few things
that we are writing again and again in our code. Using packages, we can create such
things in form of classes inside a package and whenever we need to perform that same
task, just import that package and use the class.
 Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful package
name so that we can organize our project better and when we need something we can
quickly locate it and use it, which improves the efficiency.
 Name Conflicts: We can define two classes with the same name in different packages so
to avoid name collision, we can use packages

Types of packages in Java

As mentioned in the beginning of this guide that we have two types of packages in java.
User defined package : The package we create is called user-defined package.
Built-in package : The already defined package like java.io.*, java.lang.* etc are
known as built-in packages.

75
1. Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some
of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

2. User defined package

Example

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If we use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.

76
Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Using packagename.classname

If we import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello

77
1.20 JavaDoc Comments

One of the nice things about Java is javadoc. The javadoc utility lets us to put our comments
right next to our code, inside our ".java" source files. Javadoc is a tool which comes with JDK
and it is used for generating Java code documentation in HTML format from Java source code,
which requires documentation in a predefined format.

Java language supports three types of comments −

Sr.No. Comment & Description

1 /* text */
The compiler ignores everything from /* to */.

2 //text
The compiler ignores everything from // to the end of the line.

3 /** documentation */
This is a documentation comment and in general its called doc comment. The JDK
javadoc tool uses doc comments when preparing automatically generated
documentation.

We can include required HTML tags inside the description part. For instance, the following
example makes use of <h1>....</h1> for heading and <p> has been used for creating paragraph
break.

Example

/**
* <h1>Hello, World!</h1>
* The HelloWorld program implements an application that
* simply displays "Hello World!" to the standard output.
* <p>
* Giving proper comments in your program makes it more
* user friendly and it is assumed as a high quality code.
*
*
* @author Author_Name
* @version 1.0
* @since 2018-03-31
*/
public class HelloWorld {

public static void main(String[] args) {

78
/* Prints Hello, World! on standard output.
System.out.println("Hello World!");
}
}

1.20.1 The javadoc Tags

The javadoc tool recognizes the following tags

Tag Description Syntax

@author Adds the author of a class. @author name-text

Displays text in code font without


{@code} interpreting the text as HTML markup or {@code text}
nested javadoc tags.

Represents the relative path to the generated


{@docRoot} document's root directory from any generated {@docRoot}
page.

Adds a comment indicating that this API @deprecated deprecatedtext


@deprecated
should no longer be used.

Adds a Throws subheading to the generated


@exception class-name
@exception documentation, with the classname and
description
description text.

Inherits a comment from Inherits a comment from


{@inheritDoc} the nearestinheritable class or implementable the immediate surperclass.
interface.

Inserts an in-line link with the visible text


{@link
label that points to the documentation for the
{@link} package.class#member
specified package, class, or member name of
label}
a referenced class.

Identical to {@link}, except the link's label is {@linkplain


{@linkplain} displayed in plain text than code font. package.class#member
label}

Adds a parameter with the specified


@param parameter-name
@param parameter-name followed by the specified
description
description to the "Parameters" section.

@return Adds a "Returns" section with the description @return description

79
text.

Adds a "See Also" heading with a link or text


@see @see reference
entry that points to reference.

Used in the doc comment for a default @serial field-description |


@serial
serializable field. include | exclude

Documents the data written by the @serialData data-


@serialData writeObject( ) or writeExternal( ) methods. description

Documents an ObjectStreamField @serialField field-name


@serialField
component. field-type field-description

Adds a "Since" heading with the specified


@since since-text to the generated documentation. @since release

The @throws and @exception tags are @throws class-name


@throws
synonyms. description

When {@value} is used in the doc comment


of a static field, it displays the value of that {@value
{@value}
constant. package.class#field}

Adds a "Version" subheading with the


specified version-text to the generated docs
@version when the -version option is used. @version version-text

*** End of Unit – I ***

80

You might also like