Java Module I and II
Java Module I and II
Module I
What is Java?
Java is a popular programming language, created in 1995.
It is used for:
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.
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.
Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
Portable
Being architecture-neutral and having no implementation dependent aspects of the specification makes Java
portable. The compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX
subset.
Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time error
checking and runtime checking.
Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.
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.
High Performance
With the use of Just-In-Time compilers, Java enables high performance.
Distributed
Java is designed for the distributed environment of the internet.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be used to
verify and resolve accesses to objects at run-time.
Program:
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte code.
o System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of System.out.println statement later.
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java program.
When you run the Java program, Java compiler first compiles your Java code to bytecode. Then, the JVM
translates bytecode into native machine code (set of instructions that a computer's CPU executes directly).
Java is a platform-independent language. It's because when you write Java code, it's ultimately written for
JVM but not your physical machine (computer). Since JVM executes the Java bytecode which is platform-
independent, Java is platform-independent.
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java Virtual
Machine (JVM), and other components that are required to run Java applications.
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.
Any text between // and the end of the line is ignored by Java (will not be executed).
Example
// This is a comment
System.out.println("Hello World");
This example uses a multi-line comment (a comment block) to explain the code:
Variables are containers for storing data values. A variable in Java must be a specified data type.
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
boolean - stores values with two states: true or false
Example
Create a variable called name of type String and assign it the value "John":
System.out.println(name);
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Java Operators
Operators are used to perform operations on variables and values.
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 ?:
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
Relational Operators
Relational operators are used to check the relationship between two operands.
Logical Operators
Logical operators are used to check whether an expression is true or false . They are used in decision
making.
Operator Example Meaning
&& (Logical expression1 && true only if both expression1 and expression2 are
AND) expression2 true
Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that increases the
value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning
+ Unary plus: not necessary to use since numbers are positive without using it
Bitwise Operators
Operator Description
~ Bitwise Complement
^ Bitwise exclusive OR
Other operators
Ternary Operator
The ternary operator (conditional operator) is shorthand for the if-then-else statement. For example,
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each
value.
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName - it is an identifier
Example:
String[] cars;
In Java, we can declare and allocate memory of an array in one single statement. For example,
In the Java array, each memory location is associated with a number. The number is known as an array
index. We can also initialize arrays in Java, using the index number. For example,
// initialize array
age[0] = 12;
age[1] = 4;
age[2] = 5;
Array indices always start from 0. That is, the first element of an array is at index 0.
If the size of an array is n, then the last element of the array will be at index n-1.
The syntax for accessing elements of an array,
A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself.
For example,
Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a
maximum of 12 elements,
Everything in Java is associated with classes and objects, along with its attributes and methods.
Create a Class
class ClassName {
// fields
// methods
}
Example:
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Java Objects
We have used the new keyword along with the constructor of the class to create an object. Constructors are
similar to methods and have the same name as the class.
We can use the name of objects along with the . operator to access members of a class.
class Bicycle {
// field of class
int gear = 5;
// method of class
void braking() {
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial values for object attributes.
A constructor has the same name as that of the class and does not have any return type.
Example:
class Test {
Test() {
// constructor body
}}
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.
Example:
class Geek
{
int num;
String name;
Geek()
{
System.out.println("Constructor called");
}
}
class GFG
{
public static void main (String[] args)
{
// this would invoke default constructor.
class GFG
{
public static void main (String[] args)
{
// this would invoke the parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name +
" and GeekId :" + geek1.id);
}
}
There is no copy constructor in Java. However, we can copy the values from one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
In this example, we are going to copy the values of one object into another using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Syntax:
protected void finalize throws Throwable{}
Since Object class contains the finalize method hence finalize method is available for every java class
since Object is the superclass of all java classes. Since it is available for every java class hence Garbage
Collector can call the finalize method on any java object
Why finalize method is used()?
finalize() method releases system resources before the garbage collector runs for a specific object. JVM
allows finalize() to be invoked only once per object.
Module II
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a base class or a parent
class).
Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example:
class Vehicle {
System.out.println("Tuut, tuut!");
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from
the Car class
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
...
...
Interface in Java
An Interface in Java programming is defined as an abstract type used to specify the behavior of a class. A Java
interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java,
interfaces are declared using the interface keyword. All methods in the interface are implicitly public and
abstract.
To use an interface in your class, append the keyword "implements" after your class name followed by the
interface name.
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound();
myPig.sleep();
}
}
As shown in the figure given below, a class extends another class, an interface extends another interface, but
a class implements an interface.
Declaring a method in sub class which is already present in parent class is known as method overriding.
Overriding is done so that a child class can give its own implementation to a method which is already
provided by the parent class.
Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
Method overriding is used for runtime polymorphism
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
Method Overloading is a feature that allows a class to have more than one method having the same name, if
their argument lists are different.
In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.
class Adder{
Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We
can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
1) Private
Example
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only
within package. It cannot be accessed from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.
3) Protected
The protected access modifier is accessible within package and outside the package but through inheritance
only.
The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
import Keyword
The different ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
Example
//save by A.java
package pack;
public class A{
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
A method which is declared as abstract and does not have implementation is known as an abstract method.