Java - Unit-1
Java - Unit-1
Java is a general purpose object oriented programming language developed by sun Microsoft system of USA
in 1991. Originally called Oak by jamesGosling, one of the inventors of the language, java was designed for
the development of the software for consumer electronic devices like TV, VCR and such other electronic
machines.
The goal had a strong impact on the development team to make the language simple, portable and high
reliable. The java team included the existing languages like c and C++ had limitation in term of both
reliability and portability. However they modeled their new language java on c and c++ but remove a number
of features of c and c++ that were considered as source of problem and thus made java a really simple,
reliable, portable and powerful language.
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently used. Some of
them are as follows:
• Desktop Applications such as acrobat reader, media player, antivirus, etc.
• Web Applications such as irctc.co.in, javatpoint.com, etc.
• Enterprise Applications such as banking applications.
• Mobile
• Embedded System
• Smart Card
• Robotics
• Games, etc.
There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used
for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and
Java ME are used for creating mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.
History of Java
The history of Java is very interesting. Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time. The history of Java starts with the
Green Team. Java team members (also known as Green Team), initiated this project to develop a language
for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet
programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Following
are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A.,
France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why had they chose the name Java for Java language? The team gathered to choose a new name. The
suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted something that
reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and
fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique,
most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
10) Initially developed by James Gosling at Sun Microsystems(which is now a subsidiary of Oracle
Corporation) and released in 1995.
12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds new features in
Java.
Java Versions
Year Development
1990 Sun Microsoftsystem decided to develop special software that could be used to
manipulate consumer electronic device.
1991 After exploring the possibility of using the most popular object oriented
language C++ the team announced a new language named Oak.
1992 The Team known as Green Project team by sun demonstrated the application
of their new language to control a list of home application using a hand held
device with tiny touch-sensitive screen.
1993 The world Wide Web (WWW) appeared on the the internet and transformed
the text based internet to a graphical-rich-environment.
1994 The team developed a web browser called “Hotjava” to locate and run applet
program on the internet.
1995 Oak was renamed “java” due to some legal snags.java is just a name and is not
an acronym.
Here is a brief history of all the Java versions with its release date.
C++ vs Java
KEY DIFFERENCE:
• C++ uses only compiler, whereas Java uses compiler and interpreter both.
• C++ supports both operator overloading & method overloading whereas Java only supports method
overloading.
• C++ supports manual object management with the help of new and delete keywords whereas Java
has built-in automatic garbage collection.
• C++ supports structures whereas Java doesn’t supports structures.
• C++ supports unions while Java doesn’t support unions.
COMPARISON
INDEX C++ JAVA
PARAMETER
C++ was developed by Bjarne
Java was developed by James Gosling
Developed / Founded Stroustrup at Bell Labs in 1979. It
1 at Sun Microsystems. Now, it is
by was developed as an extension of
owned by Oracle.
the C language.
It has support for both procedural
Java has support only for object
2 Programming model programming and object oriented
oriented programming models.
programming.
C++ is platform dependent. It is Java is platform independent. It is
3 Platform dependence based on the concept of Write Once based on the concept of Write Once
Compile Anywhere. Run Anywhere.
C++ supports features like operator Java does not support features like
4 Features supported overloading, Goto statements, operator overloading, Goto statements,
structures, pointers, unions, etc. structures, pointers, unions, etc.
Compilation and C ++ is only compiled and cannot Java can be both compiled and
5
Interpretation be interpreted. interpreted.
Java, on the other hand, has more
C++ has very limited libraries with diverse libraries with a lot of support
Library and Code low level functionalities. C++ for code reusability. In Java, only calls
6
reusability support allows direct calls to native system through the Java Native Interface and
libraries. recently Java Native Access are
allowed.
In C++, memory management is In Java, memory management is
7 Memory Management
manual. System controlled.
C++ is pretty consistent between In Java, semantics differs for primitive
8 Type semantics
primitive and object types. and object types.
In C++, both global and namespace
9 Global Scope Java has no support for global scope.
scopes are supported.
Access control and In C++, a flexible model with In Java, the model is cumbersome and
10
object protection constant protection is available. encourages weak encapsulation.
Call by Value and C++ supports both call by value Java supports call by value only. There
11
Call by reference and call by reference. is no call by reference in java.
Thread Support C++ doesn't have built-in support Java has built-in thread support.
12 for threads. It relies on third-party
libraries for thread support.
Hardware C++ is nearer to hardware. Java is not so interactive with
13
hardware.
Features of Java
The primary objective of Java
programming language creation was to
make it portable, simple and secure
programming language. Apart from this,
there are also some excellent features
which play an important role in the
popularity of this language. The features
of Java are also known as Java
buzzwords.
A list of the most important features of
the Java language is given below.
• Simple
• Object-Oriented
• Portable
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic Garbage Collection
in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a
write once, run anywhere language. A platform is the
hardware or software environment in which a program
runs.
There are two types of platforms software-based and
hardware-based. Java provides a software-based platform.
The Java platform differs from most other platforms in the
sense that it is a software-based platform that runs on top of
other hardware-based platforms. It has two components:
• Runtime Environment
• API(Application Programming Interface)
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
• Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
• There are exception handling and the type checking mechanism in Java. All these points make Java
robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the 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. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Interpreted:
Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development
process is more rapid and analytical since the linking is an incremental and light-weight process.
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.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages, i.e., C and C++.
Java Environment:
Java environment included a large number of development tools and Hundreds of classes and methods. The
development tools are part of the system known as Java Development Kit(JDK) and the classes and method
are part of the java standard library (JSL) also known as the Application programming Interface(API).
The java development kit comes with a collection of tools that are used for developing and running java
program. They include:
Appletviewer: Enabled us to run java applets.
Java: Java interpreter which run applet and application by reading and interpreting
bytecode files.
Javac: The java compiler, which translate java source code to byte code files that the
interpreter can understand.
Javadoc: Creates HTML-format documentation from java source code files.
Javah: Produce header files for use with native methods.
Javap: java disassembler which enables us to convert bytecode file into a program
description.
Jdb: java debugger, which helps us to find errors in our programs.
AWT packages(.awt): The Abstract window tool kit packages contains classes that implements plateform-
independent graphical user interface.
Applet packages(.Applet):this includea set of classes that allow us to create java applets.
• JRE contains class libraries, JVM, and other supporting files. It does not include any tool for Java
development like a debugger, compiler, etc.
• It uses important package classes like math, swing, util, lang, awt, and runtime libraries.
• If you have to run Java applets, then JRE must be installed in your system.
• Documentation Section
• Package Statement
• Import Statement
• Interface Section
• Class Definition
• Main Method Class
Documentation Section
The documentation section is an important section but optional for a Java program. It includes basic
information about a Java program. The information includes the author's name, date of creation, version,
program name, company name, and description of the program. It improves the readability of the
program. Whatever we write in the documentation section, the Java compiler ignores the statements during
the execution of the program. To write the statements in the documentation section, we use comments. The
comments may be single-line, multi-line, and documentation comments.
• Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols. For
example:
/*It is an example of
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:
/**It is an example of documentation comment*/
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of a particular
package, we need to import that class. The import statement represents the class stored in the other package.
We use the import keyword to import the class. It is written before the class declaration and after the
package statement. We use the import statement in two ways, either import a specific class or import all
classes of a particular package. In a Java program, we can use multiple import statements. For example:
• import java.util.Scanner; //it imports the Scanner class only
• import java.util.*; //it imports all the class of the java.util package
Interface Section
It is an optional section. We can create an interface in this section if required. We use the interface keyword
to create an interface. An interface
is a slightly different from the class. It contains only constants and method declarations. Another difference
is that it cannot be instantiated. We can use interface in classes by using the implements keyword. An
interface can also be used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class
, we cannot create any Java program. A Java program may conation more than one class definition. We use
the class keyword to define the class. The class is a blueprint of a Java program. It contains information
about user-defined methods, variables, and constants. Every Java program has at least one class that contains
the main() method. For example:
class Student //class definition
{
}
Token:
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be classified as
follows:
• Keywords
• Identifiers
• Constants
• Special Symbols
• Operators
Keywords:
Keywords are pre-defined or reserved words in a programming language. Each keyword is meant to
perform a specific function in a program. Since keywords are referred names for a compiler, they can’t be
used as variable names because by doing so, we are trying to assign a new meaning to the keyword which is
not allowed. Java language supports following keywords:
Identifiers in Java
Identifiers in Java are symbolic names used for identification. They can be a class name, variable name,
method name, package name, constant name, and more. However, In Java, There are some reserved words
that cannot be used as an identifier.
A Java identifier is a name given to a package, class, interface, method, or variable. It allows a programmer
to refer to the item from other places in the program.
In programming languages, identifiers are used for identification purposes. In Java, an identifier can be a
class name, method name, variable name, or label. For example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
In the above java code, we have 5 identifiers namely:
• Test : class name.
• main : method name.
• String : predefined class name.
• args : variable name.
• a : variable name.
Java Constant
Constant is a value that cannot be changed after assigning it. Java does not directly support the constants.
There is an alternative way to define the constants in Java by using the non-access modifiers static and final.
Constants are also like normal variables. But, the only difference is, their values cannot be modified by the program
once they are defined. Constants refer to fixed values. They are also called as literals.
Special Symbols: The following special symbols are used in Java having some special meaning and thus, cannot be
used for some other purpose.
[] () {}, ; * =
Brackets []: Opening and closing brackets are used as array element reference. These indicate single and
multidimensional subscripts.
Parentheses (): These special symbols are used to indicate function calls and function parameters.
Braces {}: These opening and ending curly braces marks the start and end of a block of code containing more than one
executable statement.
Comma (, ): It is used to separate more than one statements like for separating parameters in function calls.
Semicolon : It is an operator that essentially invokes something called an initialization list.
asterick (*): It is used to create pointer variable.
Assignment operator: It is used to assign values
Variable:A variable is an identifier that denotes a storage location use to store a data value.
Variable in Java is a data container that saves the data values during Java program execution. Every variable
is assigned a data type that designates the type and quantity of value it can hold. Variable is a memory
location name of the data.
A variable is a name given to a memory location. It is the basic unit of storage in a program.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the variable effects that
memory location.
Syntax:
Datatype variable1, variable2…
Int a,
Float b,c;
int data=50;//Here data is variable
Rules:
• They must not begin with a digit.
• Uppercase and lowercase are distinct.
• It should not be a keyword.
• White space is not allowed.
• Variable names can be of any length.
Assignment of Variable:
Datatype variable =value;
Int a=10;
Example:
int a, b, c; // Declares three ints, 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'
Local Variables
• 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.
• Local variables are implemented at stack level internally.
• 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.
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public class A
{ static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Static Variables
Static variables are also known as Class variables.
• These variables are declared similarly as instance variables. The difference is that static variables are
declared using the static keyword within a class outside any method constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per class irrespective of
how many objects we create.
• Static variables are created at the start of program execution and destroyed automatically when
execution ends.
• Initialization of Static Variable is not mandatory. Its default value is 0
• If we access the static variable like the Instance variable (through an object), the compiler will show
the warning message, which won’t halt the program. The compiler will replace the object name with
the class name automatically.
• If we access the static variable without the class name, the compiler will automatically append the
class name.
import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}}
1) If Statement:
if(condition) public class Student {
{ public static void main(String[] args) {
statement 1; //executes when condition is true int x = 10;
} int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
2) if-else statement
if(condition) { public class Student {
statement 1; //executes when condition is true public static void main(String[] args) {
int x = 10;
} int y = 12;
else{ if(x+y < 10) {
statement 2; //executes when condition is fals System.out.println("x + y is less than 10");
e } else {
} System.out.println("x + y is greater than 20");
}
}
}
3) if-else-if ladder:
if(condition 1) { public class Student {
statement 1; //executes when condition 1 is true public static void main(String[] args) {
} String city = "Delhi";
else if(condition 2) { if(city == "Meerut") {
statement 2; //executes when condition 2 is true System.out.println("city is meerut");
} }else if (city == "Noida") {
else { System.out.println("city is noida");
statement 2; //executes when all the conditions ar }else if(city == "Agra") {
e false System.out.println("city is agra");
} }else {
System.out.println(city);
}
}
}
For Loop
for(initialization; condition; increment/decrement){
//statement or code to be executed
}
The Java Runtime Environment (JRE) version 8 is what you get when you download Java software from java.com.
The JRE consists of the Java Virtual Machine (JVM), Java platform core classes, and supporting Java platform
libraries. The JRE is the runtime portion of Java software, which is all you need to run Java WebStart applications
from a supported web browser. It doesn’t come with development tools, though – these tools are part of the Java
Development Kit (JDK).
The Java Plug-in software is a component of the Java Runtime Environment (JRE). The JRE allows some applications
written in the Java programming language to launch via some browsers. The Java Plug-in software is not a standalone
program and cannot be installed separately.
I have heard the terms Java Virtual Machine and JVM. Is this Java software?
The Java Virtual Machine is only one part of Java software that is involved in running an application. The Java Virtual
Machine is built right into your Java software download, part of the JRE and helps run Java applications.
Answer: For beginners, it is better to learn C++ as the syntax of C++ is easier compared to
Java and there is extensive support for standard data structures like stack, queue, etc. in
C++. However, for more experienced coders, Java is a great programming language to
know about as Java is used in a lot of big companies like Amazon, Google, etc. and
therefore, would help the developers a lot.
Answer: We cannot say that one language is more powerful than the other until the criteria
for judgement is mentioned. In other words, in terms of performance, C++ is the winner.
However, in terms of flexibility of usage, Java is definitely better.
Answer: C++ is a semi object oriented programming language which is great for beginners
to learn about the basics or fundamentals of object oriented programming. Also, in areas
like Gaming engines and High Frequency Trading, etc. high performance is of utmost
importance and hence, C++ is the preferred language in these fields.
Answer: To a certain extent, the answer to this question is Yes. Java and JavaScript had
taken over a few years back and Python seems to dominate the present (and future
perhaps). However, we have to also take into consideration the fact that C++ is still
amongst the top five most popular languages. The fact that C++ usage is more domain-
oriented, does not necessarily mean it is dying.
Answer: In order to answer this question, one’s interests need to be taken into account. If a
beginner wants to make projects on the system side, or make projects related to gaming
engines, etc. and if making high performance and fast systems is a priority, C++ is
definitely a better choice for those kinds of beginners compared to Java. However, Java
offers way more features and easy to use libraries than C++ and therefore, is preferred in
the domain of Software Development by a lot of developers. So, to build feature rich
applications with ease, a beginner can go ahead and choose Java over C++.
6. Question: What is the main key difference between C++ and Java?
Answer: The main difference between C++ and Java is that C++ is only a compiled
language while Java is both compiled and interpreted. The C++ compiler converts the
source code into machine code and therefore, it is platform dependent. However, Java
source code is converted into bytecode by its compiler and following that, the Java
interpreter executes this bytecode at runtime and produces output. The fact that Java is
interpreted is the reason as to why it is platform independent.