You are on page 1of 267

BUNTS SANGHA’S

S.M.SHETTY COLLEGE OF SCIENCE, COMMERCE AND


MANAGEMENT STUDIES, POWAI
NAAC ACCREDITED ‘A’ GRADE
ISO 9001:2015 CERTIFIED
IMC RBNQ CERTIFICATE OF MERIT 2019

“Healthy citizens are the greatest asset any country can have.”
― Winston S. Churchill

WELCOME YOU ALL IN


SYBSCIT
ACADEMIC YEAR 2020-21









































1)
2)







• −

• −

• −

• −
































Abstract class Interface
class AddTwoNumbers {

public static void main(String[] args) {

int num1 = 5, num2 = 15, sum;


sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
import java.util.Scanner;
public class AddTwoNumbers2 {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
} }
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140



public class CreateObjectExample1
{
void show()
{
System.out.println("Welcome");
}
public static void main(String[] args)
{
CreateObjectExample1 obj = new
CreateObjectExample1();
obj.show();
} }







Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Unit I
Chapter 1: Introduction

Contents:

 History
 Architecture and its Components,
 Java Class File,
 Java Runtime Environment,
 Java Virtual Machine,
 JVM Components,
 The Java API,
 Java Platform,
 Java Development Kit,
 Lambda Expressions,
 Methods References,
 Type Annotations,
 Method Parameter Reflection,
 Setting the Path Environment Variable,
 Java Compiler And Interpreter,
 Java Applications,
 main(), public, static, void, string[] args, Statements,
 White Space,
 Case Sensitivity,
 Identifiers,
 Keywords,
 Comments, braces and code blocks, variables, variable name

1. History

 Java history is interesting to know. The history of java starts from Green
Team. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.
 For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
 Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describe the
history of java.

1
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

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. Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.

Why "Oak" name?

Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why "Java" name?

 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.
 Java is an island of Indonesia where first coffee was produced (called java
coffee).
 Notice that Java is just a name not an acronym.
 Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
 In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 JDK 1.0 released in (January 23, 1996).

1.1 Difference between Java and C++

Java C++

Java is pure object oriented programming C++ is semi object oriented language b'coz we
language. We can't design and develop our can design and develop our programs and
programs and applications without object. applications, with and without object.

Java is Dynamic, Java allocates memory at C++ is static, C++ allocates memory at
run-time. compile-time.

Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.

2
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Java doesn't support multiple inheritance. C++ does support multiple inheritance.
Java uses interface for multiple inheritance.

Java supports automatic garbage collection. C++ does support destructors, which is
Java does not support destructors as C++ automatically invoked when the object goes
does. out of scope.

Java does not support default argument C++ does support default argument value.
value.

Java has built in support for threads. C++ has no built in support for threads.
Instead, c++ relies entirely upon the operating
system to provide this threads.

Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.

1.2 Java Version History

There are many java versions that has been released. Current stable release of Java is
Java SE 8.

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 March, 2014)

1.3 Features of Java

There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust

3
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Simple

According to Sun, Java language is simple because:


 Syntax is based on C++ (so easier for programmers to learn it after C++).
 Removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.

Object-oriented
 Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
 Object-oriented programming (OOPs) is a methodology that simplify software
development and maintenance by providing some rules.

Platform Independent

 A platform is the hardware or software environment in which a program runs.


 There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
 The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based
platforms. It has two components:

4
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1. Runtime Environment
2. API(Application Programming Interface)

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

Secured

Java is secured because:

o No explicit pointer
o Java Programs run inside virtual machine sandbox

Robust

Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.

Architecture-neutral

There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.

Portable

We may carry the java byte code to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

5
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications etc.

1.4 Difference between JDK, JRE and JVM

JRE

JRE is an acronym for Java Runtime Environment.


It is used to provide runtime environment. It is the
implementation of JVM. It physically exists. It
contains set of libraries + other files that JVM uses
at runtime. Implementation of JVMs is also actively
released by other companies besides Sun Micro
Systems.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.

6
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

2. JVM (Java Virtual Machine)

 JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.
 JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

2.1 Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains class loader, memory
area, execution engine etc.

7
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack
 Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.
 A new frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.

8
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine
It contains:

1) A virtual processor

2) Interpreter: Read bytecode stream then execute the instructions.

3) Just-In-Time (JIT) compiler: It is used to improve the performance. JIT compiles


parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here the term compiler refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction set
of a specific CPU.

3. Java Architecture and its Components

A Java Runtime Environment performs the following main tasks respectively.

1. Loads the class: This is done by the class loader


2. Verifies the bytecode: This is done by bytecode verifier.
3. Interprets the bytecode: This is done by the JVM

These tasks are described in detail in the subsequent sessions. A detailed Java
architecture can be drawn as given below.

Figure: Java Architecture in Detail


9
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Class loader

 Class loader loads all the class files required to execute the program. Class
loader makes the program secure by separating the namespace for the classes
obtained through the network from the classes available locally. Once the
bytecode is loaded successfully, then next step is bytecode verification by
bytecode verifier.

Byte code verifier

 The bytecode verifier verifies the byte code to see if any security problems are
there in the code.
 Once this code is verified and proven that there is no security issues with the
code, JVM will convert the byte code into machine code which will be directly
executed by the machine in which the Java program runs.

Just in Time Compiler

 This is a component which helps the program execution to happen faster.


 But this interpretation is a slower process. To overcome this difficulty, JRE
include the component JIT compiler. JIT makes the execution faster.
 Hence the main performance improvement by using JIT compiler can be seen
when the same code is executed again and again because JIT make use of the
machine code which is cached and stored.

Garbage Collection

 Garbage collection is a process by which Java achieves better memory


management. As you know, in object oriented programming, objects
communicate to each other by passing messages.
 Whenever an object is created, there will be some memory allocated for this
object. This memory will remain as allocated until there are some references to
this object. When there is no reference to this object, Java will assume that this
object is not used anymore. When garbage collection process happens, these
objects will be destroyed and memory will be reclaimed.

3.1 What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.

10
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

3.2 What happens at runtime?

At runtime, following steps are performed:

Q. Can you save a java source file by other name than the class name?

Yes, if the class is not public. It is explained in the figure given below:

To compile: javac Hard.java


To execute: java Simple

Q. Can you have multiple classes in a java source file?

Yes, like the figure given below illustrates:

11
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

4. How to set path in Java

The path is required to be set for using tools such as javac, java etc.

If you are saving the java source file inside the jdk/bin directory, path is not required
to be set because all the tools will be available in the current directory. But If you are
having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

1. temporary
2. permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

Open command prompt


copy the path of jdk/bin directory
write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.8 \bin

Let's see it in the figure given below:

12
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

2) How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:

o Go to MyComputer -> Right Click on Properties -> Go to Advanced System


Settings -> Go to Environment Variables -> Select New Option from user
variable -> write variable name -> write path of bin folder in variable value

Copy the path c://program files//java//jdk 1.8//bin and paste in variable value.

Difference between path and classpath in Java

Path Classpath
path variable is set for providing path for all classpath variable is set for provide
java tools like java, javac, javap, javah, jar, path of all java classes which is used in
appletviewer our application.

13
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

4.1 JDK Folder Hierarchy

Path variable is set for use all the tools like java, javac, javap, javah, jar,
appletviewer etc.

Example

"C:\Program Files\Java\jdk1.6.0\bin"

All the tools are present in bin folder so we set path upto bin folder.

Example: "C:\Program Files\Java\jre1.6.0\jre\lib\rt.jar"

In above rt.jar is a jar file where all the .class


files are present so we set the classpath upto
rt.jar.

14
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

5. Java API

Java Development Kit (JDK) is comprised of three basic components, as follows:

 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)

The Java API, included with the JDK, describes the function of each of its
components. In Java programming, many of these components are pre-created and
commonly used. Thus, the programmer is able to apply prewritten code via the Java
API. After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.
The API is a library of available Java classes, packages and interfaces. The three API
types are as follows:

 Official Java core API, which is bundled with the JDK download
 Optional official Java APIs, which may be downloaded if needed
 Unofficial APIs, which are third-party APIs that may be downloaded from
source websites

The APIs help programmers determine class or package functions, parameters and
other necessary information. The official API includes packages, e.g., applet
packages, graphics and GUI swing packages, input/output (IO) packages and Abstract
Windows Toolkit (AWT), among others.
There are three frames when an API starts, as follows:

 The first frame shows all API components (classes and packages).
 When a particular package is selected, the second frame shows all interfaces,
classes and exceptions of that particular package.
 The third and primary frame provides an overview of all of API packages,
which can be expanded in the main frame to show the index, class hierarchy
and help sections.

6. Java Platform

 Java is a set of computer software and specifications developed by Sun


Microsystems, which was later acquired by the Oracle Corporation, that
provides a system for developing application software and deploying it in
a cross-platform computing environment. Java is used in a wide variety
of computing platforms from embedded devices and mobile
phones to enterprise servers and supercomputers.
 Java applets, which are less common than standalone Java applications, run in
secure, sandboxed environments to provide many features of native
applications and can be embedded in HTML pages.

15
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

 Writing in the Java programming language is the primary way to produce code
that will be deployed as byte code in a Java virtual machine (JVM); byte
code compilers are also available for other languages,
including Ada, JavaScript, Python, and Ruby.
 Java eschews certain low-level constructs such as pointers and has a very
simple memory model where every object is allocated on the heap and all
variables of object types are references. Memory management is handled
through integrated automatic garbage collection performed by the JVM.
 The Java platform is a suite of programs that facilitate developing and running
programs written in the Java programming language. A Java platform will
include an execution engine (called a virtual machine), a compiler and a set
of libraries; there may also be additional servers and alternative libraries that
depend on the requirements. Java is not specific to any processor or operating
system as Java platforms have been implemented for a wide variety of
hardware and operating systems with a view to enable Java programs to run
identically on all of them. Different platforms target different classes of device
and application domains:

 Java Card: A technology that allows small Java-based applications (applets) to be


run securely on smart cards and similar small-memory devices.
 Java ME (Micro Edition): Specifies several different sets of libraries (known as
profiles) for devices with limited storage, display, and power capacities. It is often
used to develop applications for mobile devices, PDAs, TV set-top boxes, and
printers.
 Java SE (Standard Edition): For general-purpose use on desktop PCs, servers
and similar devices.
 Java EE (Enterprise Edition): Java SE plus various APIs which are useful
for multi-tier client–server enterprise applications.
 The Java platform consists of several programs, each of which provides a
portion of its overall capabilities. For example, the Java compiler, which
converts Java source code into Java bytecode (an intermediate language for the
JVM), is provided as part of the Java Development Kit (JDK). The Java
Runtime Environment(JRE), complementing the JVM with a just-in-time (JIT)
compiler, converts intermediate bytecode into native machine code on the fly.
The Java platform also includes an extensive set of libraries.
 The essential components in the platform are the Java language compiler, the
libraries, and the runtime environment in which Java intermediate bytecode
executes according to the rules laid out in the virtual machine specification.
 In most modern operating systems (OSs), a large body of reusable code is
provided to simplify the programmer's job. This code is typically provided as a
set of dynamically loadable libraries that applications can call at runtime.
Because the Java platform is not dependent on any specific operating system,
applications cannot rely on any of the pre-existing OS libraries. Instead, the
Java platform provides a comprehensive set of its own standard class libraries

16
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

containing many of the same reusable functions commonly found in modern


operating systems. Most of the system library is also written in Java.

7. Java Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that


communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.

7.1 First Java Program


Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram
{
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.

17
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

7.2 Basic Syntax (Rules)


About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the
class name.
When saving the file, you should save it using the class name (Remember Java
is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file
should be saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from
the main() method which is a mandatory part of every Java program.
 interface name-- should start with uppercase letter
 variable name-- should start with lowercase letter e.g. firstName,
orderNumber etc.
 package name -- should be in lowercase letter e.g. java, lang, sql, util etc.

8. Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers. In Java, there are several points to remember about identifiers.
They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.

18
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

9. Lambda Expressions

Lambda expression is a new and important feature of Java which was included in Java
SE 8. It provides a clear and concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection. Before lambda expression, anonymous inner class was the only
option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java
lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.


2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.

Let's see a scenario. If we don't implement Java lambda expression. Here, we are
implementing an interface method without using lambda expression.

Java Example without Lambda Expression

interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
Drawable d=new Drawable()
{
public void draw()
{
System.out.println("Drawing "+width);
} };
d.draw();
} }

19
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Output:

Drawing 10

Java Example with Lambda Expression

Now, we are implementing the above example with the help of lambda expression.

interface Drawable
{
public void draw();
}
public class LambdaExpressionExample
{
public static void main(String[] args)
{
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}

Output:

Drawing 10

10. Java Method References

Java provides a new feature called method reference in Java 8. Method reference is
used to refer method of functional interface. It is compact and easy form of lambda
expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. Here, we are
explaining method reference concept in detail.

Types of Method References

There are four types of method references:

1. Reference to a static method.


2. Reference to an instance method of a particular object.
3. Reference to a constructor.

20
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1) Reference to a Static Method

You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.

Syntax : ContainingClass::staticMethodName

Example 1

In the following example, we have defined a functional interface and referring a static
method to it's functional method say().

interface Sayable
{
void say();
}
public class MethodReference
{
public static void saySomething()
{
System.out.println("Hello, this is static method.");
}
public static void main(String[] args)
{
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}

Output:

Hello, this is static method.

2) Reference to an Instance Method

Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.

Syntax

containingObject::instanceMethodName

21
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example 1

In the following example, we are referring non-static methods. You can refer methods
by class object and anonymous object.

interface Sayable
{
void say();
}
public class MethodReference
{
public void saySomething()
{
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args)
{
MethodReference methodReference = new MethodReference(); // Creating object
Sayable sayable = methodReference::saySomething;
sayable.say(); // Calling interface method
Sayable sayable2 = new MethodReference()::saySomething;
sayable2.say(); // Calling interface method
}
}

Output:

Hello, this is non-static method.


Hello, this is non-static method.

3) Reference to a Constructor

You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.

Syntax: ClassName::new

Example

interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
22
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

System.out.print(msg);
}
}
public class ConstructorReference
{
public static void main(String[] args)
{
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}

Output:

Hello

11. Java Type Annotations

Java 8 has included two new features repeating and type annotations in its prior
annotations topic. In early Java versions, you can apply annotations only to
declarations. After releasing of Java SE 8 , annotations can be applied to any type use.
It means that annotations can be used anywhere you use a type. For example, if you
want to avoid NullPointerException in your code, you can declare a string variable
like this:

1. @NonNull String str;

Following are the examples of type annotations:

2. @NonNull List<String>
3. List<@NonNull String> str
4. Arrays<@NonNegative Integer> sort
5. @Encrypted File file
6. @Open Connection connection
7. void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException

12. Java Compiler and Interpreter

Difference between Compiler and Interpreter

No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as
input.
2 Intermediate Object Code is Generated No Intermediate Object Code
is Generated

23
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

3 Conditional Control Statements are Conditional Control Statements are


Executes faster Executes slower
4 Memory Requirement : More(Since Memory Requirement is Less
Object Code is Generated)
5 Program need not be compiled every Every time higher level program is
time converted into lower level program
6 Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
7 Example : C Compiler Example : BASIC

Explanation: Compiler Vs Interpreter


Just understand the concept of the compiler and interpreter –
1. We give complete program as input to the compiler. Our program is in the
human readable format.
2. Human readable format undergoes many passes and phases of compiler and
finally it is converted into the machine readable format.
3. However interpreter takes single line of code as input at a time and execute that
line. It will terminate the execution of the code as soon as it finds the error.
4. Memory requirement is less in Case of interpreter because no object code is
created in case of interpreter

13. Java Applications

1. Desktop GUI Applications:

Java provides GUI development through various means like Abstract Windowing
Toolkit (AWT), Swing and JavaFX. While AWT contains a number of pre-
constructed components such as menu, button, list, and numerous third-party
components, Swing, a GUI widget toolkit, additionally provides certain advanced
components like trees, tables, scroll panes, tabbed panel and lists. JavaFX, a set of
graphics and media packages, provides Swing interoperability, 3D graphic features
and self-contained deployment model which facilitates quick scripting of Java applets
and applications.

2. Mobile Applications:
Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to
build applications that run across all Java supported devices, including feature phones
and smart phones. Further, applications for Android, one of the most popular mobile
operating systems, are usually scripted in Java using the Android Software
Development Kit (SDK) or other environments.

3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components
of larger electromechanical systems performing dedicated tasks. Several devices, such

24
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

as SIM cards, blue-ray disk players, utility meters and televisions, use embedded Java
technologies. According to Oracle, 100% of Blu-ray Disc Players and 125 million
TV devices employ Java.

4. Web Applications:

Java provides support for web applications through Servlets, Struts or JSPs. The easy
programming and higher security offered by the programming language has allowed a
large number of government applications for health, social security, education and
insurance to be based on Java. Java also finds application in development of
eCommerce web applications using open-source eCommerce platforms, such as
Broadleaf.

5. Web Servers and Application Servers:


The Java ecosystem today contains multiple Java web servers and application
servers. While Apache Tomcat, Simple, Jo!, Rimfaxe Web Server (RWS) and Project
Jigsaw dominate the web server space, WebLogic, WebSphere, and Jboss EAP
dominate commercial application server space.

6. Enterprise Applications:

Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime
environment for scripting and running enterprise software, including network
applications and web-services. Oracle claims Java is running in 97% of enterprise
computers. The higher performance guarantee and faster computing in Java has
resulted in high frequency trading systems like Murex to be scripted in the language.
It is also the backbone for a variety of banking applications which have Java running
from front user end to back server end.

7. Scientific Applications:

Java is the choice of many software developers for writing applications involving
scientific calculations and mathematical operations. These programs are generally
considered to be fast and secure, have a higher degree of portability and low
maintenance. Applications like MATLAB use Java both for interacting user interface
and as part of the core system.

14. Java Statements

Statements are similar to sentences in the English language. A sentence forms a


complete idea which can include one or more clauses. Likewise, a statement in Java
forms a complete command to be executed and can include one or more expressions.

In simpler terms, a Java statement is just an instruction that explains what should
happen.

25
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Types of Java Statements

There are three main groups that encompass the different kinds of statements in Java:

 Expression statements change values of variables, call methods, and create


objects.
 Declaration statements declare variables.
 Control flow statements determine the order that statements are executed.
Typically, they're understood from top to bottom. However, with control flow
statements, that order can be interrupted to implement branching or looping so
that the Java program can run particular sections of code based on certain
conditions.

Examples of java statements

//declaration statement
int number;

//expression statement
number = 4;

//control flow statement


if (number < 10 )
{
//expression statement
System.out.println(number + " is less than ten");
}

15. Java Main Method

 public static void main(String args[]) is the main method in Java. Main method
is called by JVM. Main method is called before any object creation so A
method which can called by class name it must be static so it can be called. but
here main must be public because it is accessed by outer of default
environment (call by JVM ).
 When we are run java program by command =>java MY_Class
This command JVM interpret as this class must have a public static main
method. JVM search until it will not found main and if signature of main not
found then throws exception.

26
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

16. White Space in Java

The method determines whether the specified char value is a white space, which
includes space, tab, or new line.
Syntax: boolean isWhitespace(char ch)
Parameters
Here is the detail of parameters −
 ch − Primitive character type.
Return Value

 This method returns true, if the passed character is really a white space.
Example

public class Test


{
public static void main(String args[])
{
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));
}
}
This will produce the following result −
Output
false
true
true
true

17. Keywords

Keywords have special meaning to the Java compiler. They help in identifying a data
type name or program construct name.

abstract Continue for new switch


assert default goto package synchronized
boolean Do if private this
break double implements protected throw
byte Else import public throws
case Enum instanceof return transient

27
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

catch extends int short Try


char Final interface static void
class finally long strictfp volatile
Const Float native super while

18. Java Comments

The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code
for specific time.

Types of Java Comments

There are 2 types of comments in java.

1. Single Line Comment


2. Multi Line Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

// : This is single line comment

Example:

public class CommentExample1 {


public static void main(String[] args) {
int i=10; //Here, i is a variable
System.out.println(i);
}
}

Output:

10

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax: /* This is multi line comment */


28
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example:

public class CommentExample2 {


public static void main(String[] args)
{
/* Let's declare and print variable in java. */
int i=10;
System.out.println(i);
}
}

Output:

10

19. Braces in Java

One: Opening Curly Braces on the Same Line:

The biggest advantage to having the opening curly brace on the same line is to save
vertical space. Vertical density is an important topic when talking about easy-to-read
code, so this is definitely something that we should consider. By having the curly
brace on the same line, we reduce the (already short) code sample above by 3
lines. This means that we have more space on the screen to see additional code.

Two: Opening Curly Braces on a Separate Line

The biggest advantage to having the opening curly brace on a separate line is that the
curly braces will always line up visually (assuming that we are also using good
horizontal spacing in our code). This makes it easy to visually spot the beginning of
the code block -- we just need to find the end brace and then scan up until we see an
opening brace in the same column.

20. Variables in Java

 A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
 Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
 Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its
value can be changed.

29
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example:

int data=50; //Here data is variable


int a, b, c; // Declares three int, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

Types of Variable

There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variables:
 A variable which is declared inside the method is called local variable.
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or
block.
 There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.

2) Instance Variable
 A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.

30
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

 Instance variables can be declared in class level before or after use.


 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access
level). However, visibility for subclasses can be given for these variables with
the use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.

3) Static variable
 A variable that is declared as static is called static variable. It cannot be local.
 Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Example to understand the types of variables in java

class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class

31
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Questions

1. Explain the history of Java in short. Why "Java" name was given to the
language?
2. Difference between Java and C++?
3. Explain the features of Java.
4. Difference between JDK, JRE and JVM.
5. Explain Java Virtual Machine with diagram.
6. Explain Internal Architecture of JVM.
7. Explain Java Architecture and its Components.
8. Explain compilation and running of java program. How to set path in Java?
9. Write a short note on Java API.
10. Explain the various Java Platform.
11. Explain the basic syntax and rules for Java with an example.
12. What is Java Identifiers? Explain Lambda Expressions with an example.
13. Explain Java Method References with its types.
14. What is Java Type Annotations?
15. Differentiate between Compiler and Interpreter.
16. What are the applications of Java?
17. Explain Java Statements with an example.
18. Explain the syntax of Java main().
19. Explain white spaces in Java. List various reserved keywords.
20. Define Comments. Explain the types of comments.
21. Define variables. What are the types of variables?

32
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Unit I
Chapter 1: Introduction

Contents:

 History
 Architecture and its Components,
 Java Class File,
 Java Runtime Environment,
 Java Virtual Machine,
 JVM Components,
 The Java API,
 Java Platform,
 Java Development Kit,
 Lambda Expressions,
 Methods References,
 Type Annotations,
 Method Parameter Reflection,
 Setting the Path Environment Variable,
 Java Compiler And Interpreter,
 Java Applications,
 main(), public, static, void, string[] args, Statements,
 White Space,
 Case Sensitivity,
 Identifiers,
 Keywords,
 Comments, braces and code blocks, variables, variable name

1. History

 Java history is interesting to know. The history of java starts from Green
Team. Java team members (also known as Green Team), initiated a
revolutionary task to develop a language for digital devices such as set-top
boxes, televisions etc.
 For the green team members, it was an advance concept at that time. But, it was
suited for internet programming. Later, Java technology as incorporated by
Netscape.
 Currently, Java is used in internet programming, mobile devices, games, e-
business solutions etc. There are given the major points that describe the
history of java.

1
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

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. Originally designed for small, embedded systems in electronic appliances like
set-top boxes.
3. Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4. After that, it was called Oak and was developed as a part of the Green project.

Why "Oak" name?

Oak is a symbol of strength and chosen as a national tree of many countries like
U.S.A., France, Germany, Romania etc.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why "Java" name?

 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.
 Java is an island of Indonesia where first coffee was produced (called java
coffee).
 Notice that Java is just a name not an acronym.
 Originally developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
 In 1995, Time magazine called Java one of the Ten Best Products of 1995.
 JDK 1.0 released in (January 23, 1996).

1.1 Difference between Java and C++

Java C++

Java is pure object oriented programming C++ is semi object oriented language b'coz we
language. We can't design and develop our can design and develop our programs and
programs and applications without object. applications, with and without object.

Java is Dynamic, Java allocates memory at C++ is static, C++ allocates memory at
run-time. compile-time.

Java doesn't support pointers, goto statement, C++ does support pointers, goto statement,
operator overloading, templates, etc. operator overloading, templates.

2
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Java doesn't support multiple inheritance. C++ does support multiple inheritance.
Java uses interface for multiple inheritance.

Java supports automatic garbage collection. C++ does support destructors, which is
Java does not support destructors as C++ automatically invoked when the object goes
does. out of scope.

Java does not support default argument C++ does support default argument value.
value.

Java has built in support for threads. C++ has no built in support for threads.
Instead, c++ relies entirely upon the operating
system to provide this threads.

Java compiler converts source code into byte C++ generates object code and the same code
code, which is platform independent. may not run on different platforms.

1.2 Java Version History

There are many java versions that has been released. Current stable release of Java is
Java SE 8.

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 March, 2014)

1.3 Features of Java

There is given many features of java. They are also known as java buzzwords. The
Java Features given below are simple and easy to understand.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust

3
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Simple

According to Sun, Java language is simple because:


 Syntax is based on C++ (so easier for programmers to learn it after C++).
 Removed many confusing and/or rarely-used features e.g., explicit pointers,
operator overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.

Object-oriented
 Object-oriented means we organize our software as a combination of different
types of objects that incorporates both data and behaviour.
 Object-oriented programming (OOPs) is a methodology that simplify software
development and maintenance by providing some rules.

Platform Independent

 A platform is the hardware or software environment in which a program runs.


 There are two types of platforms software-based and hardware-based. Java
provides software-based platform.
 The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based
platforms. It has two components:

4
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1. Runtime Environment
2. API(Application Programming Interface)

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

Secured

Java is secured because:

o No explicit pointer
o Java Programs run inside virtual machine sandbox

Robust

Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.

Architecture-neutral

There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.

Portable

We may carry the java byte code to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

5
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any
machine on the internet.

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications etc.

1.4 Difference between JDK, JRE and JVM

JRE

JRE is an acronym for Java Runtime Environment.


It is used to provide runtime environment. It is the
implementation of JVM. It physically exists. It
contains set of libraries + other files that JVM uses
at runtime. Implementation of JVMs is also actively
released by other companies besides Sun Micro
Systems.

JDK

JDK is an acronym for Java Development Kit. It physically exists. It contains JRE +
development tools.

6
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

2. JVM (Java Virtual Machine)

 JVM (Java Virtual Machine) is an abstract machine. It is a specification that


provides runtime environment in which java bytecode can be executed.
 JVMs are available for many hardware and software platforms (i.e. JVM is
platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its
implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command
prompt to run the java class, an instance of JVM is created.

What it does

The JVM performs following operation:

 Loads code
 Verifies code
 Executes code
 Provides runtime environment

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

2.1 Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains class loader, memory
area, execution engine etc.

7
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack
 Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
 Each thread has a private JVM stack, created at the same time as thread.
 A new frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.

5) Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine
instruction currently being executed.

8
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine
It contains:

1) A virtual processor

2) Interpreter: Read bytecode stream then execute the instructions.

3) Just-In-Time (JIT) compiler: It is used to improve the performance. JIT compiles


parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here the term compiler refers to a
translator from the instruction set of a Java virtual machine (JVM) to the instruction set
of a specific CPU.

3. Java Architecture and its Components

A Java Runtime Environment performs the following main tasks respectively.

1. Loads the class: This is done by the class loader


2. Verifies the bytecode: This is done by bytecode verifier.
3. Interprets the bytecode: This is done by the JVM

These tasks are described in detail in the subsequent sessions. A detailed Java
architecture can be drawn as given below.

Figure: Java Architecture in Detail


9
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Class loader

 Class loader loads all the class files required to execute the program. Class
loader makes the program secure by separating the namespace for the classes
obtained through the network from the classes available locally. Once the
bytecode is loaded successfully, then next step is bytecode verification by
bytecode verifier.

Byte code verifier

 The bytecode verifier verifies the byte code to see if any security problems are
there in the code.
 Once this code is verified and proven that there is no security issues with the
code, JVM will convert the byte code into machine code which will be directly
executed by the machine in which the Java program runs.

Just in Time Compiler

 This is a component which helps the program execution to happen faster.


 But this interpretation is a slower process. To overcome this difficulty, JRE
include the component JIT compiler. JIT makes the execution faster.
 Hence the main performance improvement by using JIT compiler can be seen
when the same code is executed again and again because JIT make use of the
machine code which is cached and stored.

Garbage Collection

 Garbage collection is a process by which Java achieves better memory


management. As you know, in object oriented programming, objects
communicate to each other by passing messages.
 Whenever an object is created, there will be some memory allocated for this
object. This memory will remain as allocated until there are some references to
this object. When there is no reference to this object, Java will assume that this
object is not used anymore. When garbage collection process happens, these
objects will be destroyed and memory will be reclaimed.

3.1 What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS)
and converts the java code into bytecode.

10
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

3.2 What happens at runtime?

At runtime, following steps are performed:

Q. Can you save a java source file by other name than the class name?

Yes, if the class is not public. It is explained in the figure given below:

To compile: javac Hard.java


To execute: java Simple

Q. Can you have multiple classes in a java source file?

Yes, like the figure given below illustrates:

11
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

4. How to set path in Java

The path is required to be set for using tools such as javac, java etc.

If you are saving the java source file inside the jdk/bin directory, path is not required
to be set because all the tools will be available in the current directory. But If you are
having your java file outside the jdk/bin folder, it is necessary to set path of JDK.

There are 2 ways to set java path:

1. temporary
2. permanent

1) How to set Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow following steps:

Open command prompt


copy the path of jdk/bin directory
write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.8 \bin

Let's see it in the figure given below:

12
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

2) How to set Permanent Path of JDK in Windows

For setting the permanent path of JDK, you need to follow these steps:

o Go to MyComputer -> Right Click on Properties -> Go to Advanced System


Settings -> Go to Environment Variables -> Select New Option from user
variable -> write variable name -> write path of bin folder in variable value

Copy the path c://program files//java//jdk 1.8//bin and paste in variable value.

Difference between path and classpath in Java

Path Classpath
path variable is set for providing path for all classpath variable is set for provide
java tools like java, javac, javap, javah, jar, path of all java classes which is used in
appletviewer our application.

13
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

4.1 JDK Folder Hierarchy

Path variable is set for use all the tools like java, javac, javap, javah, jar,
appletviewer etc.

Example

"C:\Program Files\Java\jdk1.6.0\bin"

All the tools are present in bin folder so we set path upto bin folder.

Example: "C:\Program Files\Java\jre1.6.0\jre\lib\rt.jar"

In above rt.jar is a jar file where all the .class


files are present so we set the classpath upto
rt.jar.

14
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

5. Java API

Java Development Kit (JDK) is comprised of three basic components, as follows:

 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)

The Java API, included with the JDK, describes the function of each of its
components. In Java programming, many of these components are pre-created and
commonly used. Thus, the programmer is able to apply prewritten code via the Java
API. After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.
The API is a library of available Java classes, packages and interfaces. The three API
types are as follows:

 Official Java core API, which is bundled with the JDK download
 Optional official Java APIs, which may be downloaded if needed
 Unofficial APIs, which are third-party APIs that may be downloaded from
source websites

The APIs help programmers determine class or package functions, parameters and
other necessary information. The official API includes packages, e.g., applet
packages, graphics and GUI swing packages, input/output (IO) packages and Abstract
Windows Toolkit (AWT), among others.
There are three frames when an API starts, as follows:

 The first frame shows all API components (classes and packages).
 When a particular package is selected, the second frame shows all interfaces,
classes and exceptions of that particular package.
 The third and primary frame provides an overview of all of API packages,
which can be expanded in the main frame to show the index, class hierarchy
and help sections.

6. Java Platform

 Java is a set of computer software and specifications developed by Sun


Microsystems, which was later acquired by the Oracle Corporation, that
provides a system for developing application software and deploying it in
a cross-platform computing environment. Java is used in a wide variety
of computing platforms from embedded devices and mobile
phones to enterprise servers and supercomputers.
 Java applets, which are less common than standalone Java applications, run in
secure, sandboxed environments to provide many features of native
applications and can be embedded in HTML pages.

15
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

 Writing in the Java programming language is the primary way to produce code
that will be deployed as byte code in a Java virtual machine (JVM); byte
code compilers are also available for other languages,
including Ada, JavaScript, Python, and Ruby.
 Java eschews certain low-level constructs such as pointers and has a very
simple memory model where every object is allocated on the heap and all
variables of object types are references. Memory management is handled
through integrated automatic garbage collection performed by the JVM.
 The Java platform is a suite of programs that facilitate developing and running
programs written in the Java programming language. A Java platform will
include an execution engine (called a virtual machine), a compiler and a set
of libraries; there may also be additional servers and alternative libraries that
depend on the requirements. Java is not specific to any processor or operating
system as Java platforms have been implemented for a wide variety of
hardware and operating systems with a view to enable Java programs to run
identically on all of them. Different platforms target different classes of device
and application domains:

 Java Card: A technology that allows small Java-based applications (applets) to be


run securely on smart cards and similar small-memory devices.
 Java ME (Micro Edition): Specifies several different sets of libraries (known as
profiles) for devices with limited storage, display, and power capacities. It is often
used to develop applications for mobile devices, PDAs, TV set-top boxes, and
printers.
 Java SE (Standard Edition): For general-purpose use on desktop PCs, servers
and similar devices.
 Java EE (Enterprise Edition): Java SE plus various APIs which are useful
for multi-tier client–server enterprise applications.
 The Java platform consists of several programs, each of which provides a
portion of its overall capabilities. For example, the Java compiler, which
converts Java source code into Java bytecode (an intermediate language for the
JVM), is provided as part of the Java Development Kit (JDK). The Java
Runtime Environment(JRE), complementing the JVM with a just-in-time (JIT)
compiler, converts intermediate bytecode into native machine code on the fly.
The Java platform also includes an extensive set of libraries.
 The essential components in the platform are the Java language compiler, the
libraries, and the runtime environment in which Java intermediate bytecode
executes according to the rules laid out in the virtual machine specification.
 In most modern operating systems (OSs), a large body of reusable code is
provided to simplify the programmer's job. This code is typically provided as a
set of dynamically loadable libraries that applications can call at runtime.
Because the Java platform is not dependent on any specific operating system,
applications cannot rely on any of the pre-existing OS libraries. Instead, the
Java platform provides a comprehensive set of its own standard class libraries

16
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

containing many of the same reusable functions commonly found in modern


operating systems. Most of the system library is also written in Java.

7. Java Basic Syntax

When we consider a Java program, it can be defined as a collection of objects that


communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.
 Object − Objects have states and behaviors. Example: A dog has states - color,
name, breed as well as behavior such as wagging their tail, barking, eating. An
object is an instance of a class.
 Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
 Methods − A method is basically a behavior. A class can contain many
methods. It is in methods where the logics are written, data is manipulated and
all the actions are executed.
 Instance Variables − Each object has its unique set of instance variables. An
object's state is created by the values assigned to these instance variables.

7.1 First Java Program


Let us look at a simple code that will print the words Hello World.
Example
public class MyFirstJavaProgram
{
public static void main(String []args)
{
System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps −
 Open notepad and add the code as above.
 Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).
 Now, type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.

17
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

7.2 Basic Syntax (Rules)


About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity − Java is case sensitive, which means
identifier Hello and hello would have different meaning in Java.
 Class Names − For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.
Example: class MyFirstJavaClass
 Method Names − All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
Example: public void myMethodName()
 Program File Name − Name of the program file should exactly match the
class name.
When saving the file, you should save it using the class name (Remember Java
is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file
should be saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) − Java program processing starts from
the main() method which is a mandatory part of every Java program.
 interface name-- should start with uppercase letter
 variable name-- should start with lowercase letter e.g. firstName,
orderNumber etc.
 package name -- should be in lowercase letter e.g. java, lang, sql, util etc.

8. Java Identifiers
All Java components require names. Names used for classes, variables, and methods
are called identifiers. In Java, there are several points to remember about identifiers.
They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character
($) or an underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.

18
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

9. Lambda Expressions

Lambda expression is a new and important feature of Java which was included in Java
SE 8. It provides a clear and concise way to represent one method interface using an
expression. It is very useful in collection library. It helps to iterate, filter and extract
data from collection. Before lambda expression, anonymous inner class was the only
option to implement the method.
In other words, we can say it is a replacement of java inner anonymous class. Java
lambda expression is treated as a function, so compiler does not create .class file.
Functional Interface
Lambda expression provides implementation of functional interface. An interface
which has only one abstract method is called functional interface.

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


(argument-list) -> {body}

Java lambda expression is consisted of three components.

1) Argument-list: It can be empty or non-empty as well.


2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression.

Let's see a scenario. If we don't implement Java lambda expression. Here, we are
implementing an interface method without using lambda expression.

Java Example without Lambda Expression

interface Drawable{
public void draw();
}
public class LambdaExpressionExample {
public static void main(String[] args) {
int width=10;
Drawable d=new Drawable()
{
public void draw()
{
System.out.println("Drawing "+width);
} };
d.draw();
} }

19
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Output:

Drawing 10

Java Example with Lambda Expression

Now, we are implementing the above example with the help of lambda expression.

interface Drawable
{
public void draw();
}
public class LambdaExpressionExample
{
public static void main(String[] args)
{
int width=10;
//with lambda
Drawable d2=()->{
System.out.println("Drawing "+width);
};
d2.draw();
}
}

Output:

Drawing 10

10. Java Method References

Java provides a new feature called method reference in Java 8. Method reference is
used to refer method of functional interface. It is compact and easy form of lambda
expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. Here, we are
explaining method reference concept in detail.

Types of Method References

There are four types of method references:

1. Reference to a static method.


2. Reference to an instance method of a particular object.
3. Reference to a constructor.

20
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

1) Reference to a Static Method

You can refer to static method defined in the class. Following is the syntax and
example which describe the process of referring static method in Java.

Syntax : ContainingClass::staticMethodName

Example 1

In the following example, we have defined a functional interface and referring a static
method to it's functional method say().

interface Sayable
{
void say();
}
public class MethodReference
{
public static void saySomething()
{
System.out.println("Hello, this is static method.");
}
public static void main(String[] args)
{
// Referring static method
Sayable sayable = MethodReference::saySomething;
// Calling interface method
sayable.say();
}
}

Output:

Hello, this is static method.

2) Reference to an Instance Method

Like static methods, you can refer instance methods also. In the following example,
we are describing the process of referring the instance method.

Syntax

containingObject::instanceMethodName

21
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example 1

In the following example, we are referring non-static methods. You can refer methods
by class object and anonymous object.

interface Sayable
{
void say();
}
public class MethodReference
{
public void saySomething()
{
System.out.println("Hello, this is non-static method.");
}
public static void main(String[] args)
{
MethodReference methodReference = new MethodReference(); // Creating object
Sayable sayable = methodReference::saySomething;
sayable.say(); // Calling interface method
Sayable sayable2 = new MethodReference()::saySomething;
sayable2.say(); // Calling interface method
}
}

Output:

Hello, this is non-static method.


Hello, this is non-static method.

3) Reference to a Constructor

You can refer a constructor by using the new keyword. Here, we are referring
constructor with the help of functional interface.

Syntax: ClassName::new

Example

interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
22
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

System.out.print(msg);
}
}
public class ConstructorReference
{
public static void main(String[] args)
{
Messageable hello = Message::new;
hello.getMessage("Hello");
}
}

Output:

Hello

11. Java Type Annotations

Java 8 has included two new features repeating and type annotations in its prior
annotations topic. In early Java versions, you can apply annotations only to
declarations. After releasing of Java SE 8 , annotations can be applied to any type use.
It means that annotations can be used anywhere you use a type. For example, if you
want to avoid NullPointerException in your code, you can declare a string variable
like this:

1. @NonNull String str;

Following are the examples of type annotations:

2. @NonNull List<String>
3. List<@NonNull String> str
4. Arrays<@NonNegative Integer> sort
5. @Encrypted File file
6. @Open Connection connection
7. void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException

12. Java Compiler and Interpreter

Difference between Compiler and Interpreter

No Compiler Interpreter
1 Compiler Takes Entire program as input Interpreter Takes Single instruction as
input.
2 Intermediate Object Code is Generated No Intermediate Object Code
is Generated

23
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

3 Conditional Control Statements are Conditional Control Statements are


Executes faster Executes slower
4 Memory Requirement : More(Since Memory Requirement is Less
Object Code is Generated)
5 Program need not be compiled every Every time higher level program is
time converted into lower level program
6 Errors are displayed after entire Errors are displayed for every
program is checked instruction interpreted (if any)
7 Example : C Compiler Example : BASIC

Explanation: Compiler Vs Interpreter


Just understand the concept of the compiler and interpreter –
1. We give complete program as input to the compiler. Our program is in the
human readable format.
2. Human readable format undergoes many passes and phases of compiler and
finally it is converted into the machine readable format.
3. However interpreter takes single line of code as input at a time and execute that
line. It will terminate the execution of the code as soon as it finds the error.
4. Memory requirement is less in Case of interpreter because no object code is
created in case of interpreter

13. Java Applications

1. Desktop GUI Applications:

Java provides GUI development through various means like Abstract Windowing
Toolkit (AWT), Swing and JavaFX. While AWT contains a number of pre-
constructed components such as menu, button, list, and numerous third-party
components, Swing, a GUI widget toolkit, additionally provides certain advanced
components like trees, tables, scroll panes, tabbed panel and lists. JavaFX, a set of
graphics and media packages, provides Swing interoperability, 3D graphic features
and self-contained deployment model which facilitates quick scripting of Java applets
and applications.

2. Mobile Applications:
Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to
build applications that run across all Java supported devices, including feature phones
and smart phones. Further, applications for Android, one of the most popular mobile
operating systems, are usually scripted in Java using the Android Software
Development Kit (SDK) or other environments.

3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components
of larger electromechanical systems performing dedicated tasks. Several devices, such

24
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

as SIM cards, blue-ray disk players, utility meters and televisions, use embedded Java
technologies. According to Oracle, 100% of Blu-ray Disc Players and 125 million
TV devices employ Java.

4. Web Applications:

Java provides support for web applications through Servlets, Struts or JSPs. The easy
programming and higher security offered by the programming language has allowed a
large number of government applications for health, social security, education and
insurance to be based on Java. Java also finds application in development of
eCommerce web applications using open-source eCommerce platforms, such as
Broadleaf.

5. Web Servers and Application Servers:


The Java ecosystem today contains multiple Java web servers and application
servers. While Apache Tomcat, Simple, Jo!, Rimfaxe Web Server (RWS) and Project
Jigsaw dominate the web server space, WebLogic, WebSphere, and Jboss EAP
dominate commercial application server space.

6. Enterprise Applications:

Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime
environment for scripting and running enterprise software, including network
applications and web-services. Oracle claims Java is running in 97% of enterprise
computers. The higher performance guarantee and faster computing in Java has
resulted in high frequency trading systems like Murex to be scripted in the language.
It is also the backbone for a variety of banking applications which have Java running
from front user end to back server end.

7. Scientific Applications:

Java is the choice of many software developers for writing applications involving
scientific calculations and mathematical operations. These programs are generally
considered to be fast and secure, have a higher degree of portability and low
maintenance. Applications like MATLAB use Java both for interacting user interface
and as part of the core system.

14. Java Statements

Statements are similar to sentences in the English language. A sentence forms a


complete idea which can include one or more clauses. Likewise, a statement in Java
forms a complete command to be executed and can include one or more expressions.

In simpler terms, a Java statement is just an instruction that explains what should
happen.

25
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Types of Java Statements

There are three main groups that encompass the different kinds of statements in Java:

 Expression statements change values of variables, call methods, and create


objects.
 Declaration statements declare variables.
 Control flow statements determine the order that statements are executed.
Typically, they're understood from top to bottom. However, with control flow
statements, that order can be interrupted to implement branching or looping so
that the Java program can run particular sections of code based on certain
conditions.

Examples of java statements

//declaration statement
int number;

//expression statement
number = 4;

//control flow statement


if (number < 10 )
{
//expression statement
System.out.println(number + " is less than ten");
}

15. Java Main Method

 public static void main(String args[]) is the main method in Java. Main method
is called by JVM. Main method is called before any object creation so A
method which can called by class name it must be static so it can be called. but
here main must be public because it is accessed by outer of default
environment (call by JVM ).
 When we are run java program by command =>java MY_Class
This command JVM interpret as this class must have a public static main
method. JVM search until it will not found main and if signature of main not
found then throws exception.

26
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

16. White Space in Java

The method determines whether the specified char value is a white space, which
includes space, tab, or new line.
Syntax: boolean isWhitespace(char ch)
Parameters
Here is the detail of parameters −
 ch − Primitive character type.
Return Value

 This method returns true, if the passed character is really a white space.
Example

public class Test


{
public static void main(String args[])
{
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));
}
}
This will produce the following result −
Output
false
true
true
true

17. Keywords

Keywords have special meaning to the Java compiler. They help in identifying a data
type name or program construct name.

abstract Continue for new switch


assert default goto package synchronized
boolean Do if private this
break double implements protected throw
byte Else import public throws
case Enum instanceof return transient

27
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

catch extends int short Try


char Final interface static void
class finally long strictfp volatile
Const Float native super while

18. Java Comments

The java comments are statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code
for specific time.

Types of Java Comments

There are 2 types of comments in java.

1. Single Line Comment


2. Multi Line Comment

1) Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

// : This is single line comment

Example:

public class CommentExample1 {


public static void main(String[] args) {
int i=10; //Here, i is a variable
System.out.println(i);
}
}

Output:

10

2) Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax: /* This is multi line comment */


28
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example:

public class CommentExample2 {


public static void main(String[] args)
{
/* Let's declare and print variable in java. */
int i=10;
System.out.println(i);
}
}

Output:

10

19. Braces in Java

One: Opening Curly Braces on the Same Line:

The biggest advantage to having the opening curly brace on the same line is to save
vertical space. Vertical density is an important topic when talking about easy-to-read
code, so this is definitely something that we should consider. By having the curly
brace on the same line, we reduce the (already short) code sample above by 3
lines. This means that we have more space on the screen to see additional code.

Two: Opening Curly Braces on a Separate Line

The biggest advantage to having the opening curly brace on a separate line is that the
curly braces will always line up visually (assuming that we are also using good
horizontal spacing in our code). This makes it easy to visually spot the beginning of
the code block -- we just need to find the end brace and then scan up until we see an
opening brace in the same column.

20. Variables in Java

 A variable provides us with named storage that our programs can manipulate.
Each variable in Java has a specific type, which determines the size and layout
of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the variable.
 Variable is a name of memory location. There are three types of variables in
java: local, instance and static.
 Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means its
value can be changed.

29
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Example:

int data=50; //Here data is variable


int a, b, c; // Declares three int, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

Types of Variable

There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variables:
 A variable which is declared inside the method is called local variable.
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor, or
block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or
block.
 There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.

2) Instance Variable
 A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.
 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.

30
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

 Instance variables can be declared in class level before or after use.


 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access
level). However, visibility for subclasses can be given for these variables with
the use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.

3) Static variable
 A variable that is declared as static is called static variable. It cannot be local.
 Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
 Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values
can be assigned in special static initializer blocks.
Example to understand the types of variables in java

class A
{
int data=50; //instance variable
static int m=100; //static variable
void method(){
int n=90; //local variable
}
} //end of class

31
Core Java Unit 1 - Chapter 1 SYBSCIT-SEM IV

Questions

1. Explain the history of Java in short. Why "Java" name was given to the
language?
2. Difference between Java and C++?
3. Explain the features of Java.
4. Difference between JDK, JRE and JVM.
5. Explain Java Virtual Machine with diagram.
6. Explain Internal Architecture of JVM.
7. Explain Java Architecture and its Components.
8. Explain compilation and running of java program. How to set path in Java?
9. Write a short note on Java API.
10. Explain the various Java Platform.
11. Explain the basic syntax and rules for Java with an example.
12. What is Java Identifiers? Explain Lambda Expressions with an example.
13. Explain Java Method References with its types.
14. What is Java Type Annotations?
15. Differentiate between Compiler and Interpreter.
16. What are the applications of Java?
17. Explain Java Statements with an example.
18. Explain the syntax of Java main().
19. Explain white spaces in Java. List various reserved keywords.
20. Define Comments. Explain the types of comments.
21. Define variables. What are the types of variables?

32
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Unit I
Chapter 2: Data Types

Contents

 Primitive Data Types


 Object Reference Types
 Strings
 Auto boxing
 Operators and Properties of Operators
 Arithmetic Operators
 Assignment Operators
 Increment and Decrement Operator
 Relational Operator
 Logical Operator
 Bitwise Operator
 Conditional Operator

1. Introduction

 Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in the memory.
 Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals, or characters in
these variables.
 Data types represent the different values to be stored in the variable. In java, there
are two types of data types:
o Primitive data types
o Non-primitive data types

33
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Data Type Default Value Default size


Boolean False 1 bit
Char '\u0000' 2 byte
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d 8 byte

Why char uses 2 byte in java and what is \u0000 ?

It is because java uses Unicode system than ASCII code system. The \u0000 is the lowest
range of Unicode system. To get detail explanation about Unicode visit next page.

1.1 Primitive Data Types

There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.

1)byte:
 Byte data type is an 8-bit signed two's complement integer
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50
2)short:
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

34
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

3) int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values unless there is
a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
4) long:
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
5) float:
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f
6) double:
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal values,
generally the default choice
 Double data type should never be used for precise values such as currency
 Default value is 0.0d
 Example: double d1 = 123.4
7) boolean:
 boolean data type represents one bit of information
 There are only two possible values: true and false
 This data type is used for simple flags that track true/false conditions
 Default value is false
 Example: boolean one = true
8) char:
 char data type is a single 16-bit Unicode character
 Minimum value is '\u0000' (or 0)

35
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 Maximum value is '\uffff' (or 65,535 inclusive)


 Char data type is used to store any character
 Example: char letterA = 'A'
9) Reference Data types
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type or any
compatible type.
 Example: Animal animal = new Animal("giraffe");

Java Variable Example: Add Two Numbers

class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}

Output:

20

1.2 Java Literals


A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation. Literals can be assigned to any primitive type
variable.

For Example

byte a = 68;
char a = 'A'

36
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or
octal(base 8) number systems as well. Prefix 0 is used to indicate octal, and prefix 0x
indicates hexadecimal when using these number systems for literals.

For example

int decimal = 100;


int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are −
Example

"Hello World"
"two\nlines"
"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";

2. Object Reference Types

Assigning Object Reference Variables:

1. We can assign value of reference variable to another reference variable.


2. Reference Variable is used to store the address of the variable.
3. Assigning Reference will not create distinct copies of Objects.
4. All reference variables are referring to same Object.

Assigning Object Reference Variables does not –

1. Create Distinct Objects.


2. Allocate Memory
3. Create duplicate Copy
Example
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;

37
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 r1 is reference variable which contain the address of Actual Rectangle Object.


 r2 is another reference variable
 r2 is initialized with r1 means – “r1 and r2” both are referring same object , thus
it does not create duplicate object , nor does it allocate extra memory.

Example:

Assigning Object Reference Variables

class Rectangle
{
double length;
double breadth;
}
class RectangleDemo
{
public static void main(String args[])
{
Rectangle r1 = new Rectangle();
Rectangle r2 = r1;
r1.length = 10;
r2.length = 20;
System.out.println("Value of R1's Length : " + r1.length);
System.out.println("Value of R2's Length : " + r2.length);
}}

Output:

Value of R1's Length : 20.0


Value of R2's Length : 20.0

38
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

3. Strings

String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java,


string is an immutable object which means it is constant and can cannot be changed once
it has been created.

Creating a String

There are two ways to create a String in Java

1. String literal
2. Using new keyword

3.1 String literal

In java, Strings can be created like this: Assigning a String literal to a String instance:

String str1 = "Welcome";


String str2 = "Welcome";

The problem with this approach:

 String is an object in Java. However we have


not created any string object using new
keyword above. The compiler does that task
for us it creates a string object having the
string literal (that we have provided , in this
case it is “Welcome”) and assigns it to the
provided string instances.
 But if the object already exist in the memory
it does not create a new Object rather it
assigns the same old object to the new
instance, that means even though we have
two string instances above(str1 and str2)
compiler only created on string object (having the value “Welcome”) and assigned
the same to both the instances. For example there are 10 string instances that have
same value, it means that in memory there is only one object having the value and
all the 10 string instances would be pointing to the same object.
 What if we want to have two different object with the same string? For that we
would need to create strings using new keyword.

39
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 Each time you create a string literal, the JVM checks the string constant pool first.
If the string already exists in the pool, a reference to the pooled instance is
returned. If string doesn't exist in the pool, a new string instance is created and
placed in the pool. For example:

String s1="Welcome";
String s2="Welcome"; //will not create new instance

In the above example only one object will be created. Firstly JVM will not find any string
object with the value "Welcome" in string constant pool, so it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create
new object but will return the reference to the same instance

3.2 Using New Keyword

As we saw above that when we tried to assign the same string object to two different
literals, compiler only created one object and made both of the literals to point the same
object. To overcome that approach we can create strings like this:

String str1 = new String("Welcome");


String str2 = new String("Welcome");

In this case compiler would create two different object in memory having the same string.

A Simple Java String Example

public class Example


{
public static void main(String args[])
{
//creating a string by java string literal
String str = "corejava";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);
//creating another java string str3 by using new keyword
String str3 = new String("Java String Example");
//Displaying all the three strings
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}}

40
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Output:

corejava
hello
Java String Example

3.3 Java String Methods

Here are the list of the methods available in the Java String class.

Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

String s="Sachin";
System.out.println(s.toUpperCase()); //SACHIN
System.out.println(s.toLowerCase()); //sachin
System.out.println(s); //Sachin(no change in original)

Output:

SACHIN
sachin
Sachin

Java String trim() method

The string trim() method eliminates white spaces before and after string.

String s=" Sachin ";


System.out.println(s); // Sachin
System.out.println(s.trim()); //Sachin

Output:

Sachin
Sachin

Java String startsWith() and endsWith() method

String s="Sachin";

41
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

System.out.println(s.startsWith("Sa")); //true
System.out.println(s.endsWith("n")); //true

Output:

true
true

Java String charAt() method

The string charAt() method returns a character at specified index.

String s="Sachin";
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3)); //h

Output:

S
h

Java String length() method

The string length() method returns length of the string.

String s="Sachin";
System.out.println(s.length()); //6

Output:

Java String intern() method

A pool of strings, initially empty, is maintained privately by the class String. When the
intern method is invoked, if the pool already contains a string equal to this String object
as determined by the equals(Object) method, then the string from the pool is returned.
Otherwise, this String object is added to the pool and a reference to this String object is
returned.

String s=new String("Sachin");


String s2=s.intern();
System.out.println(s2); //Sachin

42
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Output:
Sachin

Java String valueOf() method

The string valueOf() method coverts given type such as int, long, float, double, boolean,
char and char array into string.

int a=10;
String s=String.valueOf(a);
System.out.println(s+10);

Output:

1010

Java String replace() method

The string replace() method replaces all occurrence of first sequence of character with
second sequence of character.

String s1="Java is a programming language. Java is a platform. Java is an Island.";


String replaceString=s1.replace("Java","Kava");
System.out.println(replaceString); //replaces all occurrences of "Java" to "Kava"

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

4. Type Casting

Type casting in Java is used to cast one class or interface to another, if they are from
same type hierarchy.

Example:
int x = 10;
byte y = (byte)x;

In Java, type casting is classified into two types,

43
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 Widening Casting(Implicit)

 Narrowing Casting(Explicitly done)

4.1 Widening or Automatic type conversion


Automatic Type casting take place when,
 the two types are compatible
 the target type is larger than the source type

Example:
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

Output:
Int value 100
Long value 100
Float value 100.0

44
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

4.2 Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.
Example:
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

Output:
Double value 100.04
Long value 100
Int value 100

5. Auto Boxing and Unboxing

 Java uses primitive data types such as int, double, float etc. to hold the basic data
types for the sake of performance. Despite the performance benefits offered by the
primitive data types, there are situations when you will need an object
representation of the primitive data type. For example, many data structures in
Java operate on objects. So you cannot use primitive data types with those data
structures. To handle such type of situations, Java provides type Wrappers which
provide classes that encapsulate a primitive type within an object.
 The automatic conversion of primitive data types into its equivalent Wrapper type
is known as boxing and opposite operation is known as unboxing. This is the new
feature of Java5. So java programmer doesn't need to write the conversion code.
5.1 Benefits of Autoboxing / Unboxing
 Autoboxing / Unboxing lets us use primitive types and Wrapper class objects
interchangeably.
 We don't have to perform Explicit typecasting.

45
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 It helps prevent errors, but may lead to unexpected results sometimes. Hence must
be used with care.
 Auto-unboxing also allows you to mix different types of numeric objects in an
expression. When the values are unboxed, the standard type conversions can be
applied.

Simple Example of Autoboxing in java:

class BoxingExample1
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing

Integer a3=5; //Boxing


System.out.println(a2+" "+a3);
} }

Output: 50 5

Simple Example of Unboxing in java:

The automatic conversion of wrapper class type into corresponding primitive type, is
known as Unboxing. Let's see the example of unboxing:

class UnboxingExample1
{
public static void main(String args[])
{
Integer i=new Integer(50);
int a=i;
System.out.println(a);
} }

Output: 50

6. Operators

Java provides a rich set of operator’s environment. Java operators can be divided into
following categories:

46
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

 Arithmetic operators
 Relation operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Misc operators
6.1 Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used
in algebra.
Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator increases integer value by one

-- Decrement operator decreases integer value by one

Java Arithmetic Operator Example

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0 }}

47
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression

class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}}

Output:

21

6.2 Relation Operators


The following table shows all relation operators supported by Java.
Operator Description

== Check if two operand are equal

!= Check if two operand are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

48
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Relational Operators

public class Test


{
public static void main(String args[])
{
int a = 10;
int b = 20;
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("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

This will produce the following result −


Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
6.3 Logical Operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

6.4 Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types long, int,
short, char and byte

49
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> left shift

<< right shift

Java Shift Operator Example: Left Shift

class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}

Output:

40
80
80
240

Java Shift Operator Example: Right Shift

class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}}

50
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Output:

2
5
2

Now lets see truth table for bitwise &, | and ^


A B a&b a|b a^b

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0

The bitwise shift operator shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value
are to be shifted. Both operands have the same precedence.
Example
a = 0001000
b=2
a << b = 0100000
a >> b = 0000010

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true. The bitwise & operator always checks
both conditions whether first condition is true or false.

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;

51
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

System.out.println(a<b&&a<c); //false && true = false


System.out.println(a<b&a<c); //false & true = false
}}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c); //false && true = false
System.out.println(a); //10 because second condition is not checked
System.out.println(a<b&a++<c); //false && true = false
System.out.println(a); //11 because second condition is checked
}}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false. The bitwise | operator always checks both
conditions whether first condition is true or false.

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;

52
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

int c=20;
System.out.println(a>b||a<c); //true || true = true
System.out.println(a>b|a<c); //true | true = true
System.out.println(a>b||a++<c); //true || true = true
System.out.println(a); //10 because second condition is not checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition is checked
}}

Output:

true
true
true
10
true
11

6.5 Assignment Operators


Assignment operator supported by Java are as follows:
Operator Description Example

= assigns values from right side operands to left side operand a=b

+= adds right operand to the left operand and assign the result to a+=b is same
left as a=a+b

-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b

*= mutiply left operand with the right operand and assign the a*=b is same
result to left operand as a=a*b

/= divides left operand with the right operand and assign the a/=b is same
result to left operand as a=a/b

%= calculate modulus using two operands and assign the result a%=b is same
to left operand as a=a%b

53
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Java Assignment Operator Example

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

Java Assignment Operator Example

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

Output:

13
9
18
9

54
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

6.6 Misc operator

There are few other operator supported by java language.


6.6.1 Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3

If epr1 Condition is true? Then value expr2 : Otherwise value expr3

Java Ternary Operator Example

class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:

6.6.2 Increment and Decrement Operator in Java :

 It is one of the variation of “Arithmetic Operator“.


 Increment and Decrement Operators are Unary Operators.
 Unary Operator Operates on One Operand.
 Increment Operator is Used to Increment Value Stored inside Variable on which it
is operating.
 Decrement Operator is used to decrement value of Variable by 1 (default).

6.6.2.1 Types of Increment and Decrement Operator:

1. Pre Increment / Pre Decrement Operator


2. Post Increment / Post Decrement Operator

55
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Pre-Increment Operator:
1. “++” is written before Variable name.
2. Value is Incremented First and then incremented value is used in expression.
3. “++” cannot be used over “Constant” of “final Variable“.

Syntax:

++ Increment operator : increments a value by 1


-- Decrement operator : decrements a value by 1

Example 1: Pre Incrementing Variable

class PreIncrement
{
public static void main(String args[])
{
int num1 = 1;
int num2 = 1;
--num1;
--num2;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}}
Output:
num1 = 0
num2 = 0

 Pre Increment : First Increment Value and then Assign Value.


 ++num1 will increment value inside “num1” variable. New value is assigned to
itself.
 New Value of num1 = 0.

Post Increment Operator:

 Post Increment : Increment Value of Variable After Assigning


 num1++ will increment value inside “num1” variable after assigning old value to
itself.
 New Value of num1 = 2.

56
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Example 2: Post Incrementing Variable

class PostIncrement
{
public static void main(String args[]) {
int num1 = 1;
int num2 = 1;
num1++;
num2++;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}}

Output:
num1 = 2
num2 = 2

Java Unary Operator Example: ++ and --

class OperatorExample
{
public static void main(String args[])
{
int x=10;
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

57
Core Java Unit 1 - Chapter 2 SYBSCIT-SEM IV

Questions

1. Define Data Types. Explain the types of data types.


2. Explain the types of Primitive data types.
3. Explain Java Literals with example.
4. Explain Object Reference types with an example.
5. Explain String Literal. What is the use of New Keyword? Give example.
6. Explain Java String Methods with an example.
7. Explain Type Casting with its syntax and example.
8. What is Autoboxing and Unboxing? Give the benefits and example.
9. Explain Arithmetic Operator and Relational Operator with an example.
10. Explain Logical and Bitwise Operator with an example.
11. Explain Assignment and Conditional Operator with an example.
12. Explain increment and decrement operator with its types and example.

58
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

Unit 2
Chapter 1 – Control Flow Statements

Contents:
The If…Else If…Else Statement
The Switch Case Statement

1. Introduction
 Decision making structures have one or more conditions to be evaluated or tested
by the program, along with a statement or statements that are to be executed if the
condition is determined to be true, and optionally, other statements to be executed
if the condition is determined to be false.
 Following is the general form of a typical decision making structure found in most
of the programming languages −

1.1 if statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(Boolean_expression)
{
// Statements will execute if the Boolean expression is true
}

59
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

 If the Boolean expression evaluates to true then the block of code inside the if
statement will be executed. If not, the first set of code after the end of the if
statement (after the closing curly brace) will be executed.
Flow Diagram

Example

public class Test


{
public static void main(String args[])
{
int x = 10;

if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
This will produce the following result −
Output
This is if statement.

1.2 if-else statement


An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

60
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

Syntax

if(Boolean_expression)
{
// Executes when the Boolean expression is true
}
else
{
// Executes when the Boolean expression is false
}

If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram

Example
public class Test {
public static void main(String args[]) {
int x = 30;
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
Output
This is else statement

61
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

1.3 The if...else if...else Statement


A if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if, else if, else statements there are a few points to keep in mind.
 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
Following is the syntax of an if...else statement −
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}
else
{
// Executes when the none of the above condition is true.
}
Example
public class Test {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
} } }
Output
Value of X is 30
62
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

1.4 Nested if-else


It is always legal to nest if-else statements which means you can use one if or else if
statement inside another if or else if statement.
Syntax
The syntax for a nested if...else is as follows −
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
} }
You can nest else if...else in the similar way as we have nested if statement.
Example
public class Test {
public static void main(String args[]) {
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
} } } }
This will produce the following result −
Output
X = 30 and Y = 10

1.5 switch statement


A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each case.
Syntax
The syntax of enhanced for loop is −
switch(expression) {
case value :
// Statements
break; // optional

63
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

case value :
// Statements
break; // optional
// You can have any number of case statements.
default : // Optional
// Statements
}
The following rules apply to a switch statement −
 The variable used in a switch statement can only be integers, convertable integers
(byte, short, char), strings and enums.
 You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none
of the cases is true. No break is needed in the default case.
Flow Diagram

64
Core Java Unit 2-Chpater 1 SYBSCIT-SEM IV

Example
public class Test
{
public static void main(String args[])
{
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D'
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}}
Output
Well done
Your grade is C

Questions

1. Explain if statement with its syntax, control flow diagram and example.
2. Explain if-else statement with its syntax, control flow diagram and example.
3. Explain if...else if...else statement with its syntax, control flow diagram and
example.
4. Explain Nested if-else statement with its syntax, control flow diagram and
example.
5. Explain switch statement with its syntax, control flow diagram and example.

65
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

Unit 2
Chapter 2 - Iterations

Contents:

 The While Loop


 The Do … While Loop
 The For Loop
 The Foreach Loop
 Labelled Statements
 The Break And Continue Statements
 The Return Statement

1. Introduction:

Looping statement is the statements execute one or more statement repeatedly several
number of times. In java programming language there are three types of loops; while, for
and do-while.

Why use loop?


When you need to execute a block of code several number of times then you need to use
looping concept in Java language.

Advantage with looping statement


 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

Difference between conditional and looping statement


Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.

66
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

1.1 While loop

In while loop first check the condition if condition is true then control goes inside the
loop body otherwise goes outside of the body. while loop will be repeats in clock wise
direction.

Syntax

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

Example while loop

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

Output
0
1
2
3
4

1.2 for loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3
parts Initialization, Condition and Increment or Decrements

Syntax

for ( initialization; condition; increment )

67
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

{
statement(s);
}

 Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any
loop control variables.
 Condition: This is next step after initialization step, if it is true, the body of the
loop is executed, if it is false then the body of the loop does not execute and flow
of control goes outside of 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 execute.
This statement allows to update any loop control variables.

Flow Diagram

Control flow of for loop

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

68
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

Example of for loop (* Display any message exactly 5 times)


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

Output

Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !
Hello Friends !

1.3 do-while

 A do-while loop is similar to a while loop, except that a do-while loop is execute
at least one time.
 A do while loop is a control flow statement that executes a block of code at least
once, and then repeatedly executes the block, or not, depending on a given
condition at the end of the block (in while).

69
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

When use do..while loop


When we need to repeat the statement block at least one time then use do-while loop. 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();

In below example you can see in this program i=20 and we check condition i is less than
10, that means condition is false but do..while loop execute onec and print Hello world !
at one time.

Example do..while loop

class dowhileDemo
{
public static void main(String args[])
{
int i=20;
do
{
System.out.println("Hello world !");
i++;
}
while(i<10);
}}

Output

Hello world !

Example do..while loop

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

70
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

{
int i=0;
do
{
System.out.println(+i);
i++;
}
while(i<5);
}
}

Output
1
2
3
4
5

1.4 Break statement


The break statement in Java programming language has the following two usages −
 When the break statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
 It can be used to terminate a case in the switch statement (covered in the next
chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
Flow Diagram

71
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

Example
public class Test
{
public static void main(String args[])
{
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers )
{
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
} } }
This will produce the following result −
Output
10
20

1.5 Continue statement


 The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.
 In a for loop, the continue keyword causes control to immediately jump to the
update statement.
 In a while loop or do/while loop, control immediately jumps to the Boolean
expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue;
Flow Diagram

72
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

Example
public class Test
{
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
10
20
40
50

1.6 Labelled Loop


According to nested loop, if we put break statement in inner loop, compiler will jump
out from inner loop and continue the outer loop again. What if we need to jump out from
the outer loop using break statement given inside inner loop? The answer is, we should
define lable along with colon(:) sign before loop.

Syntax of Labelled loop

73
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

Example without labelled loop


class WithoutLabelledLoop
{
public static void main(String args[])
{
int i,j;

for(i=1;i<=10;i++)
{
System.out.println();

for(j=1;j<=10;j++)
{
System.out.print(j + " ");

if(j==5)
break; //Statement 1
} } } }

Output :

12345
12345
12345
12345
12345
12345
12345
12345
12345
12345

In the above example, statement 1 will break the inner loop and jump outside from inner
loop to execute outer loop.

Example with labelled loop


class WithLabelledLoop
{
public static void main(String args[])
{
int i,j;

74
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

loop1: for(i=1;i<=10;i++)
{
System.out.println();

loop2: for(j=1;j<=10;j++)
{
System.out.print(j + " ");

if(j==5)
break loop1; //Statement 1
} } }}

Output :

12345
In the above example, statement 1 will break the inner loop and jump outside the outer
loop.

1.7 For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection
elements. The advantage of for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.

Advantage of for-each loop:

o It makes the code more readable.


o It eliminates the possibility of programming errors.

Syntax of for-each loop:

for(data_type variable : array | collection){}

Example of for-each loop for traversing the array elements:

class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
for(int i:arr)

75
Core Java Unit 2-Chapter 2 SYBSCIT-SEM IV

{
System.out.println(i);
} } }

Output:
12
13
14
44

Questions

1. Why we use loops? Give its advantages.


2. Differentiate between conditional and looping statement.
3. Explain while loop and for loop with its syntax and example.
4. Explain do-while loop with its syntax and example.
5. Explain break and continue statement with its syntax, control flow diagram and an
example.
6. Explain Labeled loop with its syntax and an example.
7. Explain For-each loop with its advantages, syntax and example.

76
Core Java Unit 2 SYBSCIT-SEM IV

Unit II
Chapter 3 – Classes

Contents:

 Types of Classes,
 Scope Rules,
 Access Modifier,
 Instantiating Objects From A Class,
 Initializing the Class Object And Its Attributes,
 Class Methods,
 Accessing A Method,
 Method Returning A Value,
 Method's Arguments,
 Method Overloading,
 Variable Arguments [Varargs],
 Constructors,
 this Instance,
 Super Instance,
 Characteristics of Members of A Class,
 Constants,
 Static fields of a class,
 Static methods of a class,
 Garbage Collection.

1. Introduction

1.1 Class declaration

 A class is a template for manufacturing objects. You declare a class by specifying


the class keyword followed by a non-reserved identifier that names it. A pair of
matching open and close brace characters ({ and }) follow and delimit the class's
body. This syntax appears below:

class identifier
{
// class body
}

77
Core Java Unit 2 SYBSCIT-SEM IV

 By convention, the first letter of a class's name is uppercased and subsequent


characters are lowercased (for example, Employee). If a name consists of multiple
words, the first letter of each word is uppercased (such as SavingsAccount). The
following example declares a class named Book:

class Book
{
// class body
}

 A class's body is populated with fields, methods, and constructors. Combining


these language features into classes is known as encapsulation. This capability lets
us program at a higher level of abstraction (classes and objects) rather than
focusing separately on data structures and functionality.

1.2 Multi-class applications and main()

 A Java application is implemented by one or more classes. Small applications can


be accommodated by a single class, but larger applications often require multiple
classes. In that case one of the classes is designated as the main class and contains
the main() entry-point method. For example, Listing 1 presents an application built
using three classes: A, B, and C; C is the main class.

Syntax: Java application with multiple classes

class A
{}
class B
{}
class C
{
public static void main(String[]args)
{
System.out.println("Application C entry point");
}}

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

 fields
 methods

78
Core Java Unit 2 SYBSCIT-SEM IV

 constructors
 blocks
 nested class and interface

2. Scope Rules

 We can declare variables within any block.


 Block is begun with an opening curly brace and ended by a closing curly brace.
 1 block equal to 1 new scope in Java thus each time you start a new block, you
are creating a new scope.
 A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.

Example 1: Variable Scope in Java Programming

class Scope {
public static void main(String args[])
{
int n1; // Visible in main
n1 = 10;
if(n1 == 10)
{ // start new scope
int n2 = 20; // visible only to this block
System.out.println("n1 and n2 : "+ n1 +""+ n2); // num1 and num2 both visible
here.
}
// n2 = 100; // Error! y not known here
// n1 is still visible here.
System.out.println("n1 is " + n1);
}}

Output :

n1and n2 : 10 20
n1 is 10

 n1 is declared in main block thus it is accessible in main block.


 n2 is declared in if block thus it is only accessible inside if block.
 Any attempt to access it outside block will cause compiler time error.
 Nested Block can have access to its outermost block. [if block is written inside
main block thus all the variables declared inside main block are accessible in if
block]

79
Core Java Unit 2 SYBSCIT-SEM IV

Example 2 : How we get Compile Error

class ScopeInvalid {
public static void main(String args[]) {
int num = 1;
{ // creates a new scope
int num = 2; // Compile-time error
// num already defined
} } }

It will cause compile error because variable “num” is declared in main scope and thus it
is accessible to all the innermost blocks. However we can try this –

class ScopeInvalid
{
public static void main(String args[])
{
{ // creates a new scope
int num = 1;
}
{ // creates a new scope
int num = 2;
}}}

3. Access Modifier

Each object has members (members can be variable and methods) which can be declared
to have specific access. Java has 4 access level and 3 access modifiers. Access levels are
listed below in the least to most restrictive order.
3.1 public: Members (variables, methods, and constructors) declared public (least
restrictive) within a public class are visible to any class in the Java program, whether
these classes are in the same package or in another package. Below screen shot shows
eclipse view of public class with public members.
3.2 protected: The protected fields or methods, cannot be used for classes and Interfaces.
Fields, methods and constructors declared protected in a super-class can be accessed only
by subclasses in other packages. Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not a subclass of the protected
member’s class.
3.3 Default (no value):The default access level is declared by not writing any access
modifier at all. Any class, field, method or constructor that has no declared access
modifier is accessible only by classes in the same package.

80
Core Java Unit 2 SYBSCIT-SEM IV

3.4 private: The private (most restrictive) modifiers can be used for members but cannot
be used for classes and Interfaces. Fields, methods or constructors declared private are
strictly controlled, which means they cannot be accessed by anywhere outside the
enclosing class.
Java has modifiers other than access modifiers listed below:
3.5 static: static can be used for members of a class. The static members of the class can
be accessed without creating an object of a class. Let's take an example of Vehicle class
which has run () as a static method and stop () as a non-static method. In Maruti class we
can see how to access static method run () and non-static method stop ().
3.6 final: This modifier applicable to class, method, and variables. This modifier tells the
compiler not to change the value of a variable once assigned. If applied to class, it cannot
be sub-classed. If applied to a method, the method cannot be overridden in sub-class. In
below sample, we can see compiler errors while trying to change the value of filed age
because it is defined as final while we can change the value of name field.
3.7 abstract: There are situations in which you will want to define a superclass that
declares the structure of a given abstraction without providing a complete implementation
of every method. This modifier is applicable to class and methods only.

Below Table summarizes the access modifiers


Modifier class constructor method Data/variables
Public Yes Yes Yes Yes
protected Yes Yes Yes
Default Yes Yes Yes Yes
Private Yes Yes Yes
Static Yes
Final Yes Yes

4. Object in Java

 Let us now look deep into what are objects. If we


consider the real-world, we can find many objects
around us, cars, dogs, humans, etc. All these objects
have a state and a behavior.
 If we consider a dog, then its state is - name, breed,
color, and the behavior is - barking, wagging the tail,
running.
 If you compare the software object with a real-world
object, they have very similar characteristics.
 Software objects also have a state and a behavior. A software object's state is
stored in fields and behavior is shown via methods.
 So in software development, methods operate on the internal state of an object and
the object-to-object communication is done via methods.
81
Core Java Unit 2 SYBSCIT-SEM IV

 An entity that has state and behavior is known as an object e.g. chair, bike, marker,
pen, table, car etc. It can be physical or logical (tangible and intangible). The
example of intangible object is banking system.

4.1 An object has three characteristics:

o state: represents data (value) of an object.


o behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.

4.2 Creating an Object


As mentioned previously, a class provides the blueprints for objects. So basically, an
object is created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class –

 Declaration − A variable declaration with a variable name with an object type.


 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Example

public class Puppy


{
public Puppy(String name) // This constructor has one parameter, name.
{
System.out.println("Passed Name is :"+ name );
}
public static void main(String[]args)
{
Puppy myPuppy=newPuppy("tommy") // Following statement would create an object
}}

82
Core Java Unit 2 SYBSCIT-SEM IV

Output

Passed Name is: tommy

4.3 Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instance
variable, following is the fully qualified path −
ObjectReference = new Constructor(); /* First create an object */
ObjectReference.variableName; /* Now call a variable as follows */
ObjectReference.MethodName(); /* Now you can call a class method as follows */

Example
This example explains how to access instance variables and methods of a class.
public class Puppy
{
int puppyAge;
public Puppy(String name) // This constructor has one parameter, name.
{
System.out.println("Name chosen is :"+ name );
}
publicvoidsetAge(int age )
{
puppyAge= age;
}
publicintgetAge()
{
System.out.println("Puppy's age is :"+puppyAge);
returnpuppyAge;
}
publicstaticvoid main(String[]args)
{
PuppymyPuppy=newPuppy("tommy"); /* Object creation */
myPuppy.setAge(2); /* Call class method to set puppy's age */
myPuppy.getAge(); /* Call another class method to get puppy's age */
System.out.println("Variable Value :"+myPuppy.puppyAge); /* You can access instance
variable as follows as well */
}
}

83
Core Java Unit 2 SYBSCIT-SEM IV

Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2

5. Class Methods

 A Java method is a collection of statements that are grouped together to perform


an operation. When you call the System.out.println() method, for example, the
system actually executes several statements in order to display a message on the
console.
 Now you will learn how to create your own methods with or without return values,
invoke a method with or without parameters, and apply method abstraction in the
program design.
5.1 Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b)
{
// body
}
Here,
 public static − modifier
 int − return type
 methodName − name of the method
 a, b − formal parameters
 int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in
the following syntax −
Syntax
modifier returnType nameofMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.

84
Core Java Unit 2 SYBSCIT-SEM IV

nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the
statements.
Example
Here is the source code of the above defined method called min(). This method takes two
parameters num1 and num2 and returns the maximum between the two −

public static int minFunction(int n1, int n2)


{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
5.2 Method Calling
 For using a method, it should be called. There are two ways in which a method is
called i.e., method returns a value or returning nothing (no return value).
 The process of method calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when –
 the return statement is executed.
 it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Let’s consider an
example −
System.out.println("hello world!");

The method returning value can be understood by the following example −

int result = sum(6, 9);

Example

public class ExampleMinNumber


{
public static void main(String[] args)
{
85
Core Java Unit 2 SYBSCIT-SEM IV

int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
public static int minFunction(int n1, int n2) /** returns the minimum of two numbers */
{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will produce the following result −
Output
Minimum value = 6

5.3 The void Keyword


 The void keyword allows us to create methods which do not return a value. Here,
in the following example we're considering a void method methodRankPoints.
This method is a void method, which does not return any value. Call to a void
method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement
which ends with a semicolon as shown in the following example.
Example
public class ExampleVoid
{
public static void main(String[] args)
{
methodRankPoints(255.7);
}
public static void methodRankPoints(double points)
{
if (points >= 202.5)
{
System.out.println("Rank:A1");
}

86
Core Java Unit 2 SYBSCIT-SEM IV

else if (points >= 122.4)


{
System.out.println("Rank:A2");
}
else
{
System.out.println("Rank:A3");
} }}

Output
Rank:A1

5.4 Passing Parameters by Value


 While working under calling process, arguments are to be passed. These should be
in the same order as their respective parameters in the method specification.
Parameters can be passed by value or by reference.
 Passing Parameters by Value means calling a method with a parameter. Through
this, the argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values of
the arguments remains the same even after the method invocation.
public class swappingExample
{
public static void main(String[] args)
{
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b); // Invoke the swap method
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b)
{
System.out.println("Before swapping(Inside), a = " + a + " b = " + b); // Swap n1 with n
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}}

87
Core Java Unit 2 SYBSCIT-SEM IV

This will produce the following result −


Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

5.5 Using Command-Line Arguments


 Sometimes you will want to pass some information into a program when you run
it. This is accomplished by passing command-line arguments to main( ).
 A command-line argument is the information that directly follows the program's
name on the command line when it is executed. To access the command-line
arguments inside a Java program is quite easy. They are stored as strings in the
String array passed to main( ).
Example
The following program displays all of the command-line arguments that it is called with:
public class CommandLine
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
{
System.out.println("args["+i+"]: "+args[i]);
}}}
Try executing this program as shown here −
$java CommandLine this is a command line 200 -100
This will produce the following result −
Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

88
Core Java Unit 2 SYBSCIT-SEM IV

5.6 Method Overloading in Java


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

5.6.1 Advantage of method overloading

 Method overloading increases the readability of the program.


 Different ways to overload the method. There are two ways to overload the
method in java
1. By changing number of arguments
2. By changing the data type
3. Let’s consider the example discussed earlier for finding minimum numbers of
integer type. If, let’s say we want to find the minimum number of double type.
Then the concept of overloading will be introduced to create two or more methods
with the same name but different parameters.
4. The following example explains the same −
Example
public class ExampleOverloading
{
public static void main(String[] args)
{
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
double result2 = minFunction(c, d); // same function name with different parameters
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}

89
Core Java Unit 2 SYBSCIT-SEM IV

public static int minFunction(int n1, int n2)


{
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
public static double minFunction(double n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}}

Output
Minimum Value = 6
Minimum Value = 7.3

Overloading methods makes program readable. Here, two methods are given by the same
name but with different parameters. The minimum number from integer and double types
is the result.

5.7 Method Overriding

 If a class inherits a method from its superclass, then there is a chance to override
the method provided that it is not marked final.
 The benefit of overriding is: ability to define a behavior that's specific to the
subclass type which means a subclass can implement a parent class method based
on its requirement. In object-oriented terms, overriding means to override the
functionality of an existing method.
Example:

classAnimal
{
public void move()
{
System. out. println("Animals can move");

90
Core Java Unit 2 SYBSCIT-SEM IV

}
class Dog extends Animal
{
public void move()
{
System. out. println("Dogs can walk and run");
}
public class TestDog
{
public static void main(String args[])
{
Animal a =new Animal(); // Animal reference and object
Animal b =new Dog(); // Animal reference but Dog object
a. move(); // runs the method in Animal class
b. move(); //Runs the method in Dog class
}}

Output:

Animals can move


Dogs can walk and run
 In the above example, you can see that the even though b is a type of Animal it
runs the move method in the Dog class. The reason for this is: In compile time, the
check is made on the reference type. However, in the runtime, JVM figures out the
object type and would run the method that belongs to that particular object.
Therefore, in the above example, the program will compile properly since Animal
class has the method move. Then, at the runtime, it runs the method specific for
that object.

Rules for method overriding:

• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
• The access level cannot be more restrictive than the overridden method's access level.
For example, if the superclass method is declared public, then the overriding method in
the subclass cannot be either private or protected.
• Instance methods can be overridden only if they are inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be re-declared.
• If a method cannot be inherited, then it cannot be overridden.

91
Core Java Unit 2 SYBSCIT-SEM IV

• A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
• A subclass in a different package can only override the non-final methods declared
public or protected.
• An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not. However the overriding method should not
throw checked exceptions that are new or broader than the ones declared by the
overridden method. The overriding method can throw narrower or fewer exceptions than
the overridden method.
• Constructors cannot be overridden

6. Variable Arguments

 The varrags allows the method to accept zero or muliple arguments. Before
varargs either we use overloaded method or take an array as the method parameter
but it was not considered good because it leads to the maintenance problem. If we
don't know how many argument we will have to pass in the method, varargs is the
better approach.

6.1 Advantage of Varargs:

We don't have to provide overloaded methods so less code.

Syntax of varargs:

Three dots after the data type. Syntax is as follows:

return_type method_name(data_type... variableName){}

Simple Example of Varargs in java:

class VarargsExample1
{
static void display(String... values)
{
System.out.println("display method invoked ");
}
public static void main(String args[])
{
display(); //zero argument
display("my","name","is","varargs"); //four arguments
}
}

92
Core Java Unit 2 SYBSCIT-SEM IV

Output:

display method invoked


display method invoked
Another Program of Varargs in java:

class VarargsExample2
{
static void display(String... values)
{
System.out.println("display method invoked ");
for(String s:values){
System.out.println(s);
}
}
public static void main(String args[])
{
display();//zero argument
display("hello");//one argument
display("my","name","is","varargs"); //four arguments
}
}

Output:
display method invoked
display method invoked
hello
display method invoked
my
name
is
varargs

6.2 Rules for varargs:

While using the varargs, you must follow some rules otherwise program code won't
compile. The rules are as follows:

o There can be only one variable argument in the method.


o Variable argument (varargs) must be the last argument.

93
Core Java Unit 2 SYBSCIT-SEM IV

7. Constructors

 Constructor in java is a special type of method that is used to initialize the object.
 Java constructor is invoked at the time of object creation. It constructs the values
i.e. provides data for the object that is why it is known as constructor.

7.1 Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

7.2 Types of java constructors

There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

7.2.1 Java Default Constructor:

A constructor that have no parameter is known as default constructor.

Syntax of default constructor:


<class_name>(){}

Example of default constructor

class Bike1
{
Bike1()
{
System.out.println("Bike is created");

94
Core Java Unit 2 SYBSCIT-SEM IV

}
public static void main(String args[]){
Bike1 b=new Bike1();
} }

Output:

Bike is created

7.2.2 Java parameterized constructor

A constructor that have parameters is known as parameterized constructor.


Example of Parameterized Constructor

class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}

Output:

111 Karan
222 Aryan

7.3 Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists.The compiler differentiates these

95
Core Java Unit 2 SYBSCIT-SEM IV

constructors by taking into account the number of parameters in the list and their
type.

Example of Constructor Overloading

class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

Output:

111 Karan 0
222 Aryan 25

96
Core Java Unit 2 SYBSCIT-SEM IV

7.4 Difference between constructor and method in java

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


Constructor is used to initialize the state of an Method is used to expose
object. behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default Method is not provided by
constructor if you don't have any constructor. compiler in any case.
Constructor name must be same as the class Method name may or may not
name. be same as class name.

7.5 Java Copy Constructor

There is no copy constructor in java. But, we can copy the values of one object to another
like copy constructor in C++. There are many ways to copy the values of one object into
another in java. They are:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java
constructor.

class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}
Student6(Student6 s)
{
id = s.id;

97
Core Java Unit 2 SYBSCIT-SEM IV

name =s.name;
}
void display(){System.out.println(id+" "+name);
} } }
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();

Output:

111 Karan
111 Karan

7.6 Copying values without constructor

We can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.

class Student7
{
int id;
String name;
Student7(int i,String n)
{
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);
}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

98
Core Java Unit 2 SYBSCIT-SEM IV

Output:

111 Karan
111 Karan

8. This instance in Java

1) this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

0 null 0.0
0 null 0.0

99
Core Java Unit 2 SYBSCIT-SEM IV

In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword

class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}

Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need
to use this keyword like in the following program:

9. Super Keyword in Java

 The super keyword in java is a reference variable which is used to refer


immediate parent class object.
100
Core Java Unit 2 SYBSCIT-SEM IV

 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

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


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

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}}

Output:
black
white

 In the above example, Animal and Dog both classes have a common property
color. If we print color property, it will print the color of current class by default.
To access the parent property, we need to use super keyword.

101
Core Java Unit 2 SYBSCIT-SEM IV

2) super can be used to invoke parent class method

 The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.

class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}}

Output:

eating...
barking...

102
Core Java Unit 2 SYBSCIT-SEM IV

 In the above example Animal and Dog both classes have eat() method if we call
eat() method from Dog class, it will call the eat() method of Dog class by default
because priority is given to local.
 To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

class Animal
{
Animal()
{
System.out.println("animal is created");
}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3
{
public static void main(String args[])
{
Dog d=new Dog();
}}

Output:

animal is created
dog is created

103
Core Java Unit 2 SYBSCIT-SEM IV

10. Java Member of an Inner class

 A non-static class that is created inside a class but outside a method is called
member inner class.

Syntax:

class Outer
{
//code
class Inner
{
//code
}
}

10.1 Java Member inner class example

In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.

class TestMemberOuter1
{
private int data=30;
class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

Output:

data is 30

104
Core Java Unit 2 SYBSCIT-SEM IV

11. Constants in Java

 Java does not directly support constants. However, a static final variable is
effectively a constant.
 The static modifier causes the variable to be available without loading an instance
of the class where it is defined. The final modifier causes the variable to be
unchangeable.
 Java constants are normally declared in ALL CAPS. Words in Java constants are
normally separated by underscores.
 An example of constant declaration in Java is written below:

public class MaxUnits


{
Public static final int MAX_UNITS = 25;
}

12. static fields of a class

Java static variable

 It is a variable which belongs to the class and not to object(instance)


 Static variables are initialized only once , at the start of the execution . These
variables will be initialized first, before the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn’t need any
object
 Syntax : <class-name>.<variable-name>

Java Static Method

 It is a method which belongs to the class and not to the object(instance)


 A static method can access only static data. It can not access non-static data
(instance variables)
 A static method can call only other static methods and can not call a non-static
method from it.
 A static method can be accessed directly by the class name and doesn’t need any
object
 Syntax : <class-name>.<method-name>
 A static method cannot refer to "this" or "super" keywords in anyway
 main method is static , since it must be be accessible for an application to run ,
before any instantiation takes place.

105
Core Java Unit 2 SYBSCIT-SEM IV

static block

The static block, is a block of statement inside a Java class that will be executed when a
class is first loaded in to the JVM. A static block helps to initialize the static data
members, just like constructors help to initialize instance members in java programming
language.

class Test
{
static
{ //Code goes here
}}

Questions

1. Define class in java. Explain multi-class applications with an example.


2. Explain the Scope Rules in java with an example.
3. Explain the various modifiers presents in java.
4. What is object in java? Explain its characteristics.
5. How to create object in java?
6. What are the different ways to access instance variables and methods?
7. Define Class method. How to create class method? Give example.
8. How to call method in Java? Give example.
9. Explain void keyword.
10. How to pass the parameters by value?
11. Explain the use of command line arguments.
12. Explain method overloading in java with its advantages and an example.
13. Explain Method Overriding in java with its example. What are the rules for
method overriding?
14. Define Variable arguments. Give its advantage, syntax, rules and example.
15. Explain constructors with its types and example of each.
16. Explain constructor overloading in java with an example.
17. Difference between constructor and method in java.
18. Explain java copy constructor in java with an example.
19. Explain this instance in java with an example.
20. Explain super keyword with an example.
21. Explain java inner class with an example.
22. Explain java constants, static variable and static method.

106
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Unit III

Chapter 1: Inheritance

Contents:

 Inheritance
 Derived Class Objects
 Inheritance and Access Control
 Default Base Class Constructors
 This and super keywords.
 Abstract Classes And Interfaces
 Abstract Classes
 Abstract Methods
 Interfaces
 What Is An Interface?
 How Is An Interface Different From An Abstract Class?
 Multiple Inheritance
 Default Implementation
 Adding New Functionality
 Method Implementation
 Classes V/s Interfaces
 Defining An Interface
 Implementing Interfaces.

1. Inheritance

 The mechanism of deriving the properties and methods of one class to another class
is called as inheritance.
 The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
 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.

107
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Why use inheritance in java

 Method Overriding (runtime polymorphism).


 Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

Terms used in Inheritance


 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class or extended class.
 Super Class/Parent Class/ Base Class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent class.
 Reusability: reusability is a mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class.
 extends keyword: It indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

1.1 IS-A Relationship


IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
public class Animal
{
}
public class Mammal extends Animal
{
}

public class Reptile extends Animal


{
}
public class Dog extends Mammal
{
}
Now, based on the above example, in Object-Oriented terms, the following are true −
 Animal is the superclass of Mammal class.
 Animal is the superclass of Reptile class.
 Mammal and Reptile are subclasses of Animal class.

108
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

 Dog is the subclass of both Mammal and Animal classes.


Now, if we consider the IS-A relationship, we can say −
 Mammal IS-A Animal
 Reptile IS-A Animal
 Dog IS-A Mammal
 Hence: Dog IS-A Animal as well
 Inheritance defines is-a relationship between a Super class and its Sub
class. extends and implements keywords are used to describe inheritance in Java.

1.2 Purpose of Inheritance


 It promotes the code reusabilty i.e the same methods and variables which are defined
in a parent/super/base class can be used in the child/sub/derived class.
 It promotes polymorphism by allowing method overriding.

1.3 Disadvantages of Inheritance


 Main disadvantage of using inheritance is that the two classes (parent and child
class) gets tightly coupled.
 This means that if we change code of parent class, it will affect to all the child
classes which is inheriting/deriving the parent class, and hence, it cannot be
independent of each other.

2. Derived Class Objects in Java

 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.
 In the terminology of Java, a class which is inherited is called parent or super class
and the new class is called child or subclass.
 Following is an example demonstrating Java inheritance. In this example, you can
observe two classes namely Calculation and My_Calculation.
 Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.

109
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Example:

class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y)


{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation
{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}}

110
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

3. Access Control

Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −
 Visible to the package, the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

3.1 Default Access Modifier - No Keyword


Default access modifier means we do not explicitly declare an access modifier for a class,
field, method, etc. A variable or method declared without any access control modifier is
available to any other class in the same package. The fields in an interface are implicitly
public static final and the methods in an interface are by default public. In this example, we
have created two packages pack and mypack. We are accessing the A class from outside its
package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java
package pack;
class A
{
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();//Compile Time Error
obj.msg();//Compile Time Error
} }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

111
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

3.2 Private Access Modifier - Private


 Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
 Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
 Variables that are declared private can be accessed outside the class, if public getter
methods are present in the class.
 Using the private modifier is the main way that an object encapsulates itself and
hides data from the outside world.
 In this example, we have created two classes A and Simple. A class contains private
data member and private method. We are accessing these private members from
outside the class, so there is compile time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
} }

3.3 Public Access Modifier - Public


 A class, method, constructor, interface, etc. declared public can be accessed from
any other class. Therefore, fields, methods, blocks declared inside a public class can
be accessed from any class belonging to the Java Universe.
 However, if the public class we are trying to access is in a different package, then the
public class still needs to be imported. Because of class inheritance, all public
methods and variables of a class are inherited by its subclasses.

Example of public access modifier

//save by A.java

package pack;
public class A
{
public void msg()

112
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

{
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

3.4 Protected Access Modifier - Protected


 Variables, methods, and constructors, which are declared protected in a superclass
can be accessed only by the subclasses in other package or any class within the
package of the protected members' class.
 The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in a interface cannot be
declared protected.
 Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.
 In this example, we have created the two packages pack and mypack. The A class of
pack package is public, so can be accessed from outside the package. But msg
method of this package is declared as protected, so it can be accessed from outside
the class only through inheritance.

//save by A.java

package pack;
public class A {
protected void msg() {
System.out.println("Hello");
}}

//save by B.java

package mypack;
import pack.*;
class B extends A {
public static void main(String args[]) {

113
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

B obj = new B();


obj.msg();
} }

Output: Hello

Let's understand the access modifiers by a simple table.

Access within within outside package by outside


Modifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

4. Access Control and Inheritance


The following rules for inherited methods are enforced −
 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
 Methods declared private are not inherited at all, so there is no rule for them.

4.1 Types of Inheritance

 Single Inheritance
 Multiple Inheritance (Through Interface)
 Multilevel Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Example: Inheritence

File Name: Employee.java

class Employee
{
float salary=40000;
}

File Name: Programmer.java

class Programmer extends Employee // sub class inheriting Employee class


{

114
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary); // property of base class
System.out.println("Bonus of Programmer is:"+p.bonus);
} }

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Employee.java
D:\Core Java\Abstract class and Interface>javac Programmer.java
D:\Core Java\Abstract class and Interface>java Programmer
Programmer salary is:40000.0
Bonus of programmer is:10000

4.2 Single Inheritance

Single Inheritance is the simple inheritance of all, When a class extends another class(Only
one class) then we call it as Single inheritance. The below diagram represents the single
inheritance in java where Class B extends only one class Class A. Here Class B will be
the Sub class and Class A will be one and only Super class.

File Name: Animal.java

class Animal
{
void eat()
{
System.out.println("eating...");
}
}

File Name: Dog.java

class Dog extends Animal // Single Inheritance


{
void bark()
{
System.out.println("barking...");
}
}

115
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

File Name: TestInheritance.java

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

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac TestInheritance.java
D:\Core Java\Abstract class and Interface>java TestInheritance
barking...
eating...

Example 2:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
ClassB b = new ClassB(); //Assigning ClassB object to ClassB reference
b.dispA(); //call dispA() method of ClassA
b.dispB(); //call dispB() method of ClassB
}}

Output :
disp() method of ClassA
disp() method of ClassB

116
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

4.3 Multilevel Inheritance

In Multilevel Inheritance a derived class will be inheriting a parent class and as well as
the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassBact as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.

File Name: Animal.java


class Animal
{
void eat()
{
System.out.println("eating...");
} }

File Name: Dog.java


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

File Name: BabyDog.java


class BabyDog extends Dog // Multilevel inheritance
{
void weep()
{
System.out.println("weeping...");
} }

File Name: TestInheritance2.java


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

117
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac BabyDog.java
D:\Core Java\Abstract class and Interface>javac TestInheritance2.java
D:\Core Java\Abstract class and Interface>java TestInheritance2
weeping...
barking...
eating...

Example 2:

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
ClassC c = new ClassC(); //Assigning ClassC object to ClassC reference
c.dispA(); //call dispA() method of ClassA
c.dispB(); //call dispB() method of ClassB
c.dispC(); //call dispC() method of ClassC
}}

Output:

disp() method of ClassA


disp() method of ClassB
disp() method of ClassC

118
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

4.4 Hierarchical Inheritance

In Hierarchical inheritance one parent class will be inherited by many sub classes. As per
the below example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will
be acting as a parent class for ClassB, ClassC and ClassD.

File Name: Animal.java


class Animal
{
void eat()
{
System.out.println("eating...");
} }

File Name: Dog.java


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

File Name: Cat.java


class Cat extends Animal // Hierarchical inheritance
{
void meow()
{
System.out.println("meowing...");
}}

File Name: TestInheritance3.java


class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}}

119
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac Cat.java
D:\Core Java\Abstract class and Interface>javac TestInheritance3.java
D:\Core Java\Abstract class and Interface>java TestInheritance3
meowing...
eating...

Example 2:

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
ClassB b = new ClassB(); //Assigning ClassB object to ClassB reference
b.dispB(); //call dispB() method of ClassB
b.dispA(); //call dispA() method of ClassA
ClassC c = new ClassC() //Assigning ClassC object to ClassC reference
c.dispC(); //call dispC() method of ClassC

120
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

c.dispA(); //call dispA() method of ClassA


ClassD d = new ClassD(); //Assigning ClassD object to ClassD reference
d.dispD(); //call dispD() method of ClassD
d.dispA(); //call dispA() method of ClassA
}}

Output:

disp() method of ClassB


disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA

4.5 Multiple Inheritance in Java

Multiple Inheritance is nothing


but one class extending more than one
class. Multiple Inheritance is basically not
supported by many Object Oriented
Programming languages such as Java,
Small Talk, C# etc.. (C++ Supports
Multiple Inheritance). As the Child class
has to manage the dependency of more than
one Parent class. But you can achieve
multiple inheritance in Java using Interfaces.

Example:

interface Car
{
int speed=60;
public void distanceTravelled();
}
interface Bus
{
int distance=100;
public void speed();
}
public class Vehicle implements Car,Bus
{
int distanceTravelled;
int averageSpeed;
public void distanceTravelled()

121
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

{
distanceTravelled=speed*distance;
System.out.println("Total Distance Travelled is : "+distanceTravelled);
}
public void speed()
{
int averageSpeed=distanceTravelled/speed;
System.out.println("Average Speed maintained is : "+averageSpeed);
}
public static void main(String args[])
{
Vehicle v1=new Vehicle();
v1.distanceTravelled();
v1.speed();
}
}
Output :

Total Distance Travelled is : 6000


Average Speed maintained is : 100

4.6 Hybrid Inheritance in Java

Hybrid Inheritance is the combination of both


Single and Multiple Inheritance. Again Hybrid
inheritance is also not directly supported in Java
only through interface we can achieve this. Flow
diagram of the Hybrid inheritance will look like
below. As you can ClassA will be acting as
the Parent class for ClassB & ClassC and ClassB
& ClassC will be acting as Parent for ClassD.

Implementation of Hybrid Inheritance with Classes

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public class ClassB extends ClassA
{
public void show()
{
System.out.println("show() method of ClassB");

122
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

}
public void dispB()
{
System.out.println("disp() method of ClassB");
}}
public class ClassC extends ClassA
{
public void show()
{
System.out.println("show() method of ClassC");
}
public void dispC()
{
System.out.println("disp() method of ClassC");
}}
public class ClassD extends ClassB,ClassC
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
public static void main(String args[])
{
ClassD d = new ClassD();
d.dispD();
d.show();//Confusion happens here which show method to call
}}

Output:

Error!!

Implementation of Hybrid Inheritance with Interfaces

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}}
public interface InterfaceB
{
public void show();
}
public interface InterfaceC
{

123
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

public void show();


}
public class ClassD implements InterfaceB,InterfaceC
{
public void show()
{
System.out.println("show() method implementation");
}
public void dispD()
{
System.out.println("disp() method of ClassD");
}
public static void main(String args[])
{
ClassD d = new ClassD();
d.dispD();
d.show();
}}

Output:

disp() method of ClassD


show() method implementation

4.7 Inheritance and Access Control

In Java, we have access specifiers: private, public, protected and default. Effect of these
access specifiers are as follows:

Private Protected Public Default

Same class

Same package’s derived class


Same package’s non – derived
class
Different package’s derived class
Different package’s non – derived
class

124
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

5. Default Base Class Constructors

 A derived Java class does not inherit a constructor from its base class.
 If a base class has a default constructor, i.e., a constructor with no arguments, then
that constructor is automatically called when a derived class is instantiated if the
derived class has its own default constructor.
 A default constructor is automatically provided by the compiler.

6. this and super keywords

A. this keyword
 this keyword is used in the following cases:
o this can be used to refer current class instance variable.
o this can be used to invoke current class method (implicitly)
o this() can be used to invoke current class constructor.
o this can be passed as an argument in the method call.
o this can be passed as argument in the constructor call.
o this can be used to return the current class instance from the method.

Example 1: this keyword refers current class instance variable.

File Name: Student.java


class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno; // this refers current class instance variable.
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}

125
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

File Name: TestThis1.java


class TestThis1{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac Student.java
D:\Core Java\Abstract class and Interface>javac TestThis1.java
D:\Core Java\Abstract class and Interface>java TestThis1
111 ankit 5000
112 sumit 6000

Example 2: this keyword refers current class constructor

File Name: A.java


class A
{
A()
{
this(5); // this refers current class constructor
System.out.println("hello a");
}
A(int x) {
System.out.println(x);
} }

File Name: TestThis2.java


class TestThis2 {
public static void main(String args[]) {
A a=new A();
} }
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac A.java
D:\Core Java\Abstract class and Interface>javac TestThis2.java
D:\Core Java\Abstract class and Interface>java TestThis2
5
hello a
126
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

B. super keyword
 super keyword is used in the following cases:
o super can be used to refer immediate parent class instance variable.
o super can be used to invoke immediate parent class method.
o super() can be used to invoke immediate parent class constructor.

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

File Name: Animal.java


class Animal
{
String color="white";
}

File Name: Dog.java


class Dog extends Animal
{
String color="black";
void printColor() {
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal
class
} }

File Name: TestSuper1.java


class TestSuper1
{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac TestSuper1.java
D:\Core Java\Abstract class and Interface>java TestSuper1
black
white

127
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Example 2: super can be used to invoke parent class method

File Name: Animal.java


class Animal{
void eat(){
System.out.println("eating...");
} }

File Name: Dog.java


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

File Name: TestSuper2.java


class TestSuper2 {
public static void main(String args[]) {
Dog d=new Dog();
d.work();
}}
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac TestSuper2.java
D:\Core Java\Abstract class and Interface>java TestSuper2
eating...
barking...

Example 3: super is used to invoke parent class constructor.

File Name: Animal.java


class Animal{
Animal(){

128
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

System.out.println("animal is created");
} }

File Name: Dog.java


class Dog extends Animal {
Dog(){
super();
System.out.println("dog is created");
} }

File Name: TestSuper3.java


class TestSuper3 {
public static void main(String args[]) {
Dog d=new Dog();
} }
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac Animal.java
D:\Core Java\Abstract class and Interface>javac Dog.java
D:\Core Java\Abstract class and Interface>javac TestSuper2.java
D:\Core Java\Abstract class and Interface>java TestSuper2
animal is created
dog is created

6. Abstract Classes and Interfaces:

 Abstraction is a process of hiding the implementation details and showing only


functionality to the user.
 For example, sending SMS where you type the text and send the message. You
don't know the internal processing about the message delivery.
 Advantages of Abstraction:
o It shows only essential things to the user and hides the internal details.
o Abstraction lets you focus on what the object does instead of how it does it.
 There are two ways to achieve abstraction in java : -
o Abstract class
o Interface

7. Abstract Classes

 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.
 It needs to be extended and its method implemented.
129
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

 It cannot be instantiated.
 It can have constructors and static methods.
 It can have final methods which will force the subclass not to change the body of the
method.

Example abstract class

abstract class A{}

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

7.1 Abstract Methods

 A method which is declared as abstract and does not have implementation is known
as an abstract method.
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the parent
class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method
declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semoi colon (;) at the end.

Example abstract method

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

File Name: Bike.java

abstract class Bike


{
abstract void run(); //no method body and abstract
}

130
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

File Name: Honda.java

class Honda extends Bike


{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
} }
To compile and run the file on command prompt:
D:\Core Java\Abstract class and Interface>javac Honda.java
D:\Core Java\Abstract class and Interface>java Honda
running safely..

Example 2:
abstract class Shape
{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by 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();
s.draw();
} }
131
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

Output:

drawing circle

Note: An abstract class can have data member, abstract method, method body, constructor
and even main() method.

8. Interfaces:

 An interface is a reference type in Java. It is similar to class with a collection of


abstract methods.
 It has static constants and abstract methods. It cannot have a method body.
 The interface in Java is a mechanism to achieve abstraction and multiple
inheritance in Java.
 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.

An interface is similar to a class in the following ways −


An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
However, an interface is different from a class in several ways, including −
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

132
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

8.1 What is An Interface?

 An Interface is a reference type which has only non-abstract methods.


 Advantages:
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.
8.2 Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare
an interface −
interface interface_name
{
// Any number of final, static fields
// Any number of abstract method declarations
}

Bank Example:
This example provides the implementation of Bank interface.

File Name: Bank.java


interface Bank{
float rateOfInterest();
}

File Name: SBI.java


class SBI implements Bank{
public float rateOfInterest()
{
return 9.15f;
}}

File Name: PNB.java


class PNB implements Bank{
public float rateOfInterest()
{
return 9.7f;
}}

133
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

File Name: TestInterface.java


class TestInterface{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Bank.java
D:\Core Java\Abstract class and Interface> javac SBI.java
D:\Core Java\Abstract class and Interface> javac PNB.java
D:\Core Java\Abstract class and Interface> javac TestInterface.java
D:\Core Java\Abstract class and Interface> java TestInterface
ROI: 9.15

9. How Is An Interface Different From An Abstract Class?

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since 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- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
8) An abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

134
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

10. Multiple Inheritance, Default Implementation, Adding New Functionality,


Method Implementation

 If a class implements multiple interfaces, or an interface extends multiple interfaces,


it is known as multiple inheritance.
 Multiple inheritance is not supported through class in java, but it is possible by an
interface

File Name: Printable.java


interface Printable{
void print();
}

File Name: Showable.java


interface Showable{
void print();
}

File Name: TestInterface3.java


class TestInterface3 implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
TestInterface3 obj = new TestInterface3();
obj.print();
} }

To compile and run the file on command prompt:


D:\Core Java\Abstract class and Interface>javac Printable.java
D:\Core Java\Abstract class and Interface> javac Showable.java
D:\Core Java\Abstract class and Interface> javac TestInterface3.java
D:\Core Java\Abstract class and Interface> java TestInterface3
Hello

135
Core Java Unit III-Chapter 1 SYBSCIT-SEM IV

11. Classes v/s Interfaces

Class Interface
1) In a class, we can only define member In an interface, we can only declare
functions, we cannot declare them. member functions, we cannot define them.
2) In a class, the data members are by In an interface, the data members are by
default non static. default final and static.
3) In a class, static member functions can In an interface, static member functions are
be defined. not allowed.
4) Objects of a class can be created Objects of an interface cannot be created
5) Constructors in a class can be defined. Constructors in an interface cannot be
defined.
6) A class cannot extend multiple classes. An interface can multiple classes.

Questions

1. Define Inheritance. Why we use inheritance? Give its syntax and terms used.
2. Explain IS-A relationship with an example. Give purpose and disadvantages of
Inheritance.
3. Explain Derived class objects in java with an example.
4. Explain the different access modifiers with an example.
5. Explain Single and Multilevel inheritance with its example.
6. Explain Hierarchical Inheritance with an example.
7. Explain Hybrid Inheritance with an example.
8. Explain Multiple Inheritance with an example.
9. Explain this and super keywords with an example.
10. Explain abstract class with its syntax and example.
11. Explain abstract method with its syntax and example.
12. Explain Interfaces in detail. How to declare interfaces? Give example.
13. How Is An Interface Different From An Abstract Class?
14. Differentiate between Classes v/s Interfaces.

136
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

UNIT III
Chapter 2: Packages

Contents

 Creating Packages
 Default Package
 Importing Packages
 Using a Package.

1. Introduction

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

1.1 Advantage of Java Package

 Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
 Java package provides access protection.
 Java package removes naming collision.

 Programmers can define their own packages to bundle group of classes/interfaces,


etc. It is a good practice to group related classes implemented by you so that a
programmer can easily determine that the classes, interfaces, enumerations, and
annotations are related.

137
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

 Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it
is also easier to locate the related classes.

2. Creating Packages

 A java package is a group of similar types of classes, interfaces and sub-


packages.
 Package in java can be categorized in two form:
o built-in package and user-defined package.
 Built - in packages are pre defined packages in java.
Eg: as java, lang, awt, javax, swing, net, io, util, sql etc.
 User - defined packages are those packages that are created by programmers to
bundle group of classes/interfaces, etc.

2.1 The Directory Structure of Packages


Two major results occur when a class is placed in a package −
 The name of the package becomes a part of the name of the class, as we just
discussed in the previous section.
 The name of the package must match the directory structure where the corresponding
bytecode resides.

File Name: PackageDemo.java


package mypack;
public class PackageDemo
{
public static void main(String args[])
{
System.out.println("Welcome to packages");
} }

To compile the file on command prompt:


D:\Core Java\Packages>javac -d . PackageDemo.java

The -d switch specifies the destination where to put the generated class file. In our case it
will create a package / folder named mypack and place the PackageDemo.class file inside
it.

To run the file on command prompt:


D:\Core Java\Packages>java mypack.PackageDemo
Welcome to packages

You need to use fully qualified package name e.g. mypack. PackageDemo to run the
class.

138
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

2. Default Package

There are three packages that are imported by default for each source file in java.
1. package with no name
2. java.lang package
3. current package (the package in which the current file is defined)

package with no name


 If you omit the package statement while writing the class definition, then the class
name is placed inside a default package, which has no name.
 Java compiler automatically imports this package.
Java.lang package
 Java is a pure object oriented programming language where code is written in form
of classes.
 These class components (known as types) are built-in or primitive types and types
5from components.
 Primitive types can be used directly while component types must usually be ordered
from a library by importing them from the appropriate package.
 The Java standard libraries include java.lang package by default, which contains a
number of components that are used very commonly in Java programs.
 However, you can import the same package explicitly also.
Current package
 The current package is the one in which the class in execution is defined.
 Current Java package is automatically imported by Java compiler.

3. Importing Packages and Using a Package


 The import keyword is used to make the classes and interface of another package
accessible to the current package.
 There are three ways to import the package from outside the package.
1. import package.*;
2. import package.classname;
3. using fully qualified name

Using package.*
 If you use package.* then all the classes and interfaces inside this package will be
accessible but not subpackages.

File Name: A.java


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

139
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

File Name: B.java


package mypack;
import pack.*; // Using packagename.*
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
} }

To compile and run the file on command prompt:

D:\Core Java\Packages>javac -d . A.java


D:\Core Java\Packages>javac -d . B.java
D:\Core Java\Packages>java mypack.B
Hello

Using packagename.classname

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

File Name: A.java


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

File Name: B.java


package mypack;
import pack.A; // Using packagename.classname
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
} }

To compile and run the file on command prompt:


D:\Core Java\Packages>javac -d . A.java
D:\Core Java\Packages>javac -d . B.java
D:\Core Java\Packages>java mypack.B
Hello

140
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

In Java, we have access specifiers : private, public, protected and default. Effect of these
access specifiers are as follows:

Using fully qualified name


 If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Example of package by import fully qualified name

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

Sequence of the program must be package then import then class.

141
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

4. Default Packages

 These packages consists of a large number of classes which are a part of


Java API. For e.g, we have used java.io package previously which contain
classes to support input / output operations in Java. Similarly, there are other
packages which provides different functionality.
 Some of the commonly used built-in packages are shown in the table below :

Package Description
Name
java.lang Contains language support classes ( for e.g classes which defines primitive data types,
math operations, etc.) . This package is automatically imported.
java.io Contains classes for supporting input / output operations.
java.util Contains utility classes which implement data structures like Linked List, Hash Table,
Dictionary, etc and support for Date / Time operations.
java.applet Contains classes for creating Applets.
java.awt Contains classes for implementing the components of graphical user interface ( like
buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.

Example:

import java.lang.Math; // import 'Math' class


public class ImportDemo
{
public static void main(String args[])
{
double val = 64.0;
double sqroot = Math.sqrt(val); // Access sqrt() method using classname
System.out.println("Sq. root of " + val + " is " + sqroot);
}}

Private Protected Public Default

Same class

Same package’s derived class


Same package’s non – derived
class
Different package’s derived class
Different package’s non – derived
class

142
Core Java Unit III – Chapter 2 SYBSCIT-SEM IV

Questions

1. Define packages. Give its advantages. How to create packages in java?


2. Explain the directory structure of packages with package compilation and its running
environment.
3. Explain the default packages in java.
4. How to import packages to give access to the classes and interfaces of other
packages?

143
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Unit IV
Chapter 1 – Enumerations and Arrays

Contents

 Two Dimensional Arrays,


 Multi-Dimensional Arrays,
 Vectors,
 Adding Elements To A Vector,
 Accessing Vector Elements,
 Searching For Elements In A Vector,
 Working With The Size of The Vector.

1. Enumerations

Enumeration is part of Java language since JDK5. Enumeration literally means


“the action of mentioning a number of things one by one” or “a symbolic name for
a set of values”. In Java Enumeration means “a group of named constant” or “list
of named constant”.

1.1 Objective of Enumeration in Java:

1. Enumeration is treated as data types consisting of a set of named values called


elements, members, enumeral, or enumerators of the type.
2. In Java, enumeration defines a class type.
3. Java enums are more powerful than C/C++ enums
4. In Java, we can also add variables, methods and constructors to it.
5. The major objective of enum is to define own data types (Enumerated Data
Types).

Example:
Natural enumerated types :
a. Planets
b. Days of week
c. Colours
d. Directions

1.2 How to Define and Use an Enumeration :Declaration of enum in Java


There are two ways in which enum declaration can be done
1. Enum declaration can be done outside a Class
OR
2. Enum declaration can be done inside a Class but not inside a Method

144
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

A simple enum example where enum is declared outside any class (We have used
enum keyword instead of class keyword)

Declaration:
enumColor
{
RED, GREEN, BLUE;
}

Example 1: Java Code:


public class Test
{
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}}

Output: RED

Example 2: A simple enum example where Enum declaration can be done inside a
Class but not inside a Method

Java Code:
public class Test
{
enumColor
{
RED, GREEN, BLUE;
}
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}}

Output: RED

1.3 Important points of enum:


1. Every enum internally implemented by using Class.
2. Every enum constant represents an object of type enum.
3. enum type can be passed as an argument to switch statement.
4. Every enum constant is always implicitly public static final. Since it is
static, we can access it by using enum Name. Since it is final, we can’t
create child enums.

145
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

5. We can declare main() method inside enum. Hence we can invoke enum
directly from the Command Prompt.
6. A Java program to demonstrate that we can have main() inside enum class.
7. values(), ordinal() and valueOf() methods :These methods are present inside
java.lang.Enum.
a. values() method can be used to return all values present inside enum.
Order is important in enums.
b. By using ordinal() method, each enum constant index can be found,
just like array index.
c. valueOf() method returns the enum constant of the specified string
value, if exists.

Example 1: A Java program to demonstrate working on enum in switch

import java.util.Scanner;
enum Day // An Enum class
{
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY;
}
public class Test // Driver class that contains an object of "day" and main().
{
Day day;
public Test(Day day) // Constructor
{
this.day = day;
}
public void dayIsLike() // Prints a line about Day using switch
{
switch (day)
{
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
} }
public static void main(String[] args) // Driver method

146
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

{
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}}

OUTPUT:

Example 2:

enumColor
{
RED, GREEN, BLUE;
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}}

Example 3: Java program to demonstrate working of values(), ordinal() and


valueOf()

numColor
{
RED, GREEN, BLUE;
}
class Test
{
public static void main(String[] args)
{
Color arr[] = Color.values(); // Calling values()
for (Color col : arr) // enum with loop
{
// Calling ordinal() to find index of color.
System.out.println(col + " at index " + col.ordinal());
}

147
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

// Using valueOf(). Returns an object of Color with given constant.


Uncommenting second line causes exception ,IllegalArgumentException
System.out.println(Color.valueOf("RED"));
// System.out.println(Color.valueOf("WHITE"));
} }

Output:

enum and methods: enum can contain concrete methods only i.e. no any abstract
method.

Example 4: Java program to demonstrate that enums can have constructor and
concrete methods. An enum (Note enum keyword in place of class keyword)

enumColor
{
RED, GREEN, BLUE;
privateColor() // enum constructor called separately for each constant
{
System.out.println("Constructor called for : " +
this.toString());
}
public void colorInfo() // Only concrete (not abstract) methods allowed
{
System.out.println("Universal Color");
}}
public class Test
{
public static void main(String[] args) // Driver method
{
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}}

Output:

148
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

1.4 Points to remember about Enumerations:

1. Enumerations are of class type, and have all the capabilities that a Java class
has.
2. Enumerations can have Constructors, instance Variables, methods and can
even implement Interfaces.
3. Enumerations are not instantiated using new keyword.
4. All Enumerations by default inherit java.lang.Enum class.

2. Arrays:

Array literally means “an ordered series or arrangement”. In Java an Array is a


dynamically-created object that serves as a container to hold constant number of
values of the same type.

Following are the properties of arrays as accepted by the Java compiler.


1. Arrays stores similar data types which means array can hold data of same
data type values. This is one of the limitations of arrays compared to other
data structures.
2. Each value stored, in an array, is known as an element and all elements are
indexed. The first element added, by default, gets 0 index. That is, the 5th
element added gets an index number of 4.
3. Elements can be retrieved by their index number.
4. Array elements are stored in contiguous (continuous) memory locations.
5. Once array is created, its size is fixed and at runtime if required, more
elements cannot be added. One of the limitation of arrays compared to other
data structures.
6. One array name can represent multiple values. Array is the easiest way to
store a large quantity of data of same data types.
For example: to store the salary of 100 employees, it is required to declare 100
variables. But with arrays, with one array name all the 100 employees salaries
can be stored.
7. Arrays can be multidimensional.
8. At the time of creation itself, array size should be declared (array
initialization does not require size).
9. In Java, arrays are predefined objects and with the help of methods
elements of array can be manipulated.
10. As Java does not support garbage values, unassigned elements are given
default values; the same values given to unassigned instance variables.

149
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

11. Instead of declaring individual variables, such as number0, number1, ...,


and number99, you declare one array variable such as numbers and use
numbers[0], numbers[1], and ..., numbers[99] to represent individual
variables.
12. Normally, array is a collection of similar type of elements that have
contiguous memory location.
13. Java array is an object the 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.
14. Array in java is index based, first element of the array is stored at 0 index.

2.1 Advantage of Java Array

o Code Optimization: It makes the code optimized, we can retrieve or sort the
data easily.
o Random access: We can get any data located at any index position.

2.2 Disadvantage of Java Array

o Size Limit: We can store only fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
java.

Question: please why do we need an array in programming?


Answer: The answer is the same as why do you require a data structure in a
programming language. Array is special type of Data Structure.

2.3 Exploring Array in Java

Declaring Array and it’s Index

Question 1: How to declare an array?


Answer: Here's how you can declare an array in Java:

dataType[] arrayName;

Here, dataType can be a primitive data type like: int, char, Double, byte etc. or an
object arrayNameis an identifier.

Let's take the above example again.

Double[] data;

Here, data is an array that can hold values of type Double.

150
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Question 2: How many elements can array this hold?


Answer: The next step is to allocate memory for array elements.

data = new Double[10];

The length of data array is 10 which means , it can hold 10 elements


(10 Double values in this case).

 Note: once the length of the array is defined, it cannot be changed in the
program.

Let's take another example:

int[] age;
age = new int[5];

Here, age array can hold 5 values of type int. It's possible to define and allocate
memory of an array in one statement. You can replace two statements above with a
single statement.

int[] age = new int[5];

2.4 Accessing Java Array Index

You can access elements of an array by using indices. Let's consider previous
example.

int[] age = new int[5];

Java array index

1. The first element of array is age[0], second is age[1] and so on.


2. If the length of an array is n, the last element will be arrayName[n-1].
3. Since the length of age array is 5, the last element of the array is age[4] in
the above example.
4. The default initial value of elements of an array is 0 for numeric types and
false for boolean.

151
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Let’s explain this with the help of a program:

classArrayExample
{
public static void main(String[] args)
{
int[] age = new int[5];
System.out.println(age[0]);
System.out.println(age[1]);
System.out.println(age[2]);
System.out.println(age[3]);
System.out.println(age[4]);
}}

Output:

Example: Java Program to illustrate how to declare, instantiate, initializes and


traverse the java Array.
classTestarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}}

Output:

Example: Java Program for Declaration, Instantiation and Initialization of


Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};
152
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Let's see the simple example to print this array.


class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5}; //declaration, instantiation and initialization
for(int i=0;i<a.length;i++) //printing array
System.out.println(a[i]); //length is the property of array
}}

Output:

3. Types of Arrays in Java

A. Two Dimensional Arrays

1. In Java, a table may be implemented as a 2D array.


2. Each cell of the array is a variable that can hold a value and works like any
variable. As with one dimensional arrays, every cell in a 2D array is of the
same type.
3. The type can be a primitive type or an object reference type.
4. Important: Each cell of the array is specified with a row and column number, in
that order.
5. Assume that gradeTable is a 2D array of int, and that (conceptually) it looks
like the table given below

153
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Then,
gradeTable[ 0 ][ 1 ] // holds 42
gradeTable[ 3 ][ 4 ] // holds 93
gradeTable[ 6 ][ 2 ] // holds 78

The subscripted variables are used in assignment statements and arithmetic


expressions just like any variable:

gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1.


gradeTable[ 3 ][ 4 ]++ ; // increments the value at row 3 column 4.
int value = (gradeTable[ 6 ][ 2 ] + 2) / 2 ; // puts 40 into value

Example: Two Dimensional Array Program

In a two-dimensional, or "2D," array, the elements can be arranged in rows and


columns. Here, for example, is a 2D array of integer that has five rows and seven
columns:
An array of its with 5 rows and 7 columns:

5-by-7 grid contains a total of 35 elements


(Logical structure of the 2DArray)

 The rows in a 2D array are numbered 0, 1, 2, ..., up to the number of rows


minus one. Similarly, the columns are numbered from zero up to the number of
columns minus one. Each individual element in the array can be picked out by
specifying its row number and its column number.
 In Java, the syntax for two-dimensional arrays is similar to the syntax for one-
dimensional arrays,except that an extra index is involved, since picking out an
element requires both a row number and a column number.
For example,
1. If A is a 2D array of int, then A[3][2] would be the element in row 3, column 2.
2. That would pick out the number 17 in the array shown above.
3. The type for A would be given as int[][], with two pairs of empty brackets.
4. To declare the array variable and create the array, you could say,

int[][] A;
A = new int[5][7];

154
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

3.1 How to work with 2D Array in Java


Two dimensional array can be made in Java Programming language by using the two
loops, the first one is outer loop and the second one is inner loop. Outer loop is
responsible for rows and the inner loop is responsible for columns. And both rows and
columns combine to make two-dimensional (2D) Arrays.

Example of 2D java array

class Testarray3
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array
for(int i=0;i<3;i++) //printing 2D array
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
} }}

Output:
123
245
445

Example: Java Programming Code for Two Dimensional (2D) Array

import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)

155
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

{
arr[i][j] = scan.nextInt();
} }
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}}}

Output:

Note:
Two-dimensional arrays are sometimes useful, but they are much less common than
one-dimensional arrays. Java actually allows arrays of even higher dimension, but
they are only rarely encountered in practice.

3.3 Multi-Dimensional Arrays,


A multidimensional array is a nested array; an array within an array. In Java, you can
declare an array of arrays known as multidimensional array. So with multidimensional
array we are entering another dimension, a multidimensional array in Java is an array
within an array.
Creating Multidimensional Arrays
The basic steps for creating multidimensional arrays are:
1. Declare the array
2. Allocate space for the multidimensional array
To declare an array, you need to tell it what type it is.
We can think of declaring a variable; it's the same concept. You need to tell Java if it's
dealing with strings, numbers, or objects.
The syntax for creating a two-dimensional array is:
data type [ ] [ ] arrayName;
Let's say we have a simple table of integer values; it would be declared thus:
int [ ] [ ] table;

156
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

3.4 Passing Array to method in java

We can pass the java array to method so that we can reuse the same logic on any
array. Let's see the simple example to get minimum number of an array using method.

class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}}

Output: 3

3.5 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.
3.5.1 for loop: Example

public class TestArray


{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++) // Print all the array elements
{
System.out.println(myList[i] + " ");
}
double total = 0; // Summing all elements
for (int i = 0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is " + total);

157
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

double max = myList[0];


for (int i = 1; i < myList.length; i++)
{
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}}
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

3.5.2 The foreach Loops


JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop,
which enables you to traverse the complete array sequentially without using an index
variable.
Example

public class TestArray


{

public static void main(String[] args)


{
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (double element: myList) // Print all the array elements
{
System.out.println(element);
} } }
Output
1.9
2.9
3.4
3.5

3.6 Copying a java array

We can copy an array to another by the arraycopy method of System class.

158
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Syntax of array copy method

public static void arraycopy


(
Object src, int srcPos,Object dest, int destPos, int length
)

Example of array copy method

class TestArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
} }

Output: caffein

4. Vectors
 Vectors (the java.util.Vector class) are commonly used instead of arrays,
because they expand automatically when new data is added to them.
 The Vector class implements a growable array of objects. Like an array, it
contains components that can be accessed using an integer index. However, the
size of a Vector can grow or shrink as needed to accommodate adding and
removing items after the Vector has been created.
 Each vector tries to optimize storage management by maintaining a capacity
and a capacityIncrement. The capacity is always at least as large as the vector
size; it is usually larger because as components are added to the vector, the
vector's storage increases in chunks the size of capacityIncrement. An
application can increase the capacity of a vector before inserting a large
number of components; this reduces the amount of incremental reallocation.
Java Vector Class Declaration
public class Vector<E>
extends Object<E>
implements List<E>, Cloneable, Serializable

4.1 Java Vector Class Constructors

Vector class supports four types of constructors. These are:

159
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

SN Constructor Description
1) vector() It constructs an empty vector with the default
size as 10.
2) vector(int initialCapacity) It constructs an empty vector with the
specified initial capacity and with its capacity
increment equal to zero.
3) vector(int initialCapacity, int It constructs an empty vector with the
capacityIncrement) specified initial capacity and capacity
increment.
4) Vector( Collection<? extends E> c) It constructs a vector that contains the
elements of a collection c.

4.2 Java Vector Class Methods

Method Description
add() It is used to append the specified element in the given vector.
addAll() It is used to append all of the elements in the specified collection
to the end of this Vector.
addElement() It is used to append the specified component to the end of this
vector. It increases the vector size by one.
capacity() It is used to get the current capacity of this vector.
clear() It is used to delete all of the elements from this vector.
clone() It returns a clone of this vector.
contains() It returns true if the vector contains the specified element.
containsAll() It returns true if the vector contains all of the elements in the
specified collection.
copyInto() It is used to copy the components of the vector into the specified
array.
firstElement() It is used to get the first component of the vector.

forEach() It is used to perform the given action for each element of the
Iterable until all elements have been processed or the action
throws an exception.
indexOf() It is used to get the index of the first occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
insertElementAt() It is used to insert the specified object as a component in the
given vector at the specified index.

160
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

isEmpty() It is used to check if this vector has no components.

lastElement() It is used to get the last component of the vector.

lastIndexOf() It is used to get the index of the last occurrence of the specified
element in the vector. It returns -1 if the vector does not contain
the element.
remove() It is used to remove the specified element from the vector. If the
vector does not contain the element, it is unchanged.
removeAll() It is used to delete all the elements from the vector that are
present in the specified collection.
replaceAll() It is used to replace each element of the list with the result of
applying the operator to that element.
setSize() It is used to set the size of the given vector.

size() It is used to get the number of components in the given vector.

sort() It is used to sort the list according to the order induced by the
specified Comparator.

4.2 Adding Elements to A Vector

Java program to add elements to Vector

import java.util.*;
class VectorExample
{
public static void main(String args[])
{
Vector<String> vec = new Vector<String>(4);
vec.add("Sunday"); //Adding elements to a vector
vec.add("Monday");
vec.add("Tuesday");
vec.add("Wednesday");
System.out.println("Size is: "+vec.size()); //Check size and capacity
System.out.println("Default capacity is: "+vec.capacity());
System.out.println("Vector element is: "+vec); //Display Vector elements
vec.addElement("Thursday");
vec.addElement("Friday");
vec.addElement("Saurday");
System.out.println("Size after addition: "+vec.size());
System.out.println("Capacity after addition is: "+vec.capacity());

161
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

System.out.println("Elements are: "+vec);


}}

4.3 Accessing Vector Elements

4.3.1 Searching For Elements in a Vector:

Program to search the elements from the Vector :


import java.util.Vector;
class vector Search {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("1");
v.add("2");
v.add("3");
v.add("4");
v.add("5");
v.add("1");
v.add("2");
System.out.println(v.contains("3")); //vector contains 3 so it will return True
System.out.println(v.contains("9")); //vector doesn't contain 9 so it will return False
System.out.println(v.indexOf("5"));
System.out.println(v.lastIndexOf("2"));
} }
Output:

162
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

4.3.2 Working with The Size of The Vector

The java.util.vector.size() method in Java is used to get the size of the Vector or the
number of elements present in the Vector.

1. Syntax:
Vector.size()
2. Parameters: The method does not take any parameter.
3. Return Value: The method returns the size or the number of elements present
in the Vector.
4. Below programs illustrate the Java.util.Vector.size() method:

Program to check the Size of the Vector

import java.util.Vector;
class VectorDemo
{
public static void main(String[] args)
{
Vector<Integer> vec = new Vector<Integer>(4);
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
System.out.println("Size of the vector: "+vec.size());
} }

Output:

4.3.3 Searching For Elements In A Vector

import java.util.Vector;
public class VectorDemo
{
public static void main(String[] args) {
Vector vec = new Vector(4);
vec.add(4);
vec.add(3);
vec.add(2);
vec.add(3);
System.out.println("Index of 3 is :"+vec.indexOf(3)); // let us get the index of 3
} }

163
Core Java Unit 1-Chapter 1 SYBSCIT-SEM IV

Output:
Index of 3 is: 1

Questions

Enumeration:
1. What is enumeration in Java? Explain with suitable example.
2. What are the objectives of using Enumeration in Java?
3. With a Java program explain how to define and use an enumeration.
4. Explain how enum can be declared inside a class but not inside a method?
5. What is the importance or significance of enum for a Java programmer?
6. With the help of a Java program explain working on enum by using switch
7. Explain how values(),ordinal() and valueOf() methods can be used through enum
8. Can enum have constructor and concrete methods? if yes explain with suitable Java
Program

Array:
1. What is an Array in Java? Explain its properties as accepted by Java Complier
2. What are the Advantages and disadvantages of using Array in Java?
3. With suitable Java program explain how to declare and index an array
4. How many elements can an array hold explain in detail?
5. How to access the elements through Array index?
6. Write program to explain how to declare, instantiate, initialize and traverse the Java Array
7. What are various types of Arrays in Java? Explain with suitable example
8. Write a detailed note on Two dimensional Arrays in Java
9. Explain the structure of 2 dimensional array in Java
10. How to work with 2D array in Java?
11. Write a simple java program to explain 2D array in java, take input from user.
12. What are multi-dimensional arrays in Java explain with suitable example?
13. How to pass Array to a method in Java?
14. How to process Array elements? Explain with example
15. Explain the various ways available to copy array in Java

Vector:
1. What are vectors in Java? Explain the characteristics or features of vector in Java
2. What are the various ways of doing Java vector class declaration
3. Explain the four constructors of Vector in Java
4. Explain 5 methods used in Java Vector Class
5. What are the method to access the empty and last elements in Java vectors
6. Explain the functions of following methods: removeAll(), replaceAll(),
setSize(),size(),sort()
7. How to add elements to a Vector in Java
8. Write a program to explain how to search for elements in a vector
9. What are ways through which you can check the size of the Vector in Java?

164
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

Unit IV
Chapter 2-Multithreading

Contents

 The thread control methods,


 Thread life cycle,
 The main thread,
 Creating a thread,
 Extending the thread class.

1. Threading

 A thread, in the context of Java, is the path followed when executing a


program. All Java programs have at least one thread, known as the main
thread, which is created by the Java Virtual Machine (JVM) at the program's
start, when the main() method is invoked with the main thread.
 When a Java program starts, the JVM creates the main thread and calls the
program's main() method within that thread. The JVM also creates other
threads that are mostly invisible to you -- for example, threads associated with
garbage collection, object finalization, and other JVM housekeeping tasks.
 Java is a multithreaded programming language which means we can develop
multithreaded program using Java. A multithreaded program contains two or
more parts that can run concurrently and each part can handle different task at
the same time making optimal use of the available resources especially when
your computer has multiple CPUs. By definition multitasking is when multiple
processes share common processing resources such as a CPU.
 Multithreading extends the idea of multitasking into applications where you
can subdivide specific operations within a single application into individual
threads. Each of the threads can run in parallel. The OS divides processing time
not only among different applications, but also among each thread within an
application. Multithreading enables you to write in a way where multiple
activities can proceed concurrently in the
same program.
 Multithreading refers to two or more tasks
executing concurrently within a single
program. A thread is an independent path
of execution within a program. Many
threads can run concurrently within a
program. Every thread in Java is created
and controlled by the java.lang.Thread
class.

165
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

2. The thread control methods


Multithreading has several advantages such as
1. Threads are lightweight compared to processes
2. Threads share the same address space and therefore can share both data and
code
3. Context switching between threads is usually less expensive than between
processes
4. Cost of thread intercommunication is relatively low that that of process
intercommunication
5. Threads allow different tasks to be performed concurrently.

3. Java Thread class

Java provides Thread class to achieve thread programming. Thread class provides
constructors and methods to create and perform operations on a thread. Thread class
extends Object class and implements Runnable interface.

3.1 Java Thread Methods

Modifier and
S.N. Method Description
Type
1) void start() It is used to start the execution of the
thread.
2) void run() It is used to do an action for a thread.
3) static void sleep() It sleeps a thread for the specified amount
of time.
4) static Thread currentThread() It returns a reference to the currently
executing thread object.
5) void join() It waits for a thread to die.
6) int getPriority() It returns the priority of the thread.
7) void setPriority() It changes the priority of the thread.
8) String getName() It returns the name of the thread.
9) void setName() It changes the name of the thread.
10) long getId() It returns the id of the thread.
11) boolean isAlive() It tests if the thread is alive.
12) static void yield() It causes the currently executing thread
object to pause and allow other threads to
execute temporarily.
13) void suspend() It is used to suspend the thread.
14) void resume() It is used to resume the suspended thread.
15) void stop() It is used to stop the thread.
16) void destroy() It is used to destroy the thread group and
all of its subgroups.

166
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

Class constructors

Sr.No. Constructor & Description


1 Thread() This allocates a new Thread object.
2 Thread(Runnable target) This allocates a new Thread object.
3 Thread(Runnable target, String name) This allocates a new Thread object.
4 Thread(String name) This constructs allocates a new Thread object.
5 Thread(ThreadGroup group, Runnable target) This allocates a new Thread
object.
6 Thread(ThreadGroup group, Runnable target, String name) This allocates a
new Thread object so that it has target as its run object, has the specified name as its
name, and belongs to the thread group referred to by group.
7 Thread(ThreadGroup group, Runnable target, String name, long
stackSize)This allocates a new Thread object so that it has target as its run object,
has the specified name as its name, belongs to the thread group referred to by group,
and has the specified stack size.
8 Thread(ThreadGroup group, String name)This allocates a new Thread object.

4. Thread life cycle

A thread can be in one of the five states. According to sun, there is only 4 states in
thread life cycle in java new, runnable, non-runnable and terminated. There is no
running state. But for better understanding the threads, we are explaining it in the 5
states. The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

167
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

1) New
The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.

5. The main thread


When a Java program starts up, one thread begins running immediately. This is
usually called the main thread of your program, because it is the one that is executed
when your program begins. The main thread is important for two reasons:
• It is the thread from which other "child" threads will be spawned.
• It must be the last thread to finish execution. When the main thread stops, your
program terminates.
Although the main thread is created automatically when your program is started, it can
be controlled through a Thread object. To do so, you must obtain a reference to it by
calling the method currentThread( ), which is a public static member of Thread. Its
general form is shown here:
static Thread currentThread( )
This method returns a reference to the thread in which it is called. Once you have a
reference to the main thread, you can control it just like any other thread.

5.1 Creating a Thread


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.
Thread class: Thread class provide constructors and methods to create and perform
operations on a thread. Thread class extends Object class and implements Runnable
interface.
Commonly used Constructors of Thread class:
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r,String name)
168
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

5.2 Runnable interface

The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
1. A new thread starts(with new callstack).
2. The thread moves from New state to the Runnable state.
3. When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi t1=new Multi();
t1.start();
} }

Output:

2) Java Thread Example by implementing Runnable interface

If you are not extending the Thread class, your class object would not be treated as
a thread object. So you need to explicitly create Thread class object. We are

169
Core Java Unit 4-Chapter 2 SYBSCIT-SEM IV

passing the object of your class that implements Runnable so that your class run()
method may execute.

Questions

1. What is Threading? Explain its features in Java


2. What are the thread controls methods?
3. Explain the advantages of thread control methods?
4. What are the constructors of Thread class in Java?
5. Explain at least 5 methods of Thread Class in Java
6. With suitable diagram explain the Thread Life Cycle
7. Write a detailed note on the main Thread
8. Explain Runnable interface
9. With Java program explain Thread creation by extending the Thread Class
10. With Java program explain Thread creation by implementing the Thread Class

170

You might also like