Chapter 1 - Unit 1
Chapter 1 - Unit 1
In this version, added many new library elements, redefined the way of handling events, and
JDK 1.1 February 1997 reconfigured most of the libraries of 1.0 and deprecated some features defined by 1.0. Added
inner class, JavaBeans, JDBC, RMI, JIT (Just In time) compiler.
December Added support for many features, such as Swing and Collection Framework. The methods
J2SE 1.2
1998 suspend(), resume() and stop() of Thread class were deprecated.
J2SE 1.3 May 2000 A very small improvement, as it just improved the development environment.
It added some upgrades such as the new keyword assert, chained exception and a channel-
J2SE 1.4 February 2002 based I/O subsystem. Also added some feature to the collection framework and the Networking
classes.
The significant new features added to this version are – Generics, Annotation, Auto boxing and
September
J2SE 5.0 Auto-unboxing, Enumeration, for-each, variable-length argument, Static import, Formatted I/O,
2004
Concurrency utilities.
December In this version the API libraries and several new packages got enhanced and offered
Java SE 6
2006 improvements to the run time. It supports JDBC 4.0.
Added JVM support for dynamic language, String in the switch, Automatic resource
Java SE 7 July 2011
management in try-statement, support for underscore in integers, binary integer literals etc…
Java SE 8 March 2014 Added Date and time API, Repeating annotation, JavaFX.
September Added Java platform module system update, jshell, XML Catalog, jlink, and the JavaDB was
Java SE 9
2017 removed from JDK
Added features are local variable type interface, Application class data sharing, Garbage
Java SE 10 March 2018
collector interface, etc…
September Feature added: Dynamic class file loader, HTTP client, and Transport layer security. JavaFX, Java
Java SE 11
2018 EE, and CORBA modules have been removed from JDK.
Java SE 12 March 2019 Added Microbenchmark Suite, JVM Constant API, One AArch64 Port, Default CDS Archives etc.
Java Buzz Words (OR) Features of Java
The features of Java are also known as Java buzzwords.A list of the most important features
of the Java language is given below.
o Simple
o Platform Independent
o Architectural Neutral
o Dynamic and Extensible
o Portable
o Multi Threading
o Distributed
o Networked
o Robust
o Secured
o High Performance
o Object Oriented
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:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
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:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into byte code. This byte
code is a platform-independent code because it can be run on multiple platforms, i.e., Write
Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer.
o Java Programs run inside a virtual machine sandbox.
o 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.
o Byte code Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Note: 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 meaning of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o 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.
o 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 byte code to any platform. It
doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java byte
code is "close" to native code. It is still a little bit slower than a compiled language (e.g., C+
+). Java is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.
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.
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++.
Definition of Garbage Collection
o In java, garbage means unreferenced objects.
o Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
o To do so, we were using free() function in C language and delete() in C+
+. But, in java it is performed automatically. So, java provides better
memory management.
Any entity that has state and behaviour is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type
of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviours like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Output :
10
20
Examples 3:
class A1
{
int a=10;
int b=20;
void method1()
{
System.out.println(a);
}
void method2()
{
System.out.println(b);
}
}
class A2
{
public static void main(String args[])
{
A1 m1= new A1();
m1.method1();
A1 m2= new A1();
m2.method2();
}
}
Z:\ javac A2.java
Z:\java A2
Output :
10
20
public: It is an access specifier. We should use a public keyword before the main() method
so that JVM can identify the execution point of the program. If we use private, protected,
and default before the main() method, it will not be visible to JVM.
static: You can make a method static by using the keyword static. We should call the main()
method without creating an object. Static methods are the method which invokes without
creating the objects, so we do not need any object to call the main() method.
void: In Java, every method has the return type. Void keyword acknowledges the compiler
that main() method does not return any value.
main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute
a program line by line and end the execution after completion of this method. We can also
overload the main() method.
String args[]: The main() method also accepts some data from the user. It accepts a group of
strings, which is called a string array. It is used to hold the command line arguments in the
form of string values.
main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it can store a group of
string. Remember, this array can also store a group of numbers but in the form of string
only. Values passed to the main() method is called arguments. These arguments are stored
into args[] array, so the name args[] is generally used for it.
In java running a program happens in two steps, compilation and then execution. The image
below shows where does compile time and runtime takes place in execution of a program.
Compile time is a process in which java compiler compiles the java program and generates
a .class file. In other way, in compile time java source code (.java file) is converted in to .class
file using java compiler. While in runtime, the java virtual machine loads the .class file in
memory and executes that class to generate the output of program.
What is JVM
JVM, i.e., Java Virtual Machine.
JVM is the engine that drives the Java code.
Mostly in other Programming Languages, compiler produce code for a particular
system but Java compiler produce Bytecode for a Java Virtual Machine.
When we compile a Java program, then bytecode is generated. Bytecode is the
source code that can be used to run on any platform.
Bytecode is an intermediary language between Java source and the host system.
It is the medium which compiles Java code to bytecode which gets interpreted on a
different machine and hence it makes it Platform/Operating system independent.
JVM's work can be explained in the following manner
o Reading Bytecode.
o Verifying bytecode.
o JVM is specifically responsible for converting bytecode to machine-specific code and
is necessary in both JDK and JRE. It is also platform-dependent and performs many
functions, including memory management and security. (or) Linking the code with
the library.
Diagram of JVM
Javac is the Java Compiler which Compiles Java code into Bytecode. JVM is Java
Virtual Machine which Runs/ Interprets/ translates Bytecode into Native Machine
Code.
In Java though it is considered as an interpreted language, It may use JIT (Just-in-
Time) compilation when the bytecode is in the JVM. The JIT compiler reads the
bytecodes in many sections (or in full, rarely) and compiles them dynamically into
machine code so the program can run faster, and then cached and reused later
without needing to be recompiled. So JIT compilation combines the speed of
compiled code with the flexibility of interpretation.
JVM is specifically responsible for converting bytecode to machine-specific
code and is necessary in both JDK and JRE. It is also platform-dependent and
performs many functions, including memory management and security.
Data Types
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive Data Types:
o A primitive data type is pre-defined by the programming language. The size and type
of variable values are specified, and it has no additional methods.
o The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-Primitive Data Types:
o These data types are not actually defined by the programming language but are
created by the programmer. They are also called “reference variables” or “object
references” since they reference a memory location which stores the data.
o The non-primitive data types include Classes,Interfaces,, and Arrays.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type is used to store only two possible values: true and false. This data
type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean one = false
or
Boolean one = true
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value
is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is
most required. It saves space because a byte is 4 times smaller than an integer. It can also
be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is
32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
int a = 100000, int b = -200000
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807.
Its default value is 0. The long data type is used when you need a range of values more than
those provided by int.
Example:
long a = 100000L, long b = -200000L
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating point numbers. The float data type should never be used for
precise values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letter = 'A'
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system.
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
Problem
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
Local Variables
o Local variables are declared in methods, constructors, or blocks.
o 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.
o Access modifiers cannot be used for local variables.
o Local variables are visible only within the declared method, constructor, or block.
o Local variables are implemented at stack level internally.
o 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.
Instance Variables
o Instance variables are declared in a class, but outside a method, constructor or any
block.
o When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
o Access modifiers can be given for instance variables.
o The instance variables are visible for all methods, constructors and block in the class.
o Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null.
Class/Static Variables
o Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
o Static variables are stored in the static memory.
o Static variables are created when the program starts and destroyed when the
program stops.
o 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.
class sample
void method()
Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
additive +-
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
Control Statements
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides statements
that can be used to control the flow of Java code. Such statements are called control flow
statements. It is one of the fundamental features of Java, which provides a smooth flow of
program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
Example 1 :
for(data_type varname : array_name/collection_name)
{
//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
public class Calculation
{
public static void main(String[] args)
{
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names)
{
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Example 2 :
Java Keywords
Java has a set of keywords that are reserved words that cannot be used as variables,
methods, classes, or any other identifiers:
Keyword Description
abstract A non-access modifier. Used for classes and methods: An abstract class cannot
be used to create objects (to access it, it must be inherited from another class).
An abstract method can only be used in an abstract class, and it does not have
a body. The body is provided by the subclass (inherited from)
boolean A data type that can only store true and false values
byte A data type that can store whole numbers from -128 and 127
double A data type that can store whole numbers from 1.7e−308 to 1.7e+308
extends Extends a class (indicates that a class is inherited from another class)
final A non-access modifier used for classes, attributes and methods, which makes
them non-changeable (impossible to inherit or override)
finally Used with exceptions, a block of code that will be executed no matter if there
is an exception or not
float A data type that can store whole numbers from 3.4e−038 to 3.4e+038
int A data type that can store whole numbers from -2147483648 to 2147483647
interface Used to declare a special type of class that only contains abstract methods
long A data type that can store whole numbers from -9223372036854775808 to
9223372036854775808
native Specifies that a method is not implemented in the same Java source file (but in
another language)
private An access modifier used for attributes, methods and constructors, making
them only accessible within the declared class
protected An access modifier used for attributes, methods and constructors, making
them accessible in the same package and subclasses
public An access modifier used for classes, attributes, methods and constructors,
making them accessible by any other class
return Finished the execution of a method, and can be used to return a value from a
method
short A data type that can store whole numbers from -32768 to 32767
synchronized A non-access modifier, which specifies that methods can only be accessed by
one thread at a time
volatile Indicates that an attribute is not cached thread-locally, and is always read from
the "main memory"
Note: true, false, and null are not keywords, but they are literals and reserved words that
cannot be used as identifiers.
Benefits of OOP
Benefits of OOP include:
o Modularity. Encapsulation enables objects to be self-contained, making
troubleshooting and collaborative development easier.
o Reusability. Code can be reused through inheritance, meaning a team does not have
to write the same code multiple times.
o Productivity. Programmers can construct new programs quicker through the use of
multiple libraries and reusable code.
o Easily upgradable and scalable. Programmers can implement system functionalities
independently.
o Interface descriptions. Descriptions of external systems are simple, due to message
passing techniques that are used for objects communication.
o Security. Using encapsulation and abstraction, complex code is hidden, software
maintenance is easier and internet protocols are protected.
o Flexibility. Polymorphism enables a single function to adapt to the class it is placed
in. Different objects can also pass through the same interface.
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To declare an array, define the variable type with square brackets:
o String[] Variable_name;
o We have now declared a variable that holds an array of strings. To insert values to it,
we can use an array literal - place the values in a comma-separated list, inside curly
braces:
o String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
o To create an array of integers, you could write:
o int[] myNum = {10, 20, 30, 40};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.
}
}
Output:
Volvo BMW Ford Mazda
Opel BMW Ford Mazda
Array Length
To find out how many elements an array has, use the length property:
Example:
class sample
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}
Output:
4
Loop Through an Array
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:
Example:
class sample
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i<cars.length; i++)
{
System.out.println(cars[i]);
}
}
}
Output:
Volvo BMW Ford Mazda
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:
Syntax
for (type variable : arrayname)
{
...
}
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
class sample
{
public static void main(String[] args)
{
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)
{
System.out.println(i);
}
}
}
Output:
Volvo BMW Ford Mazda
Note :The example above can be read like this: for each String element (called i - as
in index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the for-each method
is easier to write, it does not require a counter (using the length property), and it is
more readable.
-----------------------------------------------