Module I - Basic Java 1
Module I - Basic Java 1
CSE
MODULE I
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a
Javaprogram. There are three notions of the JVM: specification, implementation, and instance. The
specification is a document that formally describes what is required of a JVM implementation. Having a single
specification ensures all implementations are interoperable. A JVM implementation is a computer program that
meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a
process that executes a computer program compiled into Java bytecode.
Java Runtime Environment (JRE) is a software package that contains what is required to run a Java program.
It includes a Java Virtual Machine implementation together with an implementation of the Java Class Library.
The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with their
Java Virtual Machine
called HotSpot.
Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javaccompiler. The Java Development Kit is provided free of charge either by OracleCorporation directly,
or by theOpenJDK open source project, which is governed by Oracle.
A Java virtual machine (JVM) is an abstract computing machine that enables a computer to run a
Javaprogram. There are three notions of the JVM: specification, implementation, and instance. The
specification is a document that formally describes what is required of a JVM implementation. Having a single
specification ensures all implementations are interoperable. A JVM implementation is a computer program that
meets the requirements of the JVM specification. An instance of a JVM is an implementation running in a
process that executes a computer program compiled into Java bytecode.
Java Runtime Environment (JRE): is a software package that contains what is required to run a Java
program. It includes a Java Virtual Machine implementation together with an implementation of the Java Class
Library. The Oracle Corporation, which owns the Java trademark, distributes a Java Runtime environment with
their Java Virtual Machine
called HotSpot.
Java Development Kit (JDK) is a superset of a JRE and contains tools for Java programmers,
e.g. a javaccompiler. The Java Development Kit is provided free of charge either by OracleCorporation directly,
or by theOpenJDK open source project, which is governed by Oracle.
java
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is known as a platform.
Since Java has its own runtime environment (JRE) and API, it is called platform.
Java Example
class Simple{
public static void main(String args[])
{
[Link]("Hello Java");
}
}
Applications of java
There are many devices where java is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as [Link], [Link] etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used forcreating mobile
applications.
Features of Java
Simple
Object-Oriented
Platform Independent
secured
Robust
Architecture Neutral
Portable
High Performance
Distributed
Multi-threaded
Simple
There is given many features of java. They are also known as java [Link]
Syntax is based on C++ (so easier for programmers to learn it after C++).java removed many confusing and/or rarely-
used features e.g., explicit pointers, operator overloading etc. No need toremove unreferenced objects because there is
Automatic Garbage Collection in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects thatincorporates both
data and [Link]-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
The Java platform differs from most other platforms in the sense that it is a software-based
platformthat runs on the top of other hardware-based platforms. It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Classloader: adds security by separating the package for the classes of the local file system from
those that are imported from network sources. Bytecode Verifier: checks the code fragments for
illegal codethat can violate access right to objects.
Security Manager: determines what resources a class can access such as reading and writing to the
[Link] security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.
Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that avoids security
problem. There is automatic garbage collection in java. There is exception handling andtype checking mechanism in java.
All these points makes java robust.
Architecture-neutral
Portable
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhatslower than a
compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributedapplications. We may 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.
Creating hello java example
class Simple{
public static void main(String args[]){
[Link]("Hello Java");4. }
}
Let's see what is the meaning of class, public, static, void, main, String[],
[Link]().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visibleto all.
static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static method. The
main method is executed by the JVM, so it doesn't require to create object to invoke the main
method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument..
[Link]() is used print statement.
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtimeenvironment
in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). It is:
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
variables in java
variableTypes of Variable
local variable
instance variable
static
variable types of
variables in java
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance
variable .It is not declared as static.
3) Static variable
A variable that is declared as static is called static variable. It cannot be local. Example to understand the types
of variables in java
class A{
int data=50;//instance
variable static int
m=100;//static variablevoid
method()
{
int n=90;//local variable
}
}//end of class
Operators in java
Operator in java is a symbol that is used to perform operations. There are many types of
operators in java such as unary operator, arithmetic operator, relational operator, shift
operator, bitwise operator, ternary operator and assignment operator.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
if statement
if-else statement
nested if statement
if-else-if ladder
Java IF Statement
The Java if statement tests the condition. It executes the if block if condition is [Link]:
if(condition){
//code to be executed
}
if statement in javaExample:
Output:
The Java if-else statement also tests the condition. It executes the if block if condition is trueotherwise else
block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
if-else statement in javaExample:
public class IfElseExample {
public static void main(String[] args) {int number=13;
}else{
[Link]("odd number");
}
}
}
11
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{
}
else if(marks>=70 && marks<80){[Link]("B grade");
}
else if(marks>=80 && marks<90){[Link]("A grade");
}else if(marks>=90 && marks<100){[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}
Output:C grade
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
default:
code to be executed if all cases are not matched;
Example:
Syntax:
for(initialization;condition;incr/decr){
//code to be executed 3.
}
Output:
1 2 3 4 5 6 7 8 9 10
Example:
public class ForExample {
public static void main(String[] args) {3.
for(int i=1;i<=10;i++){
[Link](i);
}
while(condition){
//code to be executed 3.
}
Example:
[Link](i); 6. i++;
Output:
1 2 3 4 5 6 7 8 9 10
do{
//code to be executed
}while(condition);
Example:
Output:
1 2 3 4 5 6 7 8 9 10
1. jump-statement;
2. break;
break;
[Link](i); }
Output: 1 2 3 4
The Java continue statement is used to continue loop. It continues the current flow of the program and skips the
remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement; continue;
Java Continue Statement Example Example:
public class ContinueExample { public static void main(String[] args) {
for(int i=1;i<=10;i++){ if(i==5){
continue;
}
[Link](i);
}
}
}
Output:
1 2 3 4 6 7 8 9 10
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The comments can
be used to provide information or explanation about the variable, method, class or any statement. It can also
be used to hide program code for specific time.
The single line comment is used to comment only one line. Syntax:
Output:
10
}
}
Output:
10
The documentation comment is used to create documentation API. To create documentation API, you need to
use javadoc tool.
Syntax:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/ public class
Calculator {
/** The add() method returns addition of given numbers.*/ public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/ public static int sub(int a, int b){return a-b;}
javac [Link]
javadoc [Link]
Now, there will be HTML files created for your Calculator class in the current directory. Open the HTML files
and see the explanation of Calculator class provided through documentation comment.
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convince the
customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism. Another example
can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. Forexample: phone call, we don't know
the internal [Link] java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known asencapsulation. For
example: 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.
class name should start with uppercase letter and be a noun e.g. String, Color,
Button,System, Thread etc.
interfac should start with uppercase letter and be an adjective e.g. Runnable,
ename Remote,ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(),
main(),print(), println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
packag should be in lowercase letter e.g. java, lang, sql, util etc.
ename
consta should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY
nts
name
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It can be
physical or logical (tengible and intengible). The example of integible object is banking system.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its [Link] is used to write,
so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects arecreated. So object is the instance(result) of
a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects are
created.
class <class_name>{
data member;
method;
}
Simple Example of Object and Class
In this example, we have created a Student class that have two data members id and name. We are creating the
object of the Student class by new keyword and printing the objects value.
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
[Link]([Link]);
[Link]([Link]);
8. }
}
Output: 0 null
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
o Code Reusability
o Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){[Link](rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
[Link](111,"Karan");
[Link](222,"Aryan");
[Link]();
[Link]();
}
}
OutPut:
111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the
object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the
objects allocated in memory.
Other Example:
class Rectangle{
int length;
int width;
void insert(int l,int w){
length=l;
width=w;
}
void calculateArea(){[Link](length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle(); 12. [Link](11,5);
[Link](3,15);
[Link]();
[Link]();
16. }
17. }
Output: 55
45
o By new keyword
o By newInstance() method
o By clone() method
o By factory method etc.
Annonymous object
Annonymous simply means [Link] object that have no reference is known as annonymous
object.
If you have to use an object only once, annonymous object is a good approach.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
[Link]("factorial is "+fact);8. }
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
Output:Factorial is 120
class Rectangle
{
int length;
int width;
void insert(int l,int w)
{
length=l;
width=w;
}
void calculateArea(){[Link](length*width);}
public static void main(String args[]){
Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects
[Link](11,5);
[Link](3,15);
[Link]();
[Link]();
}
}
Output: 55
45
Method Overloading in Java
Different ways to overload the method
Output: 30 40
class Calculation2{
{[Link](a+b);}
[Link](20,20);
}
}
Output:
21.
0
40
In java, method overloading is not possible by changing the return type of the method
becausethere may occur ambiguity. Let's see how ambiguity may occur: because there was
problem:
class Calculation3{
{[Link](a+b);}
{[Link](a+b);}
int result=[Link](20,20); //Here how can java determine which sum() method should be called
10
[Link](a+b);
}
[Link](a+b+c);
}
}
}
Output: 40 60
Example of Method Overloading with Type Promotion if matching found If there are matching type arguments
in the method, type promotion is not performed.
class OverloadingCalculation2{
void sum(int a,int b)
{
[Link]("int arg method invoked");
}
void sum(long a,long b)
{
[Link]("long arg method invoked");
}
public static void main(String args[])
Constructor in Java:
Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked
at the time of object creation. It constructs the values [Link] data for the object that is why it is
known as constructor.
Rules for creating java constructor
Output:
Bike is created
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides
you a default [Link] 0 and null values are provided by default constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
[Link]();
[Link]();
}
}
Output:
111 Karan 222 Aryan
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter [Link] compiler differentiates these
constructors by taking into account the number of parameters in the list and their
type.
Output:
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
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = [Link];
name =[Link];
}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
}
}
Output:
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
[Link]=[Link];
[Link]=[Link];
[Link]();
[Link]();
}
}
Output:
111 Karan
111 Karan
There are many non-access modifiers such as static, abstract, synchronized, native, volatile,transient etc.
Here, we will learn access modifiers.
1) private access modifier
The private access modifier is accessible only within [Link]
example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is compile time error.
class A{
private int data=40;
Output:Hello
Access Modifier within class within package outside package by subclass only
outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
If you are overriding any method, overridden method (i.e. declared in subclass) must not be more
restrictive.
class A{
The default modifier is more restrictive than protected. That is why there is compile time error.