Java Notes Module 1
Java Notes Module 1
Java Notes Module 1
and JAVA
Introduction:
Object-oriented programming was developed because limitations were discovered in
earlier approaches to programming Object oriented programming is an approach to
program organization and development that attempts to eliminate some of the pitfalls of
conventional programming methods by incorporating the best structured programming
features with several powerful new concepts. It is a new way of organizing and developing
programs.
1. Classes:
Class is a user-defined data type and is a way to bind the data and its associated functions
together. Classes behave like the built-in types of a programming language. The syntax used
to create an object is no different than the syntax used to create an integer object in C. If
It specifies what data and what functions will be included in objects of that class. Defining
the class doesn’t create any objects, just as the mere existence of data type int doesn’t
create any variables.
2. Objects:
Objects are the basic run-time entities in an object-oriented system. They may represent a
person, or a student, a place, a bank account, a table of data or any item that the program
has to handle. They may also represent user-defined data such as vectors, time and lists.
Thinking in terms of objects, rather than functions using which easily programs can be
designed Programming problem is analyzed in terms of objects and the nature of
communication between them. Program object should be chosen such that they match
closely with the real-world objects.
Object is a variable of the type class or instance of the 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. Each object is associated with the data of type class with which they are created.
The fundamental idea behind object-oriented languages is to combine into a single unit
both data and the functions that operate on that data. Such a unit is called an object. An
object’s functions, called member functions or methods in Java typically provide the only
way to access its data. If you want to read a data item in an object, you call a member
function in the object. It will access the data and return the value to you. You can’t access
the data directly. The data is hidden, so it is safe from accidental alteration.
The wrapping up of data and functions into a single unit (called class) is known as
encapsulation.
The data is not accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface between
the objects data and the program.
This insulation of the data from direct access by the program is called data hiding of
information hiding.
Abstraction refers to the act of representing essential features 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, weight and cost, and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created.
The attributes sometimes called data members because they hold information. The
functions that operate on these data are sometimes called methods or member
functions. Since the classes use the concept of data abstraction, they are known as
Abstract Data Types(ADT).
4. Inheritance:
Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
It supports the concept of hierarchical classification. For example, the bird ‘robin’ is
a part of the class ‘flying bird’ which is again a part of the class ‘bird’.
In OOP, the concept of inheritance provides the ideas of reusability. A programmer
can take an existing class and, without modifying it, add additional features and
capabilities to it. This is done by deriving a new class from the existing one. The new
class will inherit the capabilities of the old one, but is free to add new features of its
own. In Java the original class is called the super class; other classes can be defined
that share its characteristics, but add their own as well. These are called sub classes.
The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a
sum. If the operands are strings, then the operation would produce a third string by
Polymorphism in Java
Method Overloading
Method Overriding
Method overloading is defined as a process that can create multiple methods of the same
name in the same class, and all the methods work in different ways. Method overloading
occurs when there is more than one method of the same name in the class. In this process,
the call to the method is resolved at compile-time hence known as Static Polymorphism
or Compile-Time polymorphism
Method Overriding:
Method overriding is defined as a process when the subclass or a child class has the same
method as declared in the parent class. In this case calling of method is resolved at run time
hence known as Dynamic Binding or Run-time Polymorphism.
6. Dynamic Binding:
Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming
Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding (also known as late binding) means that the
code associated with a given procedure call is not known until the time of the call at
run-time. It is associated with polymorphism and inheritance.
The technology of data hiding facilitates the programmer to design and develop safe
programs that do not disturb code in other parts of the program.
Save development time (and cost) by reusing code – once an object class is created it
can be used in other applications. All object oriented programming languages allows
creating extended and reusable parts of programs. Object oriented programming
changes the way of thinking of a programmer. This results in rapid development of
new software in a short time.
Using inheritance, we can eliminate redundant program code and continue the use
of previously defined classes.
Divided Into Program is divided into small Program is divided into parts called
parts called functions objects.
Importance Importance is not given to data Importance is given to the data rather
but to functions as well as than procedures or functions because
sequence of actions to be done. it works as a real world.
Access POP does not have any access OOP has access specifiers named
Specifiers specifier. Public, Private, Protected, etc.
Data In POP, Data can move freely In OOP, objects can move and
Moving from function to function in the communicate with each other
system. through member functions.
Data Access Most function uses Global data Data cannot move easily from
for sharing that can be accessed function to function, it can be kept
freely from function to function in public or private so we can control
the system. the access of data.
Expansion To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
Introduction to Java
The history of java starts from Green Team. Java team members (also known as Green
Team), initiated a revolutionary task to develop a language for digital devices such as set-
top boxes, televisions etc Later, Java technology as incorporated by Netscape. Currently,
Java is used in internet programming, mobile devices, games, e-business solutions etc.
The major points that describe the history of java are as follows:
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like settop
boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Java is an island in Indonesia where the first coffee was produced (called Java coffee).
It is a kind of espresso bean. Java name was chosen by James Gosling while having a
cup of coffee nearby his office.
6) In 1995, Time magazine called Java one of the Ten Best Products of 1995. JDK 1.0 was
released on January 23, 1996.
7) Java Version History There are many java versions that has been released. Current
stable release of Java is Java SE 17.
1. Simple : Java is very easy to learn, and its syntax is simple, clean and easy to understand. Java
programming language is very simple and easy to learn, understand, and code. Most of the syntaxes
in java follow basic programming language C and object-oriented programming concepts are
similar to C++. In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed.
3. Portable: n C/C++, the source code may run slightly differently on different hardware platforms,
but Java simplifies it. You can run Java bytecode on any hardware that has a compliant JVM which
can convert the bytecode according to that particular machine.
5. Secured :Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Java supports access modifiers to check memory access
and also ensures that no viruses enter an applet.
6. Robust: Java is robust as it is capable of handling run-time errors, supports automatic garbage
collection and exception handling,
7. Dynamic and extensible: With the help of OOPs, we can add classes and add new methods to
classes, creating new classes through subclasses. This makes it easier for us to expand our own
classes and even modify them.
Java gives the facility of dynamically linking new class libraries, methods, and objects.
9. High Performance: The performance of Java is impressive for an interpreted language because
of its intermediate bytecode.
Java provides high performance with the use of “JIT – Just In Time compiler”, in which the compiler
compiles the code on-demand basis, that is, it compiles only that method which is being called. This
saves time and makes it more efficient.
10. Multithreaded: 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. The inclusion of multithreading
enhances the overall execution speed of Java programs.
11.Distributed: A Java programmer sitting on a machine can access another program running on
the other machine using internet. This feature in Java is very helpful when we develop large
projects
With the help of JDK the user compiles and runs his java program. The following steps are used in
executing a Java Program.
Step 1:
When we compile Java program using javac tool, the Java compiler converts the source code
into an intermediate code called byte codeand a .class file is created.(in this example Simple.class is
created). This intermediate byte code is platform independent (you can take this bytecode from a
machine running windows and use it in any other machine running Linux or MacOS etc) andalso
only understandable by the JVM and not the user or even the hardware /OS layer.
Step 2:
Now the JVM comes into play, which is made to read and execute this bytecode. The JVM is
linked with operating system and runs the bytecode to execute the code depending upon operating
system. Therefore, a user can take this class file(Bytecode file) formed to any operating system
which is having a JVM installed and can run his program easily without even touching the syntax of
a program and without actually having the source code. The .class file which consists of bytecode is
not user-understandable and can be interpreted by JVM only to build it into the machine code.
Save this program as Prg1.java. A java program source code is a text file containing one or more
class definitions is called as compilation unit and the extension of this file name should be .java.
To compile above program, use the following statement in the command prompt –
javac Prg1.java
Now, the javac compiler creates a file Prg1.class containing bytecode version of the program,
which can be understandable by JVM. To run the program, we have to use Java application
launcher called java. That is, use the command –
java Prg1
The output of the program will now be displayed as –
Hello World!!!
Let us have closer look at the terminologies used in the above program now –
out is a static final (means not inheritable) field (ie, variable)in System class which is of
type PrintStream (a built-in class, contains methods to print the different data
values). Static fields and methods must be accessed by using the class name, so
we need to use System.out.
println is a public method in PrintStream class to print the data values. After printing the
data, the cursor will be pushed to the next line
Data types in Java are classified as Primitive and Non primitive data types. Examples of non-
primitive data type are classes, strings, arrays etc.
Integer data types -byte, short, int, long : belonging to Integers group involving whole-
valued signed numbers.
byte: Byte variables are declared by use of the byte keyword. For example,
byte b, c;
short :Here are some examples of short variable declarations: short s;short t;
int: The most commonly used integer type is int. ex: int x=10;
long: It 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.
Width
Name Range
(inbits)
long 64 -263 to+263–1
Width(inbi
Name Range
ts)
double 64 4.9e–324to1.8e+308
float 32 1.4e–045to3.4e+038
float: The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision,
but will become imprecise when the values are either very large or verysmall.
Ex: float x=11.345f;
We have to append f at the end of floating point literal. This is because any floating point
literal is considered as double by default and causes type casting error.
double : Double precision is actually faster than single precision on some modern
processors that have been optimized for high-speed mathematical calculations. All
transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
double d1 = 12.3 ;
All these are signed numbers and Java does not support unsigned numbers.
Operators in Java
The table above lists the precedence of operators in Java; higher it appears in the table, the higher
its precedence.Operator precedence is a rule that decides which operator will be executed first in
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators. The operands of the arithmetic operators
must be of a numeric type. You cannot use them on boolean types, but you can use them on char types,
since the char type in Java is a subset of int.
Basic arithmetic operators like +, -, * and / behave as expected for numeric data.
The – symbol can be used as unary operator to negate a variable.
If / is operated on two integer operands, then we will get only integral part of the result by
truncating the fractional part.
The % operator returns the remainder after division. It can be applied on integer and floating-
point types. in C/C++, the % operator cannot be used on float or double and should be used only
on integer variable.
For example, int x=57; double y= 32.8;
System.out.println(“on integer “ + x%10); //prints 7
System.out.println(“on double “ + y%10); //prints 2.8
Compound assignment operators like += will perform arithmetic operation with assignment.
That is, a+=2; a=a+2;
Increment/decrement operators (++ and -- ) will increase/decrease the operand by 1. That is,
a++; a=a+1; b--; b=b-1;
The ++ and -- operators can be used either as pre-increment/decrement or
postincrement/decrement operator. For example, x= 5; y=x++; //post increment Now, value of x
(that is 5) is assigned to y first, and x is then incremented to become 6.
x= 5;
y=++x; //pre-increment Now, x is incremented to 6 and then 6 is assigned to y.
class ShiftDemo
int a = 64,i,j
i = a << 2;
Original value of a: 64
Relational Operators The relational operators determine the relationship between two operands.
Specifically, they determine equality and ordering among operands. Following table lists the relational
operators supported by Java.
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.
classMain {
publicstaticvoidmain(String[] args) {
// && operator
System.out.println((5>3) && (8>5)); // true
System.out.println((5>3) && (8<5)); // false
// || operator
System.out.println((5<3) || (8>5)); // true
System.out.println((5>3) || (8<5)); // true
System.out.println((5<3) || (8<5)); // false
// ! operator
The ?: Operator(Ternary or Conditional operator): Java supports ternary operator which sometimes
can be used as an alternative for if-then-else statement. The general form is – var = expression1 ?
expression2 : expression3; Here, expression1 is evaluated first and it must return Boolean type. If it
results true, then value of expression2 is assigned to var, otherwise value of expression3 is assigned to
var. For example, int a, b, c ; ………. c= (a>b)?a:b; //c will be assigned with biggest among a and b
Assignment operators: Assignment operators are used to transfer the value of one operand (on RHS) to other(on
LHS). There are two kinds of assignment operations: simple assignment, in which the value of the second operand
is stored in the object specified by the first operand, and compound assignment, in which an arithmetic, shift, or
bitwise operation is performed prior to storing the result. All assignment operators in the following table except
the = operator are compound assignment operators.
Operator Meaning
= Store the value of the second operand in the object specified by the first operand (simple
assignment).
*= Multiply the value of the first operand by the value of the second operand; store the result in
the object specified by the first operand.
/= Divide the value of the first operand by the value of the second operand; store the result in
the object specified by the first operand.
%= Take modulus of the first operand specified by the value of the second operand; store the
result in the object specified by the first operand.
+= Add the value of the second operand to the value of the first operand; store the result in the
object specified by the first operand.
–= Subtract the value of the second operand from the value of the first operand; store the result
in the object specified by the first operand.
<<= Shift the value of the first operand left the number of bits specified by the value of the
>>= Shift the value of the first operand right the number of bits specified by the value of the
second operand; store the result in the object specified by the first operand.
&= Obtain the bitwise AND of the first and second operands; store the result in the object
specified by the first operand.
^= Obtain the bitwise exclusive OR of the first and second operands; store the result in the
object specified by the first operand.
|= Obtain the bitwise inclusive OR of the first and second operands; store the result in the object
specified by the first operand.
Java’s Conditional Statements Java supports two conditional statements: if and switch.
These statements allow you to control the flow of your program’s execution based upon conditions
known only during run time.
If statement:
If(condition) {
statements;
If the condition is true, then the statements written within true block will be executed. The condition
should result into Boolean type.
if (condition)
{ //true block }
else
{ //false block }
If the condition is true, then the statements written within true block will be executed, otherwise false
block will be executed.
For example
,int a, b, m;
------
if(a>b) max=a;
else
max=b;
if(condition 2)
{ statements;
} // statements will be executed only when both condition 1 and 2 tested true.
if(condition1)
block1;
block2;
…………..
…………..
else
Blockn;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the block associated with that if is executed, and the rest of the ladder is bypassed. The final else
acts as a default condition; that is, if all other conditional tests fail, then the last else statement is
performed.
switch Statement
The switch statement is Java’s multi-way branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often provides
a better alternative than a large series of if-else-if statements. Here is the general form of a switch
statement:
switch (expression)
break;
case value2: // statement sequence break; ………….... case valueN: // statement sequence break; default:
// default statement sequence } The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible with the expression. The switch
statement works like this: The value of the expression is compared with each of the literal values in the
case statements. If a match is found, the code sequence following that case statement is executed. If
none of the constants matches the value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and no default is present, then no
further action is taken. The break statement is used inside the switch to terminate a statement
sequence. When a break statement is encountered, execution branches to the first line of code that
follows the entire switch statement. This has the effect of “jumping out” of the switch. The break
statement is optional. If you omit the break, execution will continue on into the next case.
break;
break;
break;
default: statements;
example
int a=1;
switch(a)
case 0: System.out.println(”zero”);
break;
case 1: System.out.println(”one”);;
break;
case 2: System.out.println(”two”);
break
default: System.out.println(”invalid”);
switch statement, the value of the expression followed by switch is evaluated the value, which is
returned by expression is compared with the constant values followed by the case. The
statements under the case are executed if the match occurs.
The value of the expression should be short,byte, int or a char
Example: float x=8.9fExample:switch( Grade )
Excellent Good OK
//corrected
switch( Grade )
{
case 'A' : System.out.println("Excellent") ; break;
case 'B' : System.out.println("Good") ; break;
case 'C' System.out.println("OK") ;
}
Default statements are optional in switch statement and are executed if the cases are not met. If
the default statement is omitted, and no case match is found, none of the statements in the switch
body are executed. The default statement need not come at the end; it can appear anywhere in the
body of the switch statement. Irrespective its placement default statements will be executed at the end
if no match is found. Example see notes
;
switch(x)
{
Case 4.5System.out.printlnoption 1”; break;
Case 8.9: System.out.println<”option 2”; break;
} //illegal as x and case constants cannot be float.
case should be followed by constant values. It cannot have expression or variables or string
constants.
Example case a+b:
case “hello”: are invalid.(see notes for ex)
Each compound statement of a switch case should contain break statement to exit from
case.break prevents the program from executing the code in all the other case statements.
If a common set of statements to be executed under multiple cases, statements should be placed in
front of the last case statement.
char ch=’b’;
Switch(ch)
case 'a' :
case 'b' :
case 'c' :
case 'd' :
case 'e' :
case 'f' : count++;
} //legal
Switch(ch)
case 'a',case 'b',case 'c' ,case 'd' ,case 'e' ,case 'f' : count++;
}//illegal
Notice that switch can only be used to compare an expression against constants. Therefore we
cannot put variables as labels (for example case n: where n is a variable) or ranges (case (1..3):)
because they are not valid constants.
Looping Statements:
Basically, the types of looping statements depends on the condition checking mode. Condition checking
can be made in two ways as : Before loop and after loop. So, there are 2(two) types of looping
statements.
for loop:
for loop is used when the number of iterations are fixed and known to the programmer.
syntax: for(exp1;exp2;exp3)
statements;
Where
exp1: initialization expression which is used to initialize loop variable. There can be multiple
initializations. initialization_expression is executed only once before starting the loop.
Exp2: conditional/testing expression which results in either true or false. For each iteration of
the loop the condition is tested, statements inside the loop are executed if the tested condition
is true. This can have multiple testing expressions followed by logical AND /OR.
Example : int i;
for(i=0;i<10;i++)
b[j]=c[k];
All 3 expressions are optional , ie for loop can be written by omitting any or all 3 expressions.
Example
int k=0;
for(;k<5;k++)
System.out.println (“hello”);
for(; ;) //unconditional for loop must have break statement inside it else runs in infinite loop
loop variable used inside the for expression should not be float
Example: for(float i=1.0;i<10.0;i++) System.out.println (”float”); //illegal
In such type of loop, the test condition is checked first before the loop is executed. Hence it is
called as entry controlled loop or pre condition testing loop.
While loop:
While loop is used when exact numbers of iterations are not known. The syntax is as follows:
example:
while(condition ) while(n!=100)
{ {
} n++;
The condition in while loop is tested at the beginning of each iteration and statements inside the
while loop are executed as long as the condition tested is true. When the condition evaluates
false the loop is terminated and statement next to while loop is executed.
Do-while loop:
This loop is used when the statements inside the loop are to be executed at least once.
Syntax:
{
Statements;
} while(condition);
The statements inside the loop are executed at least once even if the condition is false.
In such type of loop, the loop is executed first. Then condition is checked after block of
statements are executed. Hence it is called as exit controlled loop or post condition testing loop.
Jump Statements
break statement:
break statement is used in switch to exit from case. break prevents the program from
executing the code in all the other case statements.
break is used inside the loop statements(for,while or do-while) to stop further iterations of the
loop and exit from the loop.
Syntax : loop statement
{
break;
}
Inside the loop break statement usually follows a condition to exit the loop.
It can be used to end an infinite loop, or to force it to end before its natural end.
Example see notes.
Continue statement:
This is used inside the loop to skip the current iteration and continue to next iteration.
When continue is executed, the statements after the continue will be skipped and control is
transferred to next iteration.
This is used to skip some intermediate iteration.
Syntax : loop statement
{
continue;
statements; //these statements will be skipped
}
https://nptel.ac.in/courses/106/105/106105191/