Java First Unit
Java First Unit
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.
Platform Independent: Compiler converts source code to bytecode and then the JVM executes
the bytecode generated by the compiler. This bytecode can run on any platform be it Windows,
Linux, or macOS which means if we compile a program on Windows, then we can run it on
Linux and vice versa. Each operating system has a different JVM, but the output produced by
all the OS is the same after the execution of the bytecode. That is why we call java a platform-
independent language.
Object-Oriented Programming Language: Organizing the program in the terms of a
collection of objects is a way of object-oriented programming, each of which represents an
instance of the class.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
Simple: Java is one of the simple languages as it does not have complex features like pointers,
operator overloading, multiple inheritances, and Explicit memory allocation.
Robust: Java language is robust which means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible,that is why the java compiler is able
to detect even those errors that are not easy to detect by another programming language. The
main features of java that make it robust are garbage collection, Exception Handling, and
memory allocation.
Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it shows
ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like
stack corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in
an environment that is independent of the os(operating system) environment which makes java
programs more secure.
Distributed: We can create distributed applications using the java programming language.
Remote Method Invocation and Enterprise Java Beans are used for creating distributed
applications in java. The java programs can be easily distributed on one or more systems that
are connected to each other through an internet connection.
Multithreading: Java supports multithreading. It is a Java feature that allows concurrent
execution of two or more parts of a program for maximum utilization of the CPU.
Portable: As we know, java code written on one machine can be run on another machine. The
platform-independent feature of java in which its platform- independent bytecode can be taken
to any platform for execution makes java portable.
High Performance: Java architecture is defined in such a way that it reduces overhead during
the runtime and at sometimes java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called making
applications to execute faster.
Write Once Run Anywhere: As discussed above java application generates a ‘.class’ file that
corresponds to our applications (program) but contains code in binary format. It provides ease t
architecture-neutral ease as bytecode is not dependent on any machine architecture. It is the
primary reason java is used in the enterprising IT industry globally worldwide.
Power of compilation and interpretation: Most languages are designed with the purpose of
either they are compiled language or they are interpreted language. But java integrates arising
enormous power as Java compiler compiles the source code to bytecode and JVM executes this
bytecode to machine OS-dependent executable code.
Java Terminology
Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution
phases of a program. They are written, compile and run the program.
Writing a program is done by a java programmer.
The compilation is done by the JAVAC compiler which is a primary Java compiler included in
the Java development kit (JDK). It takes the Java program as input and generates bytecode as
output.
In the Running phase of a program, JVM executes the bytecode generated by the compiler.
JVM Architecture
2. Bytecode in the Development Process: As discussed, the Javac compiler of JDK compiles
the java source code into bytecode so that it can be executed by JVM. It is saved as .class file by
the compiler. To view the bytecode, a disassembler like javap can be used.
3. Java Development Kit(JDK): While we were using the term JDK when we learn about
bytecode and JVM. So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment (JRE), java debuggers, java
docs, etc. For the program to execute in java, we need to install JDK on our computer in order to
create, compile and run the java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers
allows the java program to run, however, we cannot compile it. JRE includes a browser, JVM,
applet support, and plugins. For running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that
memory JVM has a program called Garbage Collector. Garbage Collectors can recollect the
objects that are not referenced. So Java makes the life of a programmer easy by handling
memory management. However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage cannot recover the
memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for
.class files to load. By default, JDK provides many libraries. If you want to include external
libraries they should be added to the classpath.
Java Data Types
Data types in Java are of different sizes and values that can be stored in the variable that is made
as per convenience and circumstances to cover up all test cases. Java has two categories in
which data types are segregated
Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
Non-Primitive Data Type or Object Data type: such as String, Array, etc.
// Class
class DataTypes {
short s = 56;
Java if Statement
The Java if statement tests the condition. It executes the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
EXAMPLE
//Java Program to demonstate the use of if statement.
public class IfExample
{
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18");
}
}
}
Java if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example: Program to check a given year is leap or not.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
if(marks<50){ System.out.println("fail");
}
else if(marks>=50 && marks<60){ System.out.println("D grade");
}
else if(marks>=60 && marks<70){ System.out.println("C grade");
}
else if(marks>=70 && marks<80){ System.out.println("B grade");
}
else if(marks>=80 && marks<90){ System.out.println("A grade");
}else if(marks>=90 && marks<100){ System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Java Nested if statement
The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
default:
code to be executed if all cases are not matched;
}
Example: SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Syntax:
System.out.println();//new line
}
}
}
Java While Loop
The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.
The while loop is considered as a repeating if statement. If the number of iteration is not fixed,
it is recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
Increment / decrement statement
}
do{
//code to be executed / loop body
//update statement
}while (condition);
Example:
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately
need to initialize and increment the variable used in the condition (here, i). Otherwise, the loop
will execute infinitely.
DoWhileExample.java public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i); i++;
}while(i<=10);
}
}
Java Arrays
Java array is an object which contains elements of a similar data type. Additionally, The elements
of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values
or objects in an array in Java.
arrayRefVar=new datatype[size];
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]);
}}
Multidimensional Array in Java
Syntax to Declare Multidimensional Array in Java
Syntax:
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named Ravi is an object.
Properties of Java Classes
Class is not a real-world entity. It is just a template or blueprint or prototype from which
objects are created.
Class does not occupy memory.
Class is a group of variables of different data types and a group of methods.
A Class in Java can contain:
• Data member
• Method
• Constructor
• Nested Class
• Interface
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life
entities. Objects are the instances of a class that are created to use the attributes and methods of
a class. A typical Java program creates many objects, which as you know, interact by invoking
methods. An object consists of :
State: It is represented by attributes of an object. It also reflects the properties of an object.
Behavior: It is represented by the methods of an object. It also reflects the response of an object
with other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Packages
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and namespace management.
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
java.io: Contains classed for supporting input / output operations.
java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a
directory myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being
the package names.
// Name of the package must be same as the directory
// under which this file is saved
package mypack;
public class MyPackageClass
{
public void p()
{
System.out.println("This is my package!");
}
To compile the Java programs with package statements, you have to use -d option as shown
below.
javac -d Destination_folder file_name.java
Example to import the user defined package
import mypack.MyPackageClass;
public class app2 {
public static void main(String[] args) {
System.out.println("This statement is for app2");
MyPackageClass m=new MyPackageClass();
m.p();
}
Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to
handle runtime errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Major reasons why an exception Occurs
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out of
memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc.
Errors are usually beyond the control of the programmer, and we should not try to handle errors.
Error: An Error indicates a serious problem that a reasonable application should not try to
catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions
are suitable to explain certain error situations.
1. Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.
2. Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and even if we didn’t handle or
declare it, the program would not give a compilation error.
User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user- defined Exceptions’.
Example program
public class JavaExceptionExample{ public static void main(String args[]){ try{
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);} System.out.println("rest of the code...");
}
}
Exception Handling in java is managed via five keywords: try, catch, throw, throws, and finally.
Here are 5 keywords that are used in handling exceptions in Java
Keyword Description
try This keyword is used to specify a block and this block must be followed by either
catch or finally. That is, we can’t use try block alone.
catch This keyword must be preceded by a try block to handle the exception and can be
followed by a final block later.
finally This keyword is used to execute the program, whether an exception is handled or
not.
throw This keyword is used to throw an exception.
Try {
//code that may throw an exception
}
catch(Exception_class_Name ref){}
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Example
In following example, an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
Multiple Catch Blocks
A try block can be followed by multiple catch blocks.
Try {
//code that may throw an exception
}
catch(Exception_class_Name ref1){
}catch(Exception_class_Name ref2){
} catch(Exception_class_Name ref2){}
try{
int a[]=new int[5]; a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Process: A process is a self contained execution environment and it can be seen as a program or
application
Thread: Multithreading is a Java feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU. Each part of such program is called a thread. So,
threads are light-weight processes within a process.