Java Notes Lect
Java Notes Lect
CONCEPTS
1. Object
Objects are important runtime entities in object oriented method. They may characterize a
location, a bank account, and a table of data or any entry that the program must handle. Each
object holds data and code to operate the data. Object can interact without having to identify
the details of each other‘s data or code. It is sufficient to identify the type of message
received and the type of reply returned by the objects.
2. Classes
A class is a set of objects with similar properties (attributes), common behaviour (operations),
and common link to other objects. The complete set of data and code of an object can be
made a user defined data type with the help of class.
The objects are variable of type class. A class is a collection of objects of similar type.
Classes are user defined data types and work like the build in type of the programming
language. Once the class has been defined, we can make any number of objects belonging to
that class. Each object is related with the data of type class with which they are formed.
1
3. Data Abstraction
Data abstraction refers to the act of representing important description without including the
background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, cost and functions operate on these attributes. They summarize all the important
properties of the objects that are to be created.
Classes use the concepts of data abstraction and it is called as Abstract Data Type (ADT).
4. Data Encapsulation
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It is
most useful feature of class. The data is not easy to get to the outside world and only those
functions which are enclosed in the class can access it.
These functions provide the boundary between Object‘s data and program. This insulation of
data from direct access by the program is called as Data hiding.
5. Inheritance
Inheritance is the process by which objects of one class can get the properties of objects of
another class. Inheritance means one class of objects inherits the data and behaviours from
another class. Inheritance maintains the hierarchical classification in which a class inherits
from its parents.
Inheritance provides the important feature of OOP that is reusability. That means we can
include additional characteristics to an existing class without modification. This is possible
deriving a new class from existing one.
In other words, it is property of object-oriented systems that allow objects to be built from
other objects. Inheritance allows openly taking help of the commonality of objects when
constructing new classes. Inheritance is a relationship between classes where one class is the
parent class of another (derived) class. The derived class holds the properties and behaviour
of base class in addition to the properties and behaviour of derived class.
6. Polymorphism
(Poly means “many” and morph means “form”). Polymorphism means the ability to take
more than one form. Polymorphism plays a main role in allocate objects having different
internal structures to share the same external interface. This means that a general class of
operations may be accessed in the same manner even though specific activities associated
with each operation may differ. Polymorphism is broadly used in implementing inheritance.
It means objects that can take on or assume many different forms. Polymorphism means that
the same operations may behave differently on different classes. Booch defines
polymorphism as the relationship of objects many different classes by some common super
class. Polymorphism allows us to write generic, reusable code more easily, because we can
specify general instructions and delegate the implementation detail to the objects involved.
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the
call. Dynamic binding means that the code related with a given procedure call is not known
until the time of the call at run time.
Dynamic binding is associated polymorphism and inheritance.
2
Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.Originally called Oak by James Gosling (one of the inventor of the
language). Java was invented for the development of software for consumer electronic devices
like TVs, toasters, etc. The main aim had to make java simple, portable and reliable.
Java Authors: James, Arthur Van, and others.
Java supports the feature portability. Java programs can be easily moved from one computer
system to another and anywhere. Changes and upgrades in operating systems, processors and
system resources will not force any alteration in Java programs. This is reason why Java has
become a trendy language for programming on Internet which interconnects different kind of
systems worldwide. Java certifies portability in two ways.
First way is, Java compiler generates the byte code and that can be executed on any machine.
Second way is, size of primitive data types are machine independent.
3. Object- oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All program code
and data exist in objects and classes. Java comes with an extensive set of classes; organize in
packages that can be used in program by Inheritance. The object model in Java is trouble-free and
easy to enlarge.
4. Robust and secure
Java is a most strong language which provides many securities to make certain reliable code. It is
design as garbage –collected language, which helps the programmers virtually from all memory
management problems. Java also includes the concept of exception handling, which detain
serious errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer use this
language for programming on Internet.
3
The absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.
5. Distributed
Java is called as Distributed language for construct applications on networks which can contribute
both data and programs. Java applications can open and access remote objects on Internet easily.
That means multiple programmers at multiple remote locations to work together on single task.
6. Simple and small
Java is very small and simple language. Java does not use pointer and header files, goto
statements, etc. It eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive
Java performance is very extraordinary for an interpreted language, majorly due to the use of
intermediate byte code. Java architecture is also designed to reduce overheads during runtime.
The incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible
Java is also dynamic language. Java is capable of dynamically linking in new class, libraries,
methods and objects. Java can also establish the type of class through the query building it
possible to either dynamically link or abort the program, depending on the reply.
Java program is support functions written in other language such as C and C++, known as native
methods.
Comparison in Java and C++
4
11 There are no header files in Java. We have to use header file
in C++.
As we know that all programming language compilers convert the source code to machine code.
Same job done by Java Compiler to run a Java program, but the difference is that Java compiler
convert the source code into Intermediate code is called as byte code. This machine is called the
Java Virtual machine and it exists only inside the computer memory.
5
LECTURE 2: JAVA RUN- TIME ENVIRONMENT, JAVA DEVELOPERS KIT
Java environment includes a number of development tools, classes and methods. The
development tools are part of the system known as Java Development Kit (JDK) and the classes
and methods are part of the Java Standard Library (JSL), also known as the Application
Programming Interface (API).
Java Development kit (JDK) – The JDK comes with a set of tools that are used for developing
and running Java program. It includes:
For compiling and running the program we have to use following commands:
In java, we can use any text editor for writing program and then save that program with “.java
extension. Java compiler convert the source code or program in bytecode and interpreter convert
“.java file in “.class file.
Syntax:
C:\javac filename.java
If my filename is “abc.java” then the syntax will be
C:\javac abc.java
b) java(Java Interpreter)
As we learn that, we can use any text editor for writing program and then save that program with
“.java extension. Java compiler convert the source code or program in bytecode and interpreter
convert “.java file in “.class file.
Syntax:
C:\java filename
If my filename is abc.java then the syntax will be
C:\java abc
6
Simple Java Program
class FirstProgram
{
public static void main(String args[])
{
System.out.println(“This is my first program”);
}
}
The file must be named “FirstProgram.java” to equivalent the class name containing the main
method.
Java is case sensitive. This program defines a class called FirstProgram.
A class is an object oriented term. It is designed to perform a specific task. A Java class is defined
by its class name, an open curly brace, a list of methods and fields, and a close curly brace.
The name of the class is made of alphabetical characters and digits without spaces, the first
character must be alphabetical.
The line public static void main(String args[]) shows where the program will start running. The
word main means that this is the main method.
The JVM starts running any program by executing this method first.
The main method in “FirstProgram.java consists of a single statement
Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program.
For this reason, the next explanation is showing the steps.
Command line arguments are parameters that are supplied to the application program at the
time of invoking its execution. They must be supplied at the time of its execution following the
file name.
In the main () method, the args is confirmed as an array of string known as string objects. Any
argument provided in the command line at the time of program execution, are accepted to the
array args as its elements. Using index or subscripted entry can access the individual elements of
an array. The number of element in the array args can be getting with the length parameter.
7
For example:
class Add
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
int c=a+b;
System.out.println(“Addition is=”+c);
}
}
output:
c:\javac Add.java
c:\java Add 5 2
Addition is=7
A Java program is basically a set of classes. A class is defined by a set of declaration statements
and methods or functions. Most statements contain expressions, which express the actions
carried out on information or data. Smallest individual thing in a program are known as tokens.
The compiler recognizes them for building up expression and statements.
1. Literals
2. Identifiers
3. Operators
4. Separators
Literals in Java are a sequence of characters (digits, letters and other characters) that characterize
constant values to be stored in variables. Java language specifies five major types of literals are as
follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
Identifiers are programmer-created tokens. They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and method.
8
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to
operate data and variables. They frequently form a part of mathematical or logical expressions.
9
LECTURE 3: DATA TYPES, ELEMENTS OF JAVA
Data types:
A data type is a scheme for representing values. An example is int which is the Integer, a data
type.
Values are not just numbers, but any manner of data that a computer can process.
The data type defines the kind of data that is represented by a variable.
As with the keyword class, Java data types are case sensitive.
10
2. Floating point data type:
It is also called as Real number and when we require accuracy then we can use it.
There are two types of floating point data type.
float
double
It is represent single and double precision numbers. The float type is used for single precision and
it uses 4 bytes for storage space. It is very useful when we require accuracy with small degree of
precision. But in double type, it is used for double precision and uses 8 bytes of storage space. It
is useful for large degree of precision.
11
Enter marks m1, m2,m3:
66
77
88
Roll number is=7
Average is=77.0
Java allows mixing of constants and variables of different types in an expression, but during
assessment it hold to very strict rules of type conversion.
When computer consider operand and operator and if operands are different types then type is
automatically convert in higher type.
2.3 Variables:
Variables are labels that express a particular position in memory and connect it with a data type.
The first way to declare a variable: This specifies its data type, and reserves memory for it. It
assigns zero to primitive types and null to objects.
dataType variableName;
The second way to declare a variable: This specifies its data type, reserves memory for it, and
puts an initial value into that memory. The initial
value must be of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves memory for each.
dataType variableNameOne, variableNameTwo;
The second way to declare two variables: both of the same data type, reserves memory, and puts
an initial value in each variable.
dataType variableNameI = initialValueI, variableNameII=initialValueII;
Variable name:
Use only the characters ‘a‘ through ‘z‘, ‘A‘ through ‘Z‘, ‘0‘ through ‘9‘, character ‘_‘, and
character ‘$‘.
12
Constant:
Constant means fixed value which is not change at the time of execution of program. In Java,
there are two types of constant as follows:
Numeric Constants
Integer constant
Real constant
Character Constants
Character constant
String constant
1. Integer Constant:
An Integer constant refers to a series of digits. There are three types of integer as follows:
a) Decimal integer
Embedded spaces, commas and characters are not allowed in between digits.
For example:
23 411
7,00,000
17.33
b) Octal integer
It allows us any sequence of numbers or digits from 0 to 7 with leading 0 and it is called as Octal
integer.
For example:
011
00
0425
c) Hexadecimal integer
It allows the sequence which is preceded by 0X or 0x and it also allows alphabets from ‘A‘ to ‘F‘
or ‘a‘ to ‘f‘ (‘A‘ to ‘F‘ stands for the numbers ‘10‘ to ‘15‘) it is called as Hexadecimal integer.
For example:
0x7
00X
0A2B
2. Real Constant
It allows us fractional data and it is also called as floating point constant.
It is used for percentage, height and so on.
For example:
0.0234
0.777
-1.23
3. Character Constant
It allows us single character within pair of single quote.
For example:
‘A‘
‘7‘
‘\‘
13
4. String Constant
It allows us the series of characters within pair of double quote.
For example:
“WELCOME”
“END OF PROGRAM“
“BYE …BYE”
“A”
Symbolic constant:
In Java program, there are many things which is requires repeatedly and if we want to make
changes then we have to make these changes in whole program where this variable is used. For
this purpose, Java provides ‘final‘ keyword to declare the value of variable as follows:
Syntax:
final type Symbolic_name=value;
For example:
If I want to declare the value of ‘PI‘ then:
final float PI=3.1459;
the condition is, Symbolic_name will be in capital letter( it shows the difference between normal
variable and symblic name) and do not declare in method.
Comments:
A comment is a note written to a human reader of a program. The program compiles and runs
exactly the same with or without comments. Comments start with the two characters “//” (slash
slash). Those characters and everything that follows them on the same line are ignored by the java
compiler.
Everything between the two characters “/*”and the two characters “*/” are unobserved by the
compiler. There can be many lines of comments between the “/*” and the “*/”.
14
LECTURE 4: OPERATORS & EXPRESSIONS, CONTROL STRUCTURES
Operator:
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs to
operate data and variables. They frequently form a part of mathematical or logical expressions.
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
1. Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra. Java provides the fundamental arithmetic operators. These can operate on built in data
type of Java.
Following table shows the details of operators.
15
“-” operator in Java:
class SubstractionInt
{
public static void main (String args[])
{
int a = 6;
int b = 3;
System.out.println("a = " + a);
System.out.println("b =" + b);
int c = a - b;
System.out.println("Subtraction= " + c);
}
}
Output:
a=6
b=3
Subtraction=3
16
Division=3
When both operands in the expression are integers then the expression is called Integer
expression and the operation is called Integer arithmetic.
When both operands in the expression are real then the expression is called Real expression and
the operation is called Real arithmetic.
When one operand in the expression is integer and other is float then the expression is called
Mixed Mode Arithmetic expression and the operation is called Mixed Mode Arithmetic
operation.
As we learn the Arithmetic operation on integer data and store data in integer variable. But the
following program shows the use of operators with integer data and store data in float variable.
17
2. Logical operators: When we want to form compound conditions by combining two or
more relations, then we can use logical operators.
Following table shows the details of operators.
3. Relational Operators:
When evaluation of two numbers is performed depending upon their relation, assured decisions
are made.
The value of relational expression is either true or false.
18
If A=7 and A < 10 is true while 10 < A is false.
Following table shows the details of operators.
Output:
a>b = false
a<b = true
a<=b = true
4. Assignment Operators:
Assignment Operators is used to assign the value of an expression to a variable and is also called
as Shorthand operators.
Variable_name binary_operator = expression
5. Conditional Operators:
The character pair?: is a ternary operator of Java, which is used to construct conditional
expressions of the following form:
Expression1 ? Expression3 : Expression3
The increment operator ++ adds 1 to a variable. Usually the variable is an integer type, but it can
be a floating point type. The two plus signs must not be split by any character.
19
7. Bit Wise Operators:
Control Structure
Selection statement is also called as Decision making statements because it provides the decision
making capabilities to the statements.
In selection statement, there are two types:
if statement
switch statement
20
In Java, switch statement check the value of given variable or statement against a list of case values and
when the match is found a statement-block of that case is executed. Switch statement is also called as
multiway decision statement.
21
22
Iteration Statement:
The process of repeatedly executing a statements and is called as looping. The statements may be
executed multiple times (from zero to infinite number). If a loop executing continuous then it is
called as Infinite loop. Looping is also called as iterations.
In Iteration statement, there are three types of operation:
for loop
while loop
do-while loop
The for loop is entry controlled loop. It means that it provide a more conscious loop control structure.
The while loop is entry controlled loop statement. The condition is evaluated, if the condition is true then
the block of statements or statement block is executed otherwise the block of statement is not executed.
In do-while loop, first attempt of loop should be execute then it check the condition.
The benefit of do-while loop/statement is that we get entry in loop and then condition will check for very
first time. In while loop, condition will check first and if condition will not satisfied then the loop will not
execute.
23
Jumps in statement:
Statements or loops perform a set of operations continually until the control variable will not satisfy the
condition. but if we want to break the loop when condition will satisfy then Java give a permission to
jump from one statement to end of loop or beginning of loop as well as jump out of a loop.
“break” keyword use for exiting from loop and “continue” keyword use for continuing the loop.
Labelled loop:
In Iteration Statement, we covered for loop, while loop and do-while loop with example.
24
LECTURE 5: CLASS, OBJECTS & METHODS, CONSTRUCTORS
Class Definition: A class is a collection of objects of similar type. Once a class is defined, any
number of objects can be produced which belong to that class.
Objects are instances of the Class. Classes and Objects are very much related to each other.
Without objects you can't use a class.
25
Method Overloading: Method overloading means method name will be same but each method
should be different parameter list.
26
Constructors:
Constructors always have the same name to that of the class. They do not return any kind of
type not even void data type because they return the class instances itself.
class Room
{
int length;
int width;
Room(int a, int b) // area of rectangle
{
length=a;
width=b;
}
Room(int len) // area of square
{
length=width=len;
27