Module 1
Module 1
Module 1
Class
Object
Message Passing
Encapsulation
Inheritance
Polymorphism
CLASS AND OBJECT
Class is a template that defines the form of an object.
It specifies both data and code that will operate on that data
Class is essentially a set of plans that specify how to build an object.
Class is a logical abstraction.
Classes are user-defined data types. A class is a collection of objects of similar type.
• The entire set of data and code of an object can be made a user-defined data type with
the help of a class. Objects are variables of the type class.
• Once a class has been defined, we can create any number of objects belonging
to that class.
Class Composition
EXAMPLE 2- BANK ACCOUNT
• The "account" class describes the attributes and
behaviors of bank accounts.
• In Java, message passing allows objects to interact with each other by invoking methods and passing data between
them.
• Java Virtual Machine (JVM) in Java is the heart of the entire execution process of the Java
program. It is basically a program that provides the runtime environment necessary for Java
programs to execute.
• The specification of JVM is provided by Sun Microsystem whose implementation provides a
runtime environment to execute our Java applications. JVM implementation is known as
Java Runtime Environment (JRE).
• Since JVM is platform-dependent, therefore, it is available for many hardware and software
platforms.The most popular JVM is HotSpot that is produced by Oracle. It is available for many
operating systems such as Windows, Linux, Solaris, and Mac OS.
• We cannot run the Java program unless JVM is available for the appropriate hardware and
operating system platform.
Java Virtual Machine performs the following operations for execution of the program. They are as
follows:
a) Load the code into memory.
b) Verifies the code.
c) Executes the code
d) Provides runtime environment.
Bytecode in Java:
• Bytecode in Java is a highly optimized set of instructions for the Java Virtual Machine (JVM)
that reads and interprets to run the java program.
• A bytecode is a binary program code that can only run on JVM. In other words, it is a machine
language (code) for JVM in the form of .class file, but it is not machine specific because it is not a
native code.
• Java bytecode has two most important characteristics that are as follows:
• Byte code is independent of processor, i.e., Java program can be executed on any processor
architecture. It does not depend on operating systems such as Windows, Linux, and Mac OS.
How does Bytecode work in Java?
When we write a java program, the source code (in the form of .java file) is compiled by Java compiler
and converted into byte code in the form of a .class file.This compiled byte code is platform
independent code that can be run on any different computer machine on which JVM interpreter is
installed. In simple words, write once, compile and run anywhere (WOCRA).
A compiler in Java is a computer program that is used for compiling Java programs. It is platform-
independent. It converts (translates) source code (.java file) into bytecode (.class file).
Java Interpreter translates (converts) bytecode to machine code(native code) line by line during
runtime.
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 do many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications.
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 lightweight 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 extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Java Basic Syntax
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.
Object – Objects have states and behaviors. Example: A dog has states-color, name, and
breed as well as behaviors -wagging, barking, and eating. An object is an instance of a
class.
Class – A class can be defined as a template/blue print that describes the behaviors/states
that object of its type support.
Methods – A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables – Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables
/* This is my first java program. This will print 'Hello World' as the output */
public class MyFirstJavaProgram
{
public static void main(String[]args)
{
System.out.println("Hello World"); // prints Hello World
}
}
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names – For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case. Example class MyFirstJavaClass.
Method Names – All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case. Example public void myMethodName().
Program File Name – Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name, then the file should be
saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) – Java program processing starts from the main()
method, which is a mandatory part of every Java program.
/*Here is another short example. Call this file "Example2.java".*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
Short:
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
Maximum value is 32,767(inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int.
Default value is 0.
Example: short s= 10000, short r = -20000
int:
int data type is a 32-bit signed two's complement integer.
Minimum value is – 2,147,483,648.(-2^31).
Maximum value is 2,147,483,647(inclusive).(2^31 -1).
int is generally used as the default data type for integral values unless there is a concern
about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long:
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: int a = 100000L, int b = -200000L
float:
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Double:
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values, generally the
default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
Here is a short program that uses double variables to compute the area of a circle:
boolean:
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
Here is a program that demonstrates the boolean type:
b is false
b is true
This is executed.
10 > 9 is true
char:
Literals
• Literals represent fixed values in a source code. These are similar
to standard variables with the difference that these are constant.
• Integer
• Floating Point
• Boolean
• Character
• String
Example:
public class JavaIntegerLiterals {
public static void main (String[]args){
//initialize variables with integer literals
int decimalNum = 25;
int hexaNum = 0xa5;
int binaryNum = 0b1101;
int octalNum = 0172;
//print out the values of the literal
System.out.println("Decimal Integer: " + decimalNum);
System.out.println("Octal Integer: " + octalNum);
System.out.println("Hexadecimal Integer: " + hexaNum);
System.out.println("Binary Integer: " + binaryNum);
}
}
Output
Decimal Integer: 25
Octal Integer: 122
Hexadecimal Integer: 165
Binary Integer: 13
Here data type is one of Java's data types and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b and c.
int a = 10, b = 10;
// Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time
the variable is declared.
For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:
In Java, the two major scopes are those defined by a class and those defined by a method.
A block is begun with an opening curly brace and ended by a closing curly brace. A block
defines a scope. Thus, each time you start a new block, you are creating a new scope. As
cope determines what objects are visible to other parts of your program, it also determines
the lifetime of those objects.
Variables defined inside scope can't be accessed outside the scope of that variable.
Thus, when you declare a variable within a scope, you are localizing that variable and
protecting it from unauthorized access and/or modification.
Indeed, the scope rules provide the foundation for encapsulation.
x and y: 10 20
x is 40
Here is another important point to remember: variables are created when their scope is
entered, and destroyed when their scope is left. This means that a variable will not hold its
value once it has gone out of scope.
Also, a variable declared within a block will lose its value when the block is left. Thus, the
lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each
time the block in which it is declared is entered.
For example, consider the next program.
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
Although the automatic type conversions are helpful, they will not fulfill all needs. For
example, what if you want to assign an int value to a byte variable? This conversion will
not be performed automatically, because a byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion, since you are explicitly making
the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion. It has this general form:
(target_type) value
Example:
int a;
byte b;
// ...
b = (byte) a;
The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("Conversion of double to int");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("Conversion of double to byte");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Java Operators
Like other programming languages, there are arithmetic operators, bitwise operators and logical
operators in Java.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists all the arithmetic operators in Java.
The following program illustrates the increment operator.
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
a=2
b=3
c=4
d=1
Original value of a: 64
i and b: 256 0
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.
The following code fragment shifts the value 32 to the right by two positions, resulting in a being
set to 8:
int a = 32;
a = a >> 2; // a now contains 8
When a value has bits that are ―shifted off, those bits are lost. For example, the next code
fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be
lost, resulting again in a being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35 >> 2
1000
a = a >> 4;
a >>= 4;
The following two statements, which result in a being assigned the bitwise expression a OR b,
are equivalent:
a = a | b;
a |= b;
Relational Operators
The relational operators determine the relationship that one operand has to the
other. Specifically, they determine equality and ordering.
Boolean Logical Operators
The Boolean logical operators shown here operate only on Boolean operands. All of the binary
logical operators combine two Boolean values to form a resultant Boolean value.
Here is a program that is almost the same as the BitLogic example shown earlier, but it operates
on Boolean logical values instead of binary bits:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
After running this program, you will see that the same logical rules apply to Boolean values as
they did to bits. As you can see from the following output, the string representation of a
Java Boolean value is one of the literal values true or false.
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the? Operator. The ? has this general form:
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true,
then expression2 is evaluated; otherwise, expression3 is evaluated.