Java Unit-1 Notes
Java Unit-1 Notes
Aim
Object oriented programming aims to implement real world entities like inheritance, hiding,
polymorphism etc in programming. OOP is to bind together the data and the functions that
operate on them so that no other part of code can access this data except that function.
Oop’s is termed as Object-Oriented Programming language , based on objects and data. All
languages developed from 1990 having object-oriented features. The object-oriented
programming is the most important and powerful way of creating software. C++, Object Pascal,
Java, Python are multi-paradigm programming languages that support object-oriented
programming.
OOP allows decomposition of a problem into a number of elements called objects and then
binds data and function around these objects. The data associated with the function will be
accessed by object associated with that function only. The following figure depicts the objects
communication
The object-oriented paradigm deals with active objects instead of passive objects. A file in an
object-oriented paradigm can be packed with all the procedures—called methods in the object-
oriented paradigm—to be performed by the file: printing, copying, deleting and so on. The
program in this paradigm just sends the corresponding request to the object.
3
The structure of the Object oriented program is shown in the below figure:
Two objects can communicate via the function without knowing the data of each
another.
1. Classes
2. Objects
3. Dynamic Binding
4. Message Passing
5. Inheritance.
6. Abstraction
7. Encapsulation.
8. Polymorphism
Classes : A class is a user defined blueprint from which objects are created. It represents the
set of member functions and member variables that are common to all objects of one type. In
this figure Flower is class name and it has member functions as Turn() ,Pick() and member
variables as color.
4
Objects: Instance of class is called as object. Objects have states and behaviors. Example: A dog
has states - color, name, breed as well as behaviors – wagging the tail, barking, eating. In the
above diagram d1 is object to Dog class which acts as instance and access the variables and
methods of Dog class
Class
Dynamic Binding: In JAVA programming language objects are allocated their memory at the
time of execution using the new operator. After allocation of memory the instance variables are
binds with their associated methods at the time of execution. This type of data binding is also
called dynamic binding or late binding or execution time binding or run time binding.
Inheritance: It is defined as acquiring the properties from base class to derived class. By these
we can achieve code reusability .The base class can be called as parent class and derived class
can be called as child class. In this figure Class Rose acquires the properties of Flower data
member that is color.
5
Abstraction: Abstraction is defined as hiding the back ground details to the outside world. Only
the functionality will be provided to user. Let us consider an real time example of ATM machine
the use inserts the card and enter the pin for transition and does the transition but he doesn’t
know the working mechanism used internally for reading the card and how the card has been
connect the his account number. In object oriented programming we can abstract data and
process.
Encapsulation: Combining of data members and member functions into single unit is called
encapsulation. Encapsulation also hides the data to other class. Consider a real time example of
encapsulation; in a company there are different sections like the accounts section, finance
section, sales section etc. The finance section handles all the financial transactions and keeps
records of all the data related to finance. Similarly the sales sections handle all the sales related
activities and keep records of all the sales. Now there may arise a situation when for some
reason an official from finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of sales section. He will first have to
contact some other officer in the sales section and then request him to give the particular data.
This is what encapsulation is. Here the data of sales section and the employees that can
manipulate them are wrapped under a single name “sales section”.
Polymorphism: It is a Greek word which is Ploy means many forms . It is defined as one
method can be implemented in many forms which means one method can perform different
tasks. Lets us take an example of a car. A car has a gear transmission system. It has four front
gears and one backward gear. When the engine is accelerated then depending upon which gear
is engaged different amount power and movement is delivered to the car. The action is same
applying gear but based on the type of gear. Polymorphism can be achieved statically and
dynamically
Advantages of OOPs: Code Reuse and Recycling, Encapsulation, Design Benefits, Software
Maintenance.
6
Program is divided into objects depending Program is divided into small chunks based on
on the problem. the functions.
Each object controls its own data. Each function contains different data.
Focuses on security of the data Follows a systematic approach to solve the
irrespective of the algorithm. problem.
The main priority is data rather than Functions are more important than data in a
function in a program. program
The functions of the objects are linked via Different parts of a program are
message passing. interconnected via parameter passing.
There are mainly 4 type of applications that can be created using java programming:
Standalone Application, Web Application, Enterprise Application, Mobile Application.
Java is inherited form 2 languages that are C and C++.It is pure Object oriented
language.. Sun Microsystems initiated to develop a language for digital devices. It was invented
by James Gosling in June 1991.The language was initially called Oak. Later the project renamed
Java.
Java features :
Simple: Java is simple language to learn because all syntaxes are based on C and C++.
Platform independent : The languages like c and C++ are platform dependent means which
depends on particular operating system. Java is platform independent which means compiled
into platform specific machines while Java is a write once, run anywhere language.
Secured : Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because No explicit pointer, Java Programs run inside a virtual machine .
Robust : Robust means strong. Java is robust because it uses strong memory management.
There is a lack of pointers that avoids security problems. There is automatic garbage collection
in java .
Architecture-neutral : The Java designers made several hard decisions in the Java language and
the Java Virtual Machine in an attempt to alter this situation. Their goal was “write once; run
anywhere, anytime , forever.” To a great extent, this goal was accomplished.
Portable : Java is portable because it facilitates you to carry the Java byte code to any platform.
It doesn't require any implementation.
Dynamic : Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Scalability : Java platform can be implemented on wide range of computers with varying
levels of resources. This is possible because java is compact and platform independent.
Java virtual Machine is the heart of entire java program execution process. It takes the .Class
file as input and converts the byte code into machine language that is executed by processor.
9
Class Loader : Java file written by the programmer will be compiles by java compiler that
generates Class file called as byte code this class file will be given to class loader .It loads .class
file into memory.
Method Area: Method area stores code of variables and code in the methods (functions)
Heap: objects will create in heap memory. Whenever JVM loads a class, a method and heap
area is immediately created in it.
Java Stacks: Method area is used to store methods. If java program requires more memory to
store data and results then java stacks are used.
PC(Program counter) registers: Program Counter is a register which stores the address the
method Instruction to be executed.
Native Method stacks: Native methods such as C and C++ functions will be executed in native
method stack .To execute native methods it requires native method library these are connected
to JVM by native method interface.
Execution Engine contains interpreter and JIT(Just It Tie ) compiler which are responsible for
converting byte code to machine instructions .JVM uses both interpreter and compiler .This
technique is called adaptive optimizer.
As java is pure object oriented language everything in java program should place in class even
main should be placed in a class.
sample program
class Example
{
public static void main(String args[])
{
System.out.println("Hello World");
}}
1. comments
While writing a program it is important it should be readable and understandable for this
purpose we use comments .When we write a comment in a program we can understand what
the is program is doing and users can understand the code. There are 3 types of comments
3) Java documentation comments: these are used for giving description for every feature
in a java program. This description proves helpful in creation of .html file called API It
starts wit /** and ends with */ for example
/** description about a class */
Code
/** description about method */
An access specifier is a key word that tells us how to access the members of a class .We can use
access specifiers before a class and its members. There are four access specifiers available in
Java:
private: 'private' members of a class are not accessible anywhere outside the class. They are
accessible only within the class by the methods of that class. In this example the program
variable a , msg() method is of private type so they can’t be accessed outside the class.
class A{ public class Simple{
private int a=40; public static void main(String args[]){
private void msg() A obj=new A();
{ System.out.println(obj.a);//Compile Time Error
System.out.println("Hello java"); obj.msg();//Compile Time Error
} }
} }
public: 'public' members of a class are accessible everywhere. Outside the class. So any other
program can read them and use them.
class A{ public class Simple{
public int a=40; public static void main(String args[]){
public void msg() A obj=new A();
{ System.out.println(obj.a);
System.out.println("Hello java"); obj.msg();
}} } }
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.
class A{ public class Simple{
protected int a=40; public static void main(String args[]){
protected void msg() A obj=new A();
{ System.out.println(obj.a);//Compile Time Erro
System.out.println("Hello java" r
); obj.msg();//Compile Time Error
}} } }
12
default: If no access specifier is given, then the Java compiler uses a 'default' access specifier.
'default' members are accessible outside the class, but within the same directory. ·
class A{ public class Simple{
int a=40; public static void main(String args[]){
void msg() A obj=new A();
{ System.out.println(obj.a);
System.out.println("Hello java"); obj.msg();
} }
} }
Q9. Statements & Control Flow Statement
A statement specifies an action in a Java program, such as assigning the sum of x and y to z,
printing a message to the standard output, writing data to a file, etc.
Declaration statement
Expression statement
Control flow statement
//Assignment expressions
System.out.println("This is a statement");
someMethod(param1, param2);
By default, all statements in a Java program are executed in the order they appear in the
program. Sometimes you may want to execute a set of statements repeatedly for a number of
times or as long as a particular condition is true.
In Java we have eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The primitive types are also commonly referred to as simple types; these can be put in
four groups:
• Integers: It has byte, short, int, and long, which are for whole-valued signed numbers.
• Floating-point: It has float and double, which represent numbers with fractional precision.
• Characters this has char, which represents symbols in a character set
• Boolean: It is a special type for representing true/false values.
Integer types:
Numbers without fractional parts and decimal parts is called integers
For example long is a signed 64-bit type and is useful for those occasions where an int type is
not large enough to hold the desired value. The range of a long is quite large. This makes it
useful when big, whole numbers are needed.
14
Floating-Point Types : Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision
difference between float and double : Float can represent up to 7 digits accurately after
decimal point, whereas double can represent up to 15 digits accurately after decimal point.
float a=5.7F
the variable ‘a’ is having a value 5.7 F if F is not written at the end, by default JVM would have
taken it as double and allocates 8 bytes by placing F or f at the end of a value we can ask the
JVM to consider it as a float value and allocates only 4 bytes.
Characters
This data type represents a single character
Data Type Size range
Char 2 bytes 0 to 65536
Characters are represented as char in java. In C/C++ char is 8 bits wide. This is not the case in
Java. Java uses Unicode to represent characters. Unicode defines a fully international character
set that can represent all of the characters found in all human languages. It is a unification of
dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and
many more. For this purpose, it requires 16 bits.
Booleans : Java has a primitive type, called boolean, which have two values either true or false
This is the type returned by all relational operators, as in the case of a < b. boolean is also the
type required by the conditional expressions that govern the control statements such as if and
for. True or false are represented as 0(false) or 1(true)
The Scope and Lifetime of Variables : The scope of a variable is defined as within the block or
outside the block. Block starts 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. A
scope determines what objects are visible to other parts of your program. Lifetime of a variable
is defined as how long the variable exists before it is destroyed. Destroying variables refers to
15
de-allocating the memory that was allotted to the variables it was declared It also determines
the lifetime of those objects.
Languages like C and C++ defines the scope in two ways i.e. local and global variables .local
variables are the variables that are defined inside main() method global variables are that are
defined outside the main() method. However in java two major scopes that are those defined
by a class and those defined by a method.
Java Variable Types : Java has different of variables different types depending upon they
declared.
Local Variables : The scope of local variable is within the block or a method body are a
constructor Local variables are created when control enters into the block or
constructor of method's body and are destroyed once the control exits from the block.
Local variables are only visible to blocks where they are declared; they are not
accessible to outside block.
16
Instance Variables or Non-Static Fields : Variables that are non-static and declared out the block
or a constructor or a method is called instance variable. Instance variables are created when an
object of a class is created by using new keyword. Objects store their states in non-static
instance variables.
Class Variables or Static Fields : Class variables in Java are fields declared with static keyword.
Modifier static informs the compiler that there will be only one copy of such variables created
regardless of how many objects of this class are created. Static variables are created when a
class is loaded into the memory by the class loader and destroyed when a class is destroyed or
unloaded. Visibility of static fields will depend upon access modifiers. Default vales given to the
static members will follow the same rule as it is done in instance variables.
The main() method : If main method is not written in a java program JVM will not execute
it, main () is the starting point for JVM to start execution of a java program. Next to class is
JVM is the program written by java soft people and main () is written by us. Since main ()
method should be available to JVM, it should be declared as public. As main () is a method and
a method is executed by calling a method.
call a method : Create a object to class to which the method belongs to. The syntax of
creating the object is:
We call main () method without creating an object .such methods are called static
methods and should be declared as static. If a method is not returning any value then
should be defined as void before method name .void means no value i.e. main ()
method returns nothing. main () method is followed by String args[] main () method also
accepts some data from us. For example, it accepts group of strings, which is also called
as sting type array.
args[] is a array of string type it stores group of stings ,it also stores numbers but
stores it in the form of string only. The values passed to main are called as arguments
these arguments are stored in args[].
What happens if Sting args[] is not written in main() method : When main () method is
written without String args[] as Public static void main ().The code will compile but JVM
cannot run the code because it cannot recognize the main () method as the method
from where it should start execution of java program.JVM looks for main () method with
string type as parameter.
header file : A header file is the file which contains functions code of function in a
program. For example <stdio.h> contains functions like printf(),sacnf() etc., so if we what to
use this functions we have include<stdio.h>. But in java to include a header file by using
import statement.
Example:
Import java.lang.system;
When we use include statement the compiler goes to library and searches for that particular
header file .if it was found it copies the content of header file into program where the # include
is statement is written. Thus if program has 3lines and header file has 100 lines finally it has
103 lines which occupies the program memory which is wasted and processor tie is wasted. But
in java we use import statement instead of include by using import Java JVM go to library
execute the code there and substitute the result into program .so the addition storage for
header file saved and processor time is not wasted.
The import statement is used to import classes or interfaces in packages. A package is a kind of
directory that contains group of classes and interfaces. Java has several such packages in its
library.
18
Java library
|
Packages
|
Class’s |interfaces
|
Methods
Identifiers: Identifiers are used for class names, method names, and variable names. An
identifier may be uppercase and lowercase letters, numbers, or the underscore and dollar-sign
characters. They must not begin with a number, lest they be confused with a numeric literal.
Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Literals : A literal represents a value that is stored into a variable directly in the program.
Ex : boolean a= true ; short s = 1;
Integer literals
Float literals
Character literals
String literals
Boolean literals
19
Q16. Operators
Operator is a symbol which performs operations, operator has to be placed between operands .i.e.
There are three types of operators Unary, Binary and Ternary Operator.
Unary : In Java, unary arithmetic operators are used to increasing or decreasing the value of an
operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator
decreases a value. Increment and decrement unary operator works as follows:
Syntax:
val++;
val--;
These two operators have two forms: Postfix and Prefix. Both do increment or decrement in
appropriate variables. These two operators can be placed before or after of variables. When it is
placed before the variable, it is called prefix. And when it is placed after, it is called postfix.
Following example table, demonstrates the work of Increment and decrement operators with
postfix and prefix:
Example Description
val = a++; Store the value of "a" in "val" then increments.
val = a--; Store the value of "a" in "val" then decrements.
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".
Ternary operators: ternary operator is also known as the conditional operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of the operator
is to decide, which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true: value if false
Bitwise Operators :
Bitwise OR (|) : This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND (&) :This operator is binary operator, denoted by ‘&’. It returns bit by bit AND of
input values, i.e, if both bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR (^) : This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of
input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise Complement (~) :This operator is unary operator, denoted by ‘~’. It returns the one’s
compliment representation of the input value, i.e, with all bits inversed, means it makes every 0
to 1, and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10 will be -6.
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Shift Operators: These operators are used to shift the bits of a number left or right thereby
multiplying or dividing the number by two respectively.
Signed Right shift operator (>>) :Shifts the bits of the number to the right and fills 0 on voids
left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of
dividing the number with some power of two.
22
For example,
Example 1:
a = 10
a>>1 = 5
Example 2:
a = -10
a>>1 = -5
Unsigned Right shift operator (>>>) : Shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is
signed, and will extend the sign bit.
For example,
Example 1:
a = 10
a>>>1 = 5
Example 2:
a = -10
a>>>1 = 2147483643
DOES NOT preserve the sign bit.
Left shift operator (<<) : Shifts the bits of the number to the left and fills 0 on voids left as a
result. Similar effect as of multiplying the number with some power of two.
For example,
a = 5 = 0000 0101
b = -10 = 1111 0110
Unsigned Left shift operator (<<<) : Unlike unsigned Right Shift, there is no “<<<" operator
in Java, because the logical (<<) and arithmetic left-shift (<<<) operations are identical.
int a = 5;
int b = -10;
a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821
24
The order of precedence for Java operators, from highest to lowest. operators: parentheses,
square brackets, and the dot operator. Technically, these are called separators.
One type of value is assigned to another type. If the two types are compatible, then Java will
perform the conversion automatically (this is also called as implicit type conversion) . Using cast
operator which performs explicit conversion.
a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.
long l = i;
float f = l;
25
int a=1234;
byte b=(byte) a;
int a=258;
byte b;
b=(byte) a;
i. Selection statements
ii. Iteration statements
iii. Jump statements
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods
are said to be overloaded, and the process is referred to as method overloading. Method
overloading is one of the ways that Java supports polymorphism.When an overloaded method
is invoked,