Chapter 1 - Unit 1
Chapter 1 - Unit 1
Release
Version Features
Date
JDK
1995 —
Beta
January
JDK 1.0 This is the first stable version.
1996
In this version the API libraries and several new packages got
Java SE December
enhanced and offered improvements to the run time. It supports
6 2006
JDBC 4.0.
Java SE September Added Java platform module system update, jshell, XML Catalog,
9 2017 jlink, and the JavaDB was removed from JDK
Java SE Added features are local variable type interface, Application class
March 2018
10 data sharing, Garbage collector interface, etc…
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 an object-orientedprogramming 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 behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.Basic concepts of OOPs are:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o 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:
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.
Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a
wide variety of applications. So, before diving in depth, it is necessary to understand
the basic structure of Java program in detail. In this section, we have discussed the
basic structure of a Java program. At the end of this section, you will able to develop
the Hello world Java program, easily.
Java Main Method
public static void main(String[] args) is the most important Java method. When you start
learning java programming, this is the first method you encounter. Remember the first Java
Hello World program you wrote that runs and prints “Hello World”?
publicclass Test
{
public void main(String[] args)
{
System.out.println("Hello World");
}
}
$ javac Test.java
$ java Test
Error: Main method is not static inclass Test, please define the main method as:
public static void main(String[] args)
$
void
Java programming mandates that every method provide the return type. Java main method
doesn’t return anything, that’s why it’s return type is void. This has been done to keep
things simple because once the main method is finished executing, java program
terminates. So there is no point in returning anything, there is nothing that can be done for
the returned object by JVM. If we try to return something from the main method, it will give
compilation error as an unexpected return value. For example, if we have the main method
like below.
Publicclass Test
{
Publicstaticvoid main(String[] args)
{
Return0;
}
}
We get below error when above program is compiled.
$ javac Test.java
Test.java:5: error: incompatible types: unexpected return value
return0;
^
1 error
$
main
This is the name of java main method. It’s fixed and when we start a java program, it looks
for the main method. For example, if we have a class like below.
public class Test
{
public static voidmymain(String[] args)
{
System.out.println("Hello World");
}
}
And we try to run this program, it will throw an error that the main method is not found.
$ javac Test.java
$ java Test
Error: Main method not found inclass Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
$
String[] args
Java main method accepts a single argument of type String array. This is also called as java
command line arguments. Let’s have a look at the example of using java command line
arguments.
public class Test
{
public static void main(String[] args)
{
for(String s : args)
{
System.out.println(s);
}
}
}
Above is a simple program where we are printing the command line arguments. Let’s see
how to pass command line arguments when executing above program.
$javac Test.java
$ java Test 1 2 3
1
2
3
$ java Test "Hello World""RVR&JCCE"
Hello World
RVR&JCCE
$ java Test
$
Examples 1:
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();
Output :
10
20
Java main() method (Another Explanation)
The main() is the starting point for JVM to start execution of a Java program. Without the
main() method, JVM will not execute the program. The syntax of the main() method is:
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.
What happens if the main() method is written without String args[]?
The program will compile, but not run, because JVM will not recognize the main() method.
Remember JVM always looks for the main() method with a string type array as a parameter.
Execution Process
First, JVM executes the static block, then it executes static methods, and then it creates the
object needed by the program. Finally, it executes the instance methods. JVM executes a
static block on the highest priority basis. It means JVM first goes to static block even before
it looks for the main() method in the program.
Example
class Demo
{
static //static block
{
System.out.println("Static block");
}
public static void main(String args[]) //static method
{
System.out.println("Static method");
}
}
Output:
Static block
Static method
We observe that JVM first executes the static block, if it is present in the program. After that
it searches for the main() method. If the main() method is not found, it gives error.
Compile time and runtime in Java
Runtime and compile time, these are two programming terms that are more frequently
used in java programming language. The programmers specially beginners find it little
difficult to understand what exactly they are. So let's understand what these terms means in
java with example.
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
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system.
Unicode System
o ASCII (American Standard Code for Information Interchange) for the United States.
o ISO 8859-1 for Western European Language.
o KOI-8 for Russian.
o GB18030 and BIG-5 for chinese, and so on.
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.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
if(condition)
{
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}else if (city == "Noida")
{
System.out.println("city is noida");
}else if(city == "Agra")
{
System.out.println("city is agra");
}
else
{
System.out.println(city);
}
}
}
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another
if or else-if statement.
Syntax of Nested if-statement is given below.
if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
Consider the following example.
Student.java
public class Student
{
public static void main(String[] args)
{
String address = "Delhi, India";
if(address.endsWith("India"))
{
if(address.contains("Meerut"))
{
System.out.println("Your city is Meerut");
}
else if(address.contains("Noida"))
{
System.out.println("Your city is Noida");
}
else
{
System.out.println(address.split(",")[0]);
}
}
else
{
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable
which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
public class Student implements Cloneable
{
public static void main(String[] args)
{
int num = 2;
switch (num)
{
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2
While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value. The switch permits only int,
string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when
we exactly know the number of times, we want to execute the block of code.
for(initialization, condition, increment/decrement)
{
//block of statements
}
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
public class Calculattion
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++)
{
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java
C
C++
Python
JavaScript
Example 2 :
Java while loop
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
The syntax of the while loop is given below.
while(condition)
{
//looping statements
}
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
public class Calculation
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10)
{
System.out.println(i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements.
In other words, jump statements transfer the execution control to the other part of the
program. There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However,
it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for
loop.
BreakExample.java
public class BreakExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
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)
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
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.
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"};
Note: Array indexes start with 0: [0] is the first element. [1] is the second element,
etc.