OOM Chap-2 Introduction To Java
OOM Chap-2 Introduction To Java
ü INTRODUCTION TO JAVA
ü INHERITANCE
ü POLYMORPHISM
ü EXCEPTION HANDLING
PREPARED BY
Nishita Kindo (Lecturer, CSE)
BOSE, Cuttack
OOP with JAVA : INTRODUCTION TO JAVA
INTRODUCTION TO JAVA : What is Java?
What is Java ?
Application of Java
According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are asfollows:
Ø Desktop Applications such as acrobat reader, media player, antivirus, etc.
Ø Web Applications such as irctc.co.in, javatpoint.com, etc.
Ø Enterprise Applications such as banking applications.
Ø Mobile
Ø Embedded System
Ø Smart Card
Ø Robotics
Ø Games, etc.
There are mainly 4 types of applications that can be created using Java
programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window -
based applications. These are traditional software that we need to install on every
machine. Examples of standalone application are Media player, antivirus, etc. AWT and
Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is
called a web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc.
is called enterprise application. It has advantages of the high -level security, load
balancing, and clustering. In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile
application. Currently, Android and Java ME are used for creating mobile applications.
Java Platforms / Editions
C vs Java
C Java
C is a Procedural Programming
Java is an Object -Oriented language.
Language.
In the C declaration variable are declared In Java, you can declare a variable
at the beginning of theblock. anywhere.
Free is a variable used for freeing the A compiler will free up the memory by
memory in C. calling the garbage collector.
C++ Java
C++ is platform -dependent. Java is platform-independent.
C++ supports the goto statement. Java doesn't support the goto statement.
C++ supports both call by value and call Java supports call by value only. There is
by reference. no call by reference in java.
C++ doesn't have built -in support for Java has built -in thread support.
threads. It relies on third -party libraries
for thread support.
JVM Architecture
Ø Let's understand the Architecture of JVM. It contains classloader, memory area,
execution engine etc.
Ø Working of Java Virtual Machine (JVM) & its Architecture
1) Class Loader
The class loader is a subsystem used for loading class files. It performs
three major functions viz. Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant
runtime pool, and the code for methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in
the heap. This memory is common and shared across multiple threads.
Java language Stacks store local variables, and it’s partial results. Each
thread has its own JVM stack, created simultaneously as the thread is
created. A new frame is created whenever a method is invoked, and it is
deleted when method invocation process is complete.
5) PC Registers
7) Execution Engine
class Simple{
System.out.println("Hello Java");
Output:Hello Java
Parameters used in First Java Program
Ø Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
• class keyword is used to declare a class in java.
• public keyword is an access modifier which represents visibility. It means it is
visible to all.
• static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to
create an object to invoke the static method. The main method is executed by
the JVM, so it doesn't requir e to create an 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 the starting point of the program.
• String[] args is used for command line argument. We will le arn it later.
• 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.
INTRODUCTION TO JAVA : Variables and Data types
Variables in Java
A variable is a name which is associated with a value that can be changed. For
example when I write int i=10; here variable name is i which is associated with value 10,
int is a data type that represents that this variable can hold integer values.
How to Declare a variable in Java
Ø To declare a variable follow this syntax:
data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then
later assign the value to it.
Ø For example: Here num is a variable and int is a data type.
int num;
Ø Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
Variables naming convention in java
1) Variables naming cannot contain white spaces, for example: int number = 100; is
invalid because the variable name has space in it.
2) Variable name can begin with special characters such as $ and _
3) As per the java coding standards the variable name should begin with a lower case
letter, for example int number; For lengthy variables names that has more than one
words do it like this: int smallNumber; int bigNumber; (start the second word with
capital letter).
4) Variable names are case sensitive in Java.
Types of Variables in Java
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
Static variables are also known as class variable because they are
associated with the class and common for all the instances of class. For example, If I
create three objects of a class and access this static variable, it would be common for
all, the changes made to the variable using one of the object would reflect when you
access it through other objects.
Instance variable
Each instance(objects) of class has its own copy of instance variable. Unlike static
variable, instance variables have their own separate copy of instance variable. We
have changed the instance variable value using object obj2 in the following program
and when we disp layed the variable using all three objects, only the obj2 value got
changed, others remain unchanged. This shows that they have their own copy of
instance variable.
Local Variable
These variables are declared inside method of the class. Their scope is limited to the
method which means that You can’t change th eir values and access them outside of
the method.
In this example, I have declared the instance variable with the same name as local
variable, this is to demonstrate the scope of local variables.
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
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 i s 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,808 and
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
Double Data Type
• 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 s ingle 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 letterA = 'A'
• It is because java uses Unicode system not ASCII code system. The \ u0000 is
the lowest range of Unicode system. To get detail explanation about Unicode
visit next page.
Ø These are the datatypes which have instances like objects. Hence, they are called
reference variables. They are primarily classes, arrays, strings or interfaces.
a. Classes in Java
• These are the special user defined data type. It has member variables and
class methods. T hey are blueprinted by objects.
• Java program to illustrate classes:
• These are similar to classes. However there is one prime difference, i.e. the
methods are abstract by default. i.e., they have no body.
• Similarly, like objects, interfaces are also the blueprints of a class.
• If the class implements an interface, then it is supposed to add detail to every
function of the interface. If not, then we must declare the class as abstract.
• Example program to illustrate interfaces in Java:
c. Strings in Java
Java
d. Arrays in Java
import java.io. * ;
import java.util. * ;
class JavaArray {
public static void main(String[] args) throws IOException{
int i;
Scanner sc = new Scanner(System. in );
int arr[] = new int[] {
1,
2,
3,
4,
5
};
int arr1[] = new int[5];
for (i = 0; i < 5; i++) {
System.out.println("Enter your number");
arr1[i] = sc.nextInt();
}
System.out.println(“The array which was previously assigned”);
for (i = 0; i < 5; i++) {
System.out.println(arr[i]);
}
System.out.println(""); System.out.println("The
array you entered is:");for (i = 0; i < 5; i++) {
System.out.println(arr1[i]);
}}}
Output:
Enter yournumber
4
Enter yournumber
1
Enter yournumber
2
Enter yournumber
3
Enter your number
4The array which was previously assigned:
1
2
3
4
5
The array you entered is:
4
1
2
3
4
int x =101;
Octal (Base 8)
int x = 0146;
Digits 0 -9 are allowed and also characters from a -f are allowed in this form.
Furthermore, both uppercase and lowercase characters can be used, Java
provides an exception here.
int x = 0X123Face;
Binary
A literal in this type should have a prefix 0b and 0B, from 1.7 one can also
specify in binary literals, i.e. 0 and 1.
int x = 0b1111;
Example-
Output-
Integral -Literal -in-java
Here, datatypes can only be specified in decimal forms and not in octal or
hexadecimal form.
• Single Quote
char ch = 'a';
• Char as Integral
A char literal in Java can specify as integral literal which also
represents the Unicode value of a character.
char ch = 062;
• Unicode Representation
• Escape Sequence
Example-
Java String literals are any sequence of characters with a double quote.
String s = "Hello";
They may not contain unescaped newline or linefeed characters. However, the Java
compiler will evaluate compile -time expressions.
Example-
boolean b = true;
Example-
Widening casting is done automatically when passing a smaller size type to a larger
size type:
Example
Example
Arithmetic Operators
Assignment Operators
Logical Operators
Relational Operators
Unary Operators
Bitwise Operators
Ternary Operators
Shift Operators
^= Performs exponential c ^= a
(power) calculation on
operators and assign value
to the left operand
Consider the below example:
These operators compare the values on either side of them and decide the relation
among them. Assume A = 10 and B = 20.
Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
Syntax:
Shift operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number. There are three different types of shift operators, namely left
shift operator()<<, signed right operator(>>) and unsigned right shift operator(>>>).
Syntax:
Java Statements
• In Java, each statement is a complete unit of execution. For example,
int score = 9*5;
• Here, we have a statement. The complete execution of this statement involves
multiplying integers 9 and 5 and then assigning the result to the variable
score.
• In the above statement, we have an expression 9 * 5. In Java, expressions are
part of statements.
Expression statements
We can convert an expression into a statement by terminating the expression
with a ;. These are known as expression statements. For example,
// expression
number = 10
/ / statement
number = 10;
++number
/ / statement
++number;
Similarly, ++number is an expression whereas ++number; is a statement.
Declaration Statements
In Java, declaration statements are used for declaring variables. For example,
class IfElse {
public static void main(String[] args) {
int number = 10;
if (expression1) {
/ / codes
}
else if(expression2) {
/ / codes
}
else if (expression3) {
/ / codes
}
.
.
else {
/ / codes
}
Ø Here, if statements are executed from the top towards the bottom. As soon as
the test expression is true, codes inside the body of that the if statement is
executed. Then, the control of the program jumps outside the if -else-if ladder.
Ø If all test expressions are false, codes inside the body of else is executed.
int number = 0;
The number is 0.
switch (variable/expression) {
case value1:
// statements of case1
break;
case value2:
// statements of case2
break;
.. .. ...
.. .. ...
default:
/ / default statements
}
Ø The switch statement evaluates the expression (mostly variable) and
compares it with values (can be expressions) of each case label.
Ø Now, if the value matches a certain case label, then all the statements of the
matching case label are executed.
Ø For example, if the variable/ expression is equal to value2. In this case, all
statements of that matching case (statements of case2) are executed.
Ø Notice, the use of break statements in each case. The break statement is
used to terminate t he execution of the switch statement.
Ø It is important because if break is not used all the statements after the
matching case are executed in sequence until the end of the switch
statement.
int week = 4;
String day;
Output:
The day is Wednesday
Ø In the above example, we have used the switch statement to find out the
day of a week. Here, we have a variable week that holds an integer value.
The value is compared to each case inside the switch block.
Ø Here the value of week is 4. Hence it matches the case 4. So the statement
inside case 4 is executed.
while (testExpression) {
/ / codes inside the body of while loop
}
How while loop works?
In the above syntax, the test expression inside parenthesis is a boolean expression.
If the test expression is evaluated to true,
do {
/ / codes inside body of do while loop
} while (testExpression);
import java.util.Scanner;
class Sum {
public static void main(String[] args) {
Double number, sum = 0.0;
/ / creates an object of Scanner class
Scanner input = new Scanner(System.in);
do {
/ / takes input from the user
System.out.print("Enter a number: ");
number = input.nextDouble();
sum += number;
} while (number != 0.0); / / test expression
System.out.println("Sum=" + sum);
}
}
Output:
Enter a number: 2.5
Enter a number: 23.3
Enter a number: -4.2
Enter a number: 3.4
Enter a number: 0
Sum = 25.0
break;
class Test {
public static void main(String[] args) {
/ / for loop
for (int i = 1; i <= 10; ++i) {
/ / if the value of i is 5 the loop terminates
if (i == 5){
break;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
Ø In the above program, we are using the for loop to print the value of i in
each iteration. To know how for loop works, visit the Java for loop. Here,
notice the statement,
if (i == 5) {
break;
}
Ø This means when the value of i is equal to 5, the loop terminates. Hence,
we get the output with values less than 5 only.
Java continue Statement
Ø While working with loops, it is sometimes desirable to skip some
statements inside the loop or terminate the loop immediately without
checking the test expression.
Ø In such cases, break and continue statements are used. To learn about the
break statement, visit Java break.
Ø The continue statement in Java skips the current iteration of a loop (for,
while, do...while, etc) and the control of the program moves to the end of
the loop. And, the test expression of a loop is evaluated.
Ø In the case of for loop, the update statement is executed before the test
expression.
Ø The continue statement is almost always used in decision -making
statements (if...else Statement). It's syntax is:
continue;
/ / for loop
for (int i = 1; i <= 10; ++i) {
/ / if value of i is between 4 and 9, continue is executed
if (i > 4 && i < 9) {
continue;
}
System.out.println(i);
}
}
}
Output:
1
2
3
4
9
10
Ø In the above program, we are using for loop to print the value of i in each
iteration. To know how for loop works, visit Java for loop. Here, notice the
statement,
if (i > 5 && i < 9) {
continue;
}
Ø This means when the value of i becomes more than 4 and less then 9, the print
statement inside the loop is skipped. Hence, we get the output with values 5,
6, 7, and 8 skipped.