Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

Core Java Unit 1 S.Y.B.Sc.I.

T-SEM III

Chapter 1: Introduction

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

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

Why "Java" name

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

According to James Gosling "Java was one of the top choices along with Silk. Since java was so
unique, most of the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).
9) Notice that Java is just a name not an acronym.
10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996).

1
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Difference between Java and C++

Java C++

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

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

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

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

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

Java does not support default argument value. C++ does support default argument 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, which is platform independent. code may not run on different platforms.

2
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

3
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.
Basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

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:

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

4
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

 Classloader: adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
 Bytecode Verifier: checks the code fragments for illegal code that can violate access
right to objects.
 Security Manager: determines what resources a class can access such as reading and
writing to the local disk.

These security are provided by java language. Some security can also be provided by application
developer through SSL, JAAS, Cryptography etc.

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

5
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Portable

We may carry the java bytecode 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++)

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.

2. Difference between JDK, JRE and JVM

 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. JVM, JRE and JDK are
platform dependent because configuration of each OS differs. But, Java is platform
independent.

The JVM performs following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

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

6
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

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

7
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

3.1 Internal Architecture of JVM


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

8
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

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.

9
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

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

4.2. Byte code verifier

 The bytecode verifier verifies the byte code to see if any security problems are there in
the code. It checks the byte code and ensures the followings.
 1. The code follows JVM specifications.
 2. There is no unauthorized access to memory.
 3. The code does not cause any stack overflows.
 4. There are no illegal data conversions in the code such as float to object references.

10
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

4.3. Just in Time Compiler

 You might have noticed the component “Just in Time” (JIT) compiler in Figure 3. This is a
component which helps the program execution to happen faster.
 As we discussed earlier when the Java program is executed, the byte code is interpreted
by JVM. But this interpretation is a slower process. To overcome this difficulty, JRE
include the component JIT compiler. JIT makes the execution faster.
 If the JIT Compiler library exists, when a particular bytecode is executed first time, JIT
complier compiles it into native machine code which can be directly executed by the
machine in which the Java program runs. Once the byte code is recompiled by JIT
compiler, the execution time needed will be much lesser. This compilation happens
when the byte code is about to be executed and hence the name “Just in Time”.
 Once the bytecode is compiled into that particular machine code, it is cached by the JIT
compiler and will be reused for the future needs. 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. (If you are not clear about the concepts of objects, please read the
prior chapter before continuing in this session).
 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.
 Garbage collection happens automatically. There is no way that you can force garbage
collection to happen. There are two methods “System.gc()” and “Runtime.gc()” through
which you can make request for garbage collation. But calling these methods also will
not force garbage collection to happen and you cannot make sure when this garbage
collection will happen.

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

11
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

What happens at runtime?

At runtime, following steps are performed:

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

12
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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


Yes, like the figure given below illustrates:

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:

o Open command prompt


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

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

Let's see it in the figure given below:

13
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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 properties -> advanced tab -> environment variables -> new tab of
user variable -> write path in variable name -> write path of bin folder in variable value -
> ok -> ok -> ok

For Example:
1)Go to MyComputer properties

2)click on advanced tab

14
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

3)click on environment variables

4)click on new tab of user variables

15
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

5)write path in variable name

6)Copy the path of bin folder

7)paste path of bin folder in variable value

16
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

8)click on ok button

9)click on ok button

Now your permanent path is set. You can now execute any program of java from any drive.

Setting Java Path in Linux OS


Setting the path in Linux OS is same as setting the path in the Windows OS. But here we use
export tool rather than set. Let's see how to set path in Linux OS:

export PATH=$PATH:/home/jdk1.6.01/bin/
Here, we have installed the JDK in the home directory under Root (/home).

17
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Difference between path and classpath in Java

Path:

Path variable is set for providing path for all Java tools like java, javac, javap, javah, jar, applet
viewer. In Java to run any program we use java tool and for compile Java code use javac tool.
All these tools are available in bin folder so we set path up to bin folder.

classpath:

classpath variable is set for providing path of all Java classes which is used in our application. All
classes are available in lib/rt.jar so we set classpath upto lib/rt.jar.

Difference between path and classPath

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

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"

18
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

Classpath variable is used to set the path for all classes which is used in our program so we set
classpath upto rj.jar. in rt.jar file all the .class files are present. When we decompressed rt.jar
file we get all .class files.

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.

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

19
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

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

20
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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
containing many of the same reusable functions commonly found in modern operating systems.
Most of the system library is also written in Java.

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

21
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

 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.
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.
Output
C:\> javac MyFirstJavaProgram.java
C:\> java MyFirstJavaProgram
Hello World

22
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Basic Syntax
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 hellowould
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.

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.

23
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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;
//without lambda, Drawable implementation using anonymous class
Drawable d=new Drawable(){
public void draw(){System.out.println("Drawing "+width);}
};
d.draw();
} }

24
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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. In this tutorial, 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.

25
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

3. Reference to a constructor.

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.

26
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Syntax

containingObject::instanceMethodName

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
// Referring non-static method using reference
Sayable sayable = methodReference::saySomething;
// Calling interface method
sayable.say();
// Referring non-static method using anonymous object
Sayable sayable2 = new MethodReference()::saySomething;
// You can use anonymous object also
// Calling interface method
sayable2.say();
}
}

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.

27
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

Syntax: ClassName::new

Example

interface Messageable
{
Message getMessage(String msg);
}
class Message
{
public Message(String msg)
{
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

28
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

3 Conditional Control Statements are Conditional Control Statements are


Executes faster Executes slower
4 Memory Requirement : More(Since Object Memory Requirement is Less
Code is Generated)
5 Program need not be compiled every time Every time higher level program is converted
into lower level program
6 Errors are displayed after entire program is Errors are displayed for every
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

29
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

30
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

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

31
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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. M ain 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.

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.

32
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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

33
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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


*/

Example:

public class CommentExample2 {


public static void main(String[] args) {

/* Let's declare and


print variable in java. */

34
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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.

35
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

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'

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

36
Core Java Unit 1 S.Y.B.Sc.I.T-SEM III

 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

37

You might also like