KEMBAR78
Java Unit Ii | PDF | Data Type | Java Virtual Machine
0% found this document useful (0 votes)
18 views47 pages

Java Unit Ii

The document provides an overview of the history and features of the Java programming language, detailing its origins, development milestones, and key characteristics. It explains the Java Virtual Machine (JVM) architecture, the differences between Java and C++, and introduces basic Java programming concepts, including data types and a simple 'Hello World' program. Additionally, it outlines the evolution of Java versions and highlights Java's platform independence and object-oriented nature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views47 pages

Java Unit Ii

The document provides an overview of the history and features of the Java programming language, detailing its origins, development milestones, and key characteristics. It explains the Java Virtual Machine (JVM) architecture, the differences between Java and C++, and introduces basic Java programming concepts, including data types and a simple 'Hello World' program. Additionally, it outlines the evolution of Java versions and highlights Java's platform independence and object-oriented nature.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

BCA - JAVA

YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH


PRORAMMING

UNIT II
INTRODUCTION TO JAVA
HISTORY OF JAVA

The history of Java is very interesting. Java was originally designed for interactive television, but it
was too advanced technology for the digital cable television industry at the time. The history of Java
starts with the Green Team. Java team members (also known as Green Team), initiated this project
to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was suited
for internet programming. Later, Java technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given significant points that describe the history of Java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.

2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Java named "Oak"?

5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.

Why Java Programming named "Java"?

7) Why had they chosen java name for Java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.

According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so
unique, most of the team members preferred Java than other names.
1
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It is a kind
of espresso bean. Java name was chosen by James Gosling while having coffee near his office.

9) Notice that Java is just a name, not an acronym.

10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds the new
features in Java.

JAVA VERSION HISTORY

Many java versions have been released till now. The current stable release of Java is Java SE 10.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 14.0. 2 (March 2020)

THE JAVA VIRTUAL MACHINE

What is JVM?

Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code
or applications. It converts Java bytecode into machines language. JVM is a part of Java Run
Environment (JRE). In other programming languages, the compiler produces machine code for a
particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual
Machine.
2
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Here is how JVM works

First, Java code is complied into bytecode. This bytecode gets interpreted on different machines
Between host system and Java source, Bytecode is an intermediary language. JVM is responsible for
allocating memory space.

JVM Architecture

Let's understand the Architecture of JVM. It contains classloader, memory area, execution engine etc.

1) ClassLoader

The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.

2) Method Area

JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for
methods.

3) Heap

All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.

4) JVM language Stacks

Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack,
created simultaneously as the thread is created. A new frame is created whenever a method is invoked,
3

and it is deleted when method invocation process is complete.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

5) PC Registers

PC register store the address of the Java virtual machine instruction which is currently executing. In
Java, each thread has its separate PC register.

6) Native Method Stacks

Native method stacks hold the instruction of native code depends on the native library. It is written in
another language instead of Java.

7) Execution Engine

It is a type of software used to test hardware, software, or complete systems. The test execution engine
never carries any information about the tested product.

8) Native Method interface

The Native Method Interface is a programming framework. It allows Java code which is running in a
JVM to call by libraries and native applications.

9) Native Method Libraries

Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution
Engine.

Why is Java both Interpreted and Compiled Language?

Programming languages are classified as

 Higher Level Language Ex. C++, Java


 Middle-Level Languages Ex. C
 Low-Level Language Ex Assembly
 finally the lowest level as the Machine Language.

A compiler is a program which converts a program from one level of language to another. Example
conversion of C++ program into machine code.

The java compiler converts high-level java code into bytecode (which is also a type of machine code).

An interpreter is a program which converts a program at one level to another programming language
at the same level. Example conversion of Java program into C++

In Java, the Just In Time Code generator converts the bytecode into the native machine code which
are at the same programming levels.

Hence, Java is both compiled as well as interpreted language.


4
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

C++ VS JAVA
There are many differences and similarities between the C++ programming language and Java. A list
of top differences between C++ and Java are given below:

Comparison Index C++ Java

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.

Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. interpreter for printing systems but
It was an extension of C later extended as a support network
programming language. computing. It was designed with a goal
of being easy to use and accessible to a
broader audience.

Goto C++ supports Java doesn't support the goto


the goto statement. statement.

Multiple C++ supports multiple Java doesn't support multiple


inheritance inheritance. inheritance through class. It can be
achieved by interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You Java supports pointer internally.


can write pointer program in However, you can't write the pointer
C++. program in java. It means java has
restricted pointer support in java.

Compiler and C++ uses compiler only. C++ Java uses compiler and interpreter
Interpreter is compiled and run using the both. Java source code is converted
compiler which converts into bytecode at compilation time. The
source code into machine code interpreter executes this bytecode at
so, C++ is platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.
5
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Call by Value C++ supports both call by Java supports call by value only. There
and Call by value and call by reference. is no call by reference in java.
reference

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.

Documentation C++ doesn't support Java supports documentation comment


comment documentation comment. (/** ... */) to create documentation for
java source code.

Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide whether override all non-static methods by
or not override a function. default. In other words, non-static
methods are virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive
numbers, it works same like >>
operator.

Inheritance Tree C++ creates a new inheritance Java uses a single inheritance tree
tree always. always because all classes are the child
of Object class in java. The object
class is the root of the inheritance tree
in java.

Hardware C++ is nearer to hardware. Java is not so interactive with


hardware.

Object-oriented C++ is an object-oriented Java is also an object-oriented language.


language. However, in C However, everything (except fundamental
language, single root hierarchy is types) is an object in Java. It is a single
not possible. root hierarchy as everything gets derived
from java.lang.Object.

Note
o Java doesn't support default arguments like C++.
o Java does not support header files like C++. Java uses the import keyword to include different
6

classes and methods.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

SIMPLE JAVA PROGRAM

Creating Hello World Example

Let's create the hello java program:

class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}

Compilation Flow:

When we compile Java program using javac tool, java compiler converts the source code into byte
code.

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

o class keyword is used to declare a class in java.


o public keyword is an access modifier which represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The
core advantage of the static method is that there is no need to create an object to invoke the
static method. The main method is executed by the JVM, so it doesn't require to create an
object to invoke the main method. So it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class.
7
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

JAVA DATA TYPES

Data types are divided into two groups:

 Primitive data types - includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes

PRIMITIVE DATA TYPES

A primitive data type specifies the size and type of variable values, and it has no additional methods.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
8
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Integer Types
Byte

The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other
integer types to save memory when you are certain that the value will be within -128 and 127:

Example

byte myNum = 100;

System.out.println(myNum);

Short

The short data type can store whole numbers from -32768 to 32767:

Example

short myNum = 5000;

System.out.println(myNum);

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.

Example

int myNum = 100000;

System.out.println(myNum);

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with
an "L":

Example

long myNum = 15000000000L;

System.out.println(myNum);

Floating Point Types

You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
9

3.14515.
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Float

The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end
the value with an "f":

Example

float myNum = 5.75f;

System.out.println(myNum);

Double

The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should
end the value with a "d":

Example

double myNum = 19.99d;

System.out.println(myNum);

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the power of 10:

Example

float f1 = 35e3f;

double d1 = 12E4d;

System.out.println(f1);

System.out.println(d1);

Booleans

A boolean data type is declared with the boolean keyword and can only take the values true or false:

Example

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun); // Outputs true

System.out.println(isFishTasty); // Outputs false


10

Boolean values are mostly used for conditional testing, which you will learn more about in a later
chapter.
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Characters

The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':

Example

char myGrade = 'B';

System.out.println(myGrade);

Alternatively, you can use ASCII values to display certain characters:

Example

char a = 65, b = 66, c = 67;

System.out.println(a);

System.out.println(b);

System.out.println(c);

Strings

The String data type is used to store a sequence of characters (text). String values must be surrounded
by double quotes:

Example

String greeting = "Hello World";

System.out.println(greeting);

NON-PRIMITIVE DATA TYPES

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

 Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
11
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

 The size of a primitive type depends on the data type, while non-primitive types have all the
same size.

JAVA COMMENTS

Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).This example uses
a single-line comment before a line of code:

Example

// This is a comment

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

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.This example uses a multi-line comment (a
comment block) to explain the code:

Example

/* The code below will print the words Hello World

to the screen, and it is amazing */

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

JAVA VARIABLES

Variables are containers for storing data values.In Java, there are different types of variables, for
example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


12

To create a variable, you must specify the type and assign it a value:
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Syntax

type variable = value;

Where type is one of Java's types (such as int or String), and variable is the name of the variable (such
as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example

Create a variable called name of type String and assign it the value "John":

String name = "John";

System.out.println(name);

Display Variables

The println() method is often used to display variables.

To combine both text and a variable, use the + character:

Example

String name = "John";

System.out.println("Hello " + name);

KEYWORDS
Keywords are predefined, reserved words used in Java programming that have special meanings to the
compiler. For example:

int score;

Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed two's
complement integer).
You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are part of
the Java programming language syntax. Here's the complete list of all keywords in Java programming.

Java Keywords List

abstract assert boolean break byte

case catch char class const


13
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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

Beside these keywords, you cannot also use true, false and null as identifiers. It is because they are
literals.

JAVA IDENTIFIERS

Identifiers are the name given to variables, classes, methods, etc. Consider the above code;

int score;

Here, score is a variable (an identifier). You cannot use keywords as variable names. It's because
keywords have predefined meanings.
Rules for Naming an Identifier
1. Identifiers cannot be a keyword.
2. Identifiers are case-sensitive.
3. It can have a sequence of letters and digits. However, it must begin with a letter, $ or _.
The first letter of an identifier cannot be a digit.
4. It's a convention to start an identifier with a letter rather and $ or _.
5. Whitespaces are not allowed.
6. Similarly, you cannot use symbols such as @, #, and so on.

Here are some valid identifiers:


14

1. score
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

2. level
3. highestScore
4. number1
5. convertToString
Here are some invalid identifiers:

1. class
2. float
3. 1number
4. highest Score
5. @pple

LITERALS IN JAVA
Literal : Any constant value which can be assigned to the variable is called as literal/constant.
// Here 100 is a constant/literal.

int x = 100;

Integral literals
For Integral data types (byte, short, int, long), we can specify literals in 4 ways:-

1. Decimal literals (Base 10) : In this form the allowed digits are 0-9.
int x = 101;

2. Octal literals (Base 8) : In this form the allowed digits are 0-7.
// The octal number should be prefix with 0.

int x = 0146;

3. Hexa-decimal literals (Base 16) : In this form the allowed digits are 0-9 and characters are a-f.
We can use both uppercase and lowercase characters. As we know that java is a case-sensitive
programming language but here java is not case-sensitive.
// The hexa-decimal number should be prefix

// with 0X or 0x.

int x = 0X123Face;
15
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

4. Binary literals : From 1.7 onward we can specify literals value even in binary form also, allowed
digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;

JAVA OPERATORS

Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:

Example

int x = 100 + 50;

Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)

Java divides the operators into the following groups:

1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x


16
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Java Assignment Operators

Assignment operators are used to assign values to variables. In the example below, we use
the assignment operator (=) to assign the value 10 to a variable called x:

Example

int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example

int x = 10;

x += 5;

A list of all assignment operators:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Java Comparison Operators

Comparison operators are used to compare two values:

Operator Name Example


17

== Equal to x == y
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Java Logical Operators

Logical operators are used to determine the logic between variables or values:

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result !(x < 5 && x <
is true 10)

Java Bitwise Operators

Bitwise operators are used to perform binary logic with the bits of an integer or long integer.

Operator Description Example Same as Result Decimal

& AND - Sets each bit to 1 if both bits are 5&1 0101 & 0001 1
1 0001

| OR - Sets each bit to 1 if any of the two 5|1 0101 | 0001 0101 5
bits is 1

~ NOT - Inverts all the bits ~5 ~0101 1010 10

^ XOR - Sets each bit to 1 if only one of 5^1 0101 ^ 0001 0100 4
the two bits is 1

<< Zero-fill left shift - Shift left by pushing 9 << 1 1001 << 1 0010 2
zeroes in from the right and letting the
leftmost bits fall off

>> Signed right shift - Shift right by pushing 9 >> 1 1001 >> 1 1100 12
copies of the leftmost bit in from the left
and letting the rightmost bits fall off

>>> Zero-fill right shift - Shift right by 9 >>> 1 1001 >>> 1 0100 4
pushing zeroes in from the left and
18

letting the rightmost bits fall off


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

CASTS AND CONVERSIONS

Type casting is when you assign a value of one primitive data type to another type.In Java, there are
two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:

Example

public class MyClass {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of the value:

Example

public class MyClass {

public static void main(String[] args) {

double myDouble = 9.78;

int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9
19

}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

JAVA ARRAYS

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.

To declare an array, define the variable type with square brackets:

String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, we can
use an array literal - place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

You access an array element by referring to the index number. This statement accesses the value of
the first element in cars:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars[0]);

// Outputs Volvo

Change an Array Element

To change the value of a specific element, refer to the index number:

Example

cars[0] = "Opel";

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

cars[0] = "Opel";

System.out.println(cars[0]);
20

// Now outputs Opel instead of Volvo


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Array Length

To find out how many elements an array has, use the length property:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

System.out.println(cars.length);

// Outputs 4

Loop Through an Array

You can loop through the array elements with the for loop, and use the length property to specify how
many times the loop should run.

The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

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

System.out.println(cars[i]);

Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

Syntax

for (type variable : arrayname) {

...

The following example outputs all elements in the cars array, using a "for-each" loop:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


21

for (String i : cars) {


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

System.out.println(i);

MULTIDIMENSIONAL ARRAYS

A multidimensional array is an array containing one or more arrays. To create a two-dimensional


array, add each array within its own set of curly braces:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.To access the elements of
the myNumbers array, specify two indexes: one for the array, and one for the element inside that
array. This example accesses the third element (2) in the second array (1) of myNumbers:

Example

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

int x = myNumbers[1][2];

System.out.println(x); // Outputs 7

We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we
still have to point to the two indexes):

Example

public class MyClass {

public static void main(String[] args) {

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

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

for(int j = 0; j < myNumbers[i].length; ++j) {

System.out.println(myNumbers[i][j]);

}
}

}
22
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

JAVA METHODS

A method is a block of code which only runs when it is called.You can pass data, known as
parameters, into a method.Methods are used to perform certain actions, and they are also known
as functions..

Create a Method

A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:

Example

Create a method inside MyClass:

public class MyClass {

void myMethod() {

// code to be executed

Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the MyClass class and not an object of the MyClass
class. You will learn more about objects and how to access methods through objects later in
this unit.
 void means that this method does not have a return value. You will learn more about return
values later in this chapter

Call a Method

To call a method in Java, write the method's name followed by two parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it is called:

Example

Inside main, call the myMethod() method:


23

public class MyClass {


void myMethod() {
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

System.out.println("I just got executed!");


}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class MyClass {

void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Java Method Parameters

Information can be passed to methods as parameter. Parameters act as variables inside the
method.Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as parameter. When the method
is called, we pass along a first name, which is used inside the method to print the full name:

Example

public class MyClass {


24

void myMethod(String fname) {


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

myMethod("Liam");

myMethod("Jenny");

myMethod("Anja");

// Liam Refsnes

// Jenny Refsnes

// Anja Refsnes

Return Values

The void keyword, used in the examples above, indicates that the method should not return a value. If
you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead
of void, and use the return keyword inside the method:

Example

public class MyClass {

int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

// Outputs 8 (5 + 3)
25
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

JAVA CLASSES AND OBJECTS

Java is an object-oriented programming language.Everything in Java is associated with classes and


objects, along with its attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

MyClass.java

Create a class named "MyClass" with a variable x:

public class MyClass {


int x = 5;
}
Create an Object

In Java, an object is created from a class. We have already created the class named MyClass, so now
we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object name, and use the
keyword new:

Example

Create an object called "myObj" and print the value of x:

public class MyClass {

int x = 5;

public static void main(String[] args) {

MyClass myObj = new MyClass();

System.out.println(myObj.x);

JAVA CONSTRUCTORS

A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:
26
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Example

Create a constructor:

// Create a MyClass class

public class MyClass {

int x; // Create a class attribute

// Create a class constructor for the MyClass class

MyClass() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the
constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5

METHOD OVERLOADING/ POLYMORPHISM

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters
then it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading


27

Method overloading increases the readability of the program.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
CONSTRUCTOR OVERLOADING IN JAVA
Like methods, constructors can also be overloaded. In this guide we will see Constructor overloading
with the help of examples. Before we proceed further let’s understand what is constructor overloading
and why we do it.Constructor overloading is a concept of having more than one constructor with
different parameters list, in such a way so that each constructor performs a different task. For
e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and
capacity increment then you can simply use default constructor of Vector class like this Vector v =
new Vector(); however if you need to specify the capacity and increment then you call the
parameterized constructor of Vector class with two int arguments like this: Vector v= new Vector(10,
5);
28
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Constructor Overloading Example

Here we are creating two objects of class StudentData. One is with default constructor and another
one using parameterized constructor. Both the constructors have different initialization code, similarly
you can create any number of constructors with different-2 initialization codes for different-2
purposes.
StudentData.java

class StudentData
{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
29

public void setStuAge(int stuAge) {


this.stuAge = stuAge;
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

public static void main(String args[])


{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
System.out.println("Student Name is: "+myobj.getStuName());
System.out.println("Student Age is: "+myobj.getStuAge());
System.out.println("Student ID is: "+myobj.getStuID());

/*This object creation would call the parameterized


* constructor StudentData(int, String, int)*/
StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
System.out.println("Student Name is: "+myobj2.getStuName());
System.out.println("Student Age is: "+myobj2.getStuAge());
System.out.println("Student ID is: "+myobj2.getStuID());
}
}
Output:

Student Name is: New Student


Student Age is: 18
Student ID is: 100
Student Name is: Chaitanya
Student Age is: 25
Student ID is: 555

JAVA STATIC KEYWORD


The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.
30
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each
time when the object is created. All students have its unique rollno and name, so instance data member
is good in such case. Here, "college" refers to the common property of all objects. If we make it static,
this field will get the memory only once.

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
31

}
}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

2) Java static method


If you apply static keyword with any method, it is known as static method.

1. A static method belongs to the class rather than the object of a class.
2. A static method can be invoked without the need for creating an instance of a class.
3. A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.

class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}

3) Java static block


1. Is used to initialize the static data member.
32

2. It is executed before the main method at the time of classloading.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Example of static block


class A2{
static
{System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}

THIS KEYWORD IN JAVA

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

FINAL KEYWORD IN JAVA

The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will have
detailed learning of these. Let's first learn the basics of final keyword.
33
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

3) Java final class


34

If you make any class as final, you cannot extend it.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Example of final class


final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error

METHOD OVERRIDING IN JAVA

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
35

//Creating a child class


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

class Bike extends Vehicle{


public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}

Output: Vehicle is running

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the same, and there is
IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output: Bike is running safely


36
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD OVERRIDING IN


JAVA
There are many differences between method overloading and method overriding in java. A list of
differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to


readability of the program. provide the specific
implementation of the method that is
already provided by its super class.

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must In case of method


be different. overriding, parameter must be same.

4) Method overloading is the example of compile Method overriding is the example


time polymorphism. of run time polymorphism.

5) In java, method overloading can't be performed Return type must be same or


by changing return type of the method covariant in method overriding.
only. Return type can be same or different in
method overloading. But you must have to
change the parameter.

JAVA INNER CLASSES

Java inner class or nested class is a class which is declared inside the class or interface.We use inner
classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.Additionally, it can access all the members of outer class including private data members
and methods.

Syntax of Inner class


class Java_Outer_class{
37

//code
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

class Java_Inner_class{
//code
}
}
Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

JAVA INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
38
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class
is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that Programmer
is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.

TYPES OF INHERITANCE IN JAVA

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.
39
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
40

}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking...
eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.

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

Output:
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

weeping...
barking...
eating...

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

File: 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...

Q) Why multiple inheritance is not supported in java?

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

java.Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

A and B classes have the same method and you call it from child class object, there will be ambiguity
to call the method of A or B class.Since compile-time errors are better than runtime errors, Java renders
compile-time error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.

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 static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

SUPER KEYWORD IN JAVA

The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

Usage of Java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

ABSTRACT CLASS IN JAVA

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).Before learning the Java abstract class, let's
understand the abstraction in Java first.

ABSTRACTION IN JAVA

Abstraction is a process of hiding the implementation details and showing only functionality to the
43

user.Another way, it shows only essential things to the user and hides the internal details, for example,
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

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

1. abstract class Bike{


2. abstract void run();
3. }
44

4. class Honda4 extends Bike{


5. void run(){System.out.println("running safely");}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

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


7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
INTERFACE IN JAVA

An interface in Java is a blueprint of a class. It has static constants and abstract methods.The interface
in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.

 Java Interface also represents the IS-A relationship.


 It cannot be instantiated just like the abstract class.
 Since Java 8, we can have default and static methods in an interface.
 Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the abstract
45

methods. Abstract class and interface both can't be instantiated.


Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods. Since
non-abstract methods. Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".

8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}

JAVA PACKAGES /IMPORT STATEMENT

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into
two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own packages)

Built-in Packages
46
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING

The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.

The library is divided into packages and classes. Meaning you can either import a single class (along
with its methods and attributes), or a whole package that contain all the classes that belong to the
specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax

import package.name.Class;

Example

import java.util.Scanner;

User-defined Packages

package mypack;

*********************************
47
Page

You might also like