Module-I Java - Notes
Module-I Java - Notes
UNIT I
Object Oriented Programming: Benefits of Object-Oriented Programming.
Introduction to Java: Java buzzwords, byte code. Java Programming Fundamentals, data types,
variables, arrays, operators,expressions, control statements, concepts of classes, objects, constructors,
methods, access control, overloading methods and constructors, introducing access control, static,
final, exploring string class.
Principles of OOPS: Data Abstraction, Data Encapsulation, Polymorphism, and Inheritance
OOP CONCEPTS
· Class: In object-oriented programming, a class is a programming language construct that is
used as a blueprint to create objects. This blueprint includes attributes and methods that the
created objects all share. Usually, a class represents a person, place, or thing - it is an
abstraction of a concept within a computer program. Fundamentally, it encapsulates the state
and behavior of that which it conceptually represents. It encapsulates state through data
placeholders called member variables; it encapsulates behavior through reusable code called
methods.
· Object: An Object is a real time entity. An object is an instance of a class. Instance means
physically happening. An object will have some properties and it can perform some actions.
Object contains variables and methods. The objects which exhibit similar properties and
actions are grouped under one class. ―To give a real world analogy, a house is constructed
according to a specification. Here, the specification is a blueprint that represents a class, and
the constructed house represents the object‖.
o To access the properties and methods of a class, we must declare a variable of that class
type. This variable does not define an object. Instead, it is simply a variable that can refer to
an object.
o We must acquire an actual, physical copy of the object and assign it to that variable. We
can do this using new operator. The new operator dynamically allocates memory for an object
and returns a reference to it. This reference is, more or less, the address in memory of the
object allocated by new. This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated.
· Encapsulation: Wrapping up of data (variables) and methods into single unit is called
Encapsulation. Class is an example for encapsulation. Encapsulation can be described as a
protective barrier that prevents the code and data being randomly accessed by other code
defined outside the class. Encapsulation is the technique of making the fields in a class private
and providing access to the fields via methods. If a field is declared private, it cannot be
accessed by anyone outside the class.
· Abstraction: Providing the essential features without its inner details is called abstraction
(or) hiding internal implementation is called Abstraction. We can enhance the internal
implementation without effecting outside world. Abstraction provides security. A class
contains lot of data and the user does not need the entire data. The advantage of abstraction is
JAVA PROGRAMMING UNIT-I 2022-23
that every user will get his own view of the data according to his requirements and will not
get confused with unnecessary data. A bank clerk should see the customer details like account
number, name and balance amount in the account. He should not be entitled to see the
sensitive data like the staff salaries, profit or loss of the bank etc. So such data can be
abstracted from the clerks view.
· Inheritance: Acquiring the properties from one class to another class is called inheritance
(or) producing new class from already existing class is called inheritance. Reusability of code
is main advantage of inheritance. In Java inheritance is achieved by using extends keyword.
The properties with access specifier private cannot be inherited.
· Polymorphism: The word polymorphism came from two Greek words ‗poly‘ means ‗many‘
and ‗morphos‘ means ‗forms‘. Thus, polymorphism represents the ability to assume several
different forms. The ability to define more than one function with the same name is called
Polymorphism
e.g.: int add (int a, int b)
float add (float a, int b)
float add (int a , float b)
void add (float a)
int add (int a)
❖ Increased Reliability
Code that is executed frequently will tend to have fewer bugs then code that executed
infrequently. When same components are used in two or more applications, the code will be
exercised more than code that is developed for a single application. Thus bugs in such code
tend to be more quickly discovered and latter applications gain the benefit of using
components are more error free. Similarly the costs of maintenance of shared components can
be split among many projects.
❖ Code Sharing
Code sharing can occur on several levels with OO techniques. Two or more objects will share
the code that they inherit.
❖ Consistency of Interface
When two or more classes inherit from the same super class, the behavior inherit will be same
in all cases. Thus it easier to guarantee that interfaces to similar objects are in fact similar, the
user is not presented with a confusing collection of objects that are almost the same but
behave, and are interacted with, very differently.
JAVA PROGRAMMING UNIT-I 2022-23
❖ Software Components
Inheritance provide programmers with the ability to construct reusable software components.
The goal is to permit the development of new and novel applications that nevertheless require
little or no actual coding.
❖ Rapid Prototyping
When a s/w system is constructed largely out of reusable components, development time can
be concentrated on understanding new and unusual portion of the system. Thus, s/w systems
can be generated more quickly and easily, leading to a style of programming known as rapid
prototyping or exploratory programming.
❖ Polymorphism
Polymorphism in programming languages permits the programmer to generate high-level
reusable components that can be tailored to fit different applications by changes in their low-
level parts.
❖ Information hiding
A programmer who reuses a s/w components needs only to understand the nature of the
component and its interface. It is not necessary for the programmer to have detailed
information concerning matters such as the techniques used to implement the component.
1. OOP‘s allows to decompose a problem into a number of entities called objects and then
builds the data and functions around these objects.
Object A
Data
func
Data
funct Data
funct
Object B Object C
2. Programs are designed around the data being operated rather than the operations
themselves.
3. Data in OOP‘s is hidden, and can be accessed by member functions only.
4. In OOP‘s local variables can be declared at the points where they are actually used. This is
called dynamic declaration.
5. Data and associated operations are unified into a single entity called a class which can be
treated as if it were a normal built in data type, though, it is user defined.
JAVA PROGRAMMING UNIT-I 2022-23
Global Data
Advantages of OOPs:
1. We can eliminate redundant code and extend the use of classes with the concept of
inheritance.
2. We can build the programs from the standard working modules that communicate with
one another, rather than having to start writing the code from beginning. This leads to
saving of development time and higher productivity.
3. The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
4. It is possible to have multiple instance of an object to exist without any interference.
5. Software complexity can be managed.
6. OO systems can be easily upgraded from small to large systems.
Applications of OOPs:
1. Real time systems
2. Simulation and modeling
3. OO database
4. Hypertext, hypermedia and expert-text
5. AI and expert systems
6. Neural networks and parallel programming
7. Decision support and office automation systems
JAVA PROGRAMMING UNIT-I 2022-23
JAVA PROGRAMMING
HISTORY OF JAVA
• In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for
consumer electronic devices that could be controlled by a remote. This project was called
Stealth Project but later its name was changed to Green Project.
• In January 1991, Project Manager James Gosling and his team members Patrick
Naughton, Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project.
• Gosling thought C and C++ would be used to develop the project. But the problem he
faced with them is that they were system dependent languages. The trouble with C and
C++ (and most other languages) is that they are designed to be compiled for a specific
target and could not be used on various processors, which the electronic devices might
use.
• James Gosling with his team started developing a new language, which was completely
system independent. This language was initially called OAK. Since this name was
registered by some other company, later it was changed to Java.
• James Gosling and his team members were consuming a lot of coffee while developing
this language. Good quality of coffee was supplied from a place called ―Java Island‘.
Hence they fixed the name of the language as Java. The symbol for Java language is cup
and saucer.
• Sun formally announced Java at Sun World conference in 1995. On January 23rd 1996,
JDK1.0 version was released.
• Java Virtual Machine (JVM) is the heart of entire Java program execution process.
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler at the time of compilation. Remember, this java
compiler is outside the JVM. This .class file is given to the JVM. Following figure
shows the architecture of Java Virtual Machine.
JAVA PROGRAMMING UNIT-I 2022-23
• In JVM, there is a module (or program) called class loader sub system, which
performs the following instructions:
• · First of all, it loads the .class file into memory.
• · Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
•
• If the byte instructions are proper, then it allocates necessary memory to execute the
program. This memory is divided into 5 parts, called run time data areas, which
contain the data and results while running the program. These areas are as follows:
•
• o Method area: Method area is the memory block, which stores the class code, code
of the variables and code of the methods in the Java program. (Method means
functions written in a class).
•
• o Heap: This is the area where objects are created. Whenever JVM loads a class,
method and heap areas are immediately created in it.
•
• o Java Stacks: Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on
Java Stacks. So, Java Stacks are memory area where Java methods are executed.
While executing methods, a separate frame will be created in the Java Stack, where
the method is executed. JVM uses a separate thread (or process) to execute each
method.
• o PC (Program Counter) registers: These are the registers (memory areas), which
contain memory address of the instructions of the methods. If there are 3 methods, 3
PC registers will be used to track the instruction of the methods.
•
• o Native Method Stacks: Java methods are executed on Java Stacks. Similarly, native
methods (for example C/C++ functions) are executed on Native method stacks. To
JAVA PROGRAMMING UNIT-I 2022-23
execute the native methods, generally native method libraries (for example C/C++
header files) are required. These header files are located and connected to JVM by a
program, called Native method interface.
JAVA BUZZWORDS
■ Simple
■ Secure
■ Portable
■ Object-oriented
■ Robust
■ Multithreaded
■ Architecture-neutral
■ Interpreted
■ High performance
■ Distributed
■ Dynamic
Simple
Java is a small and simple language. Java does not use pointers, pre-processor header files,
goto statement and many other. It also eliminates operator overloading and multiple
inheritance. Java inherits the C/C++ syntax and many of the object oriented features of C++.
Secure
Security becomes an important issue for a language that is used for programming on Internet.
Every time when you download a ―normal program‖, here is a risk of viral infection. When
we use a java compatible web browser, we can safely download Java applets without fear of
viral infection. Java achieves this protection by confining a Java program to the Java
execution environment and not allowing it access to other parts of the computer.
Portable
Java programs can be easily moved from one computer system to another, anywhere and
anytime. This is the reason why Java has become a popular language for programming on
Internet.
Object-Oriented
Java is a true object oriented language. Almost everything in java is an object. All program
code and data reside within objects and classes Java comes with an extensive set of classes,
arranged in packages, that we can use in our programs by inheritance. The object model in
java is simple and easy to extend.
JAVA PROGRAMMING UNIT-I 2022-23
Robust
Java is a robust language. It provides many safeguards to ensure reliable code. To gaon
reliability, Java restricts in few key areas
i. to force you to find mistakes early in program development.
ii. java frees you from having to worry about many of the most common causes of
programming errors.
Java is a strictly typed language. It checks your code at compile time.
Two main reasons for program failure are:
1. Memory management mistakes and
2. Mishandled exceptional conditions (i.e runtime errors)
Memory management can be a difficult, tedious task in traditional programming
environments. For example, in C/C++, the programmer must manually allocates and free all
dynamic memory. This sometime leads to problems, because programmers will either forget
to free memory that has been previously allocated or try to free some memory that another
part of there is still using. Java virtually eliminates these problems by managing allocation
and de allocation. De allocation is completely automatic, because java provides garbage
collection for unused objects.
Exceptional conditions often arise in situations such as division by zero or file not found etc..
Java helps in this area by providing object oriented exception handling.
Multithreaded
Multithreaded means handling multiple tasks simultaneously. This means that we need not
wait for the application to finish one task before beginning another. To accomplish this, java
supports multithreaded programming which allows to write programs that do many things
simultaneously.
Architecture-Neutral
A central issue for the Java designers was that of code longevity and portability. One of the
main problems facing programmers is that no guarantee exists that if you write a program
today, it will run tomorrow—even on the same machine. Operating system upgrades,
processor upgrades, and changes in core system resources can all combine to make a program
malfunction. Java Virtual Machine solves this problem. The goal is ―write once; run
anywhere, any time, forever.‖
Java performance is impressive for an interpreted language, mainlt deu to the use of byte
code. This code can be interpreted on any system that provides a JVM. Java was designed to
perform well on very low power CPUs.
Distributed
Java is designed for the distributed environment of the Internet, because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a
file. The original version of Java (Oak) included features for intraaddress- space messaging.
This allowed objects on two different computers to execute procedures remotely. Java revived
JAVA PROGRAMMING UNIT-I 2022-23
these interfaces in a package called Remote Method Invocation (RMI). This feature brings an
unparalleled level of abstraction to client/ server programming.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner.
COMMENTS
/* this comment runs to the terminating symbol, even across line breaks */
DATATYPES
Java defines eight simple (or elemental) types of data: byte, short, int, long, char,
float,double, and boolean. These can be put in four groups:
■ Integers This group includes byte, short, int, and long, which are for whole valued signed
numbers.
■ Floating-point numbers This group includes float and double, which represent numbers
with fractional precision.
■ Characters This group includes char, which represents symbols in a character set, like
letters and numbers.
■ Boolean This group includes boolean, which is a special type for representing true/false
values.
Float Data Types: These data types handle floating point numbers
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127
values in the Unicode character set. For this reason, all the ―old tricks‖ that you have used
with characters in the past will work in Java, too. Even though chars are not integers, in many
cases you can operate on them as if they were integers. This allows you to add two characters
together, or to increment the value of a character variable. For example, consider the
following program:
Boolean Data Type: can handle truth values either true or false
e.g.:- boolean response = true;
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have
a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is the
name of the variable.
Eg : int n;
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
JAVA PROGRAMMING UNIT-I 2022-23
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
✓ 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.
JAVA PROGRAMMING UNIT-I 2022-23
✓ Therefore, variables declared within a method will not hold their values between calls
to that method.
✓ 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.
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
When these two conditions are met, a widening conversion takes place.
For example, the int type is always large enough to hold all valid byte values, so no explicit
cast statement is required.
JAVA PROGRAMMING UNIT-I 2022-23
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
Here, target-type specifies the desired type to convert the specified value to.
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("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
OPERATORS
Arithmetic operators: These operators are used to perform fundamental operations like
addition, subtraction, multiplication etc.
JAVA PROGRAMMING UNIT-I 2022-23
Assignment operator: This operator (=) is used to store some value into a variable.
Unary operators: As the name indicates unary operator‘s act only on one operand.
Bitwise operators: These operators act on individual bits (0 and 1) of the operands. They
act only on integer data types, i.e. byte, short, long and int.
This operator is called ternary because it acts on 3 variables. The syntax for this operator is:
Variable = Expression1? Expression2: Expression3;
First Expression1 is evaluated. If it is true, then Expression2 value is stored into variable
otherwise Expression3 value is stored into the variable.
OPERATOR HIERARCHY
ENUMERATED TYPES
Enumeration:
• An enumeration is created using the enum keyword. For example, here is a
simple
enum Apple
{
class EnumDemo
{
public static void main(String args[])
{
Apple ap;
ap = Apple.RedDel;
// Output an enum value.
System.out.println("Value of ap: " + ap);
System.out.println();
ap = Apple.GoldenDel;
// Compare two enum values.
if(ap == Apple.GoldenDel)
System.out.println("ap contains GoldenDel.\n");
// Use an enum to control a switch statement.
switch(ap)
{
case Jonathan:
System.out.println("Jonathan is red.");
break;
case GoldenDel:
System.out.println("Golden Delicious is yellow.");
break;
case RedDel:
System.out.println("Red Delicious is red.");
break;
case Winesap:
System.out.println("Winesap is red.");
break;
case Cortland:
System.out.println("Cortland is red.");
break;
}
}
}
JAVA PROGRAMMING UNIT-I 2022-23
CONTROL STATEMENTS
STATEMENTS
Java supports two selection 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
The if statement is Java‘s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block). The condition is any expression that returns a boolean value.
int a, b;
// ...
if(a < b) a = 0;
else b = 0;
Nested ifs
JAVA PROGRAMMING UNIT-I 2022-23
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within the same block as the else and
that is not already associated with an else. Here is an example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
switch
The switch statement is Java‘s multiway 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.
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
JAVA PROGRAMMING UNIT-I 2022-23
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements
for
while
do-while
These statements are used to repeat same set of instructions specified number of times called
loops. A loop repeatedly executes the same set of instructions until a termination condition is
met.
o while Loop: while loop repeats a group of statements as long as condition is true. Once the
condition is false, the loop is terminated. In while loop, the condition is tested first; if it is
true, then only the statements are executed. while loop is called as entry control loop.
do…while Loop: do…while loop repeats a group of statements as long as condition is true.
In do...while loop, the statements are executed first and then the condition is tested. do…while
loop is also called as exit control loop.
Syntax: do
{
statements;
} while (condition);
for Loop: The for loop is also same as do…while or while loop, but it is more compact
syntactically. The for loop executes a group of statements as long as a condition is true.
System.out.print (i + ―\t‖);
}
}
JUMP STATEMENTS
Java supports three jump statements: break, continue and return. These statements transfer
control to another part of the program.
o break:
• break can be used inside a loop to come out of it.
• break can be used inside the switch block to come out of the switch block.
• break can be used in nested blocks to go to the end of a block. Nested blocks represent
a block written within another block.
•
Syntax: break; (or) break label; //here label represents the name of the block.
continue: This statement is useful to continue the next repetition of a loop/ iteration. When
continue is executed, subsequent statements inside the loop are not executed.
Syntax: continue;
{ System.out.print (i + ―\t‖);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
return statement:
• return statement is useful to terminate a method and come back to the calling method.
• return statement in main method terminates the application.
• return statement can be used to return some value from a method to a calling method.
•
Syntax: return;
(or)
return value; // value may be of any type
• In C/C++, program starts executing from main method similarly in Java, program
starts executing from main method. The return type of main method is void because
program starts executing from main method and it returns nothing.
• Since Java is purely an Object Oriented Programming language, without creating an
object to a class it is not possible to access methods and members of a class. But main
method is also a method inside a class, since program execution starts from main
method we need to call main method without creating an object.
• Static methods are the methods, which can be called and executed without creating
objects.
• Since we want to call main () method without using an object, we should declare main
()
Sample Program:
class Sample
{
public static void main(String args[])
{
System.out.print ("Hello world");
}
}
• JVM calls main () method using its Classname.main () at the time of running the
program. JVM is a program written by Java Soft people (Java development team) and
main () is the method written by us. Since, main () method should be available to the
JVM, it should be declared as public. If we don‘t declare main () method as public,
then it doesn‘t make itself available to JVM and JVM cannot execute it.
• JVM always looks for main () method with String type array as parameter otherwise
JVM cannot recognize the main () method, so we must provide String type array as
parameter to main () method.
• A class code starts with a {and ends with a}. A class or an object contains variables
and methods (functions). We can create any number of variables and methods inside
the class.
• This is our first program, so we had written only one method called main ().
• Our aim of writing this program is just to display a string ―Hello world‖.
• In Java, print () method is used to display something on the monitor. A method should
be called by using objectname.methodname (). So, to call print () method, create an
object to PrintStream class then call objectname.print () method.
• An alternative is given to create an object to PrintStream Class i.e. System.out. Here,
System is the class name and out is a static variable in System class. out is called a
field in System class. When we call this field a PrintStream class object will be created
internally. So, we can call print() method as: System.out.print (―Hello world‖); println
() is also a method belonging to PrintStream class. It throws the cursor to the next line
after displaying the result.
• In the above Sample program System and String are the classes present in java.lang
package.
JAVA PROGRAMMING UNIT-I 2022-23
ARRAYS
An array is a group of like-typed variables that are referred to by a common name. Arrays of
any type can be created and may have one or more dimensions. A specific element in an array
is accessed by its index. Arrays offer a convenient means of grouping
related information.
One-Dimensional Arrays
type var-name[ ];
Here, type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array. That is, to use new to
allocate an array, you must specify the type and number of elements to allocate. The elements
in the array allocated by new will automatically be initialized to zero.
class Array {
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}
Multidimensional Arrays
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable. For
example, the following two declarations are equivalent:
This alternative declaration form is included as a convenience, and is also useful when
specifying an array as a return type for a method.
JAVA PROGRAMMING UNIT-I 2022-23
A stream represents flow of data from one place to other place. Streams are of two types in
java. Input streams which are used to accept or receive data. Output streams are used to
display or write data. Streams are represented as classes in java.io package.
· System.in: This represents InputStream object, which by default represents standard input
device that is keyboard.
· System.out: This represents PrintStream object, which by default represents standard output
device that is monitor.
· System.err: This field also represents PrintStream object, which by default represents
monitor. System.out is used to display normal messages and results whereas System.err is
used to display error messages.
The above two steps can be combined and rewritten in a single statement as:
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
· Now, we can read the data coming from the keyboard using read () and readLine () methods
available in BufferedReader class.
· The read method reads a single character from the keyboard but it returns its ASCII
number,which is an integer. Since, this integer number cannot be stored into character type
variable ch, we should convert it into char type by writing (char) before the method. int data
type is converted into char data type, converting one data type into another data type is called
type casting.
· readLine () method accepts a string from keyboard and returns the string into str. In this
case, casting is not needed since readLine () is taking a string and returning the same data
type.
· First, we should accept the integer number from the keyboard as a string, using readLine ()
as: String str = br.readLine ();
· Now, the number is in str, i.e. in form of a string. This should be converted into an int by
using parseInt () method, method of Integer class as:
int n = Integer.parseInt (str);
If needed, the above two statements can be combined and written as:
int n = Integer.parseInt (br.readLine() );
· parseInt () is a static method in Integer class, so it can be called using class name as
Integer.parseInt ().
· We are not using casting to convert String type into int type. The reason is String is a class
and int is a fundamental data type. Converting a class type into a fundamental data type is not
possible by using casting. It is possible by using the method Integer.parseInt().
· We can accept a float value from the keyboard with the help of the following statement:
float n = Float.parseFloat (br.readLine() );
· We are accepting a float value in the form of a string using br.readLine () and then passing
the string to Float.parseFloat () to convert it into float. parseFloat () is a static method in Float
class.
· We can accept a double value from the keyboard with the help of the following statement:
double n = Double.parseDouble (br.readLine() );
JAVA PROGRAMMING UNIT-I 2022-23
· We are accepting a double value in the form of a string using br.readLine () and then passing
the string to Double.parseDouble () to convert it into double. parseDouble () is a static method
in Double class.
throws IOException at the side of the method where read ()/ readLine () is used.
There are various ways to read input from the keyboard, the java.util.Scanner class is one of
them.The Java Scanner class breaks the input into tokens using a delimiter that is whitespace
bydefault. It provides many methods to read and parse various primitive values.
JAVA PROGRAMMING UNIT-I 2022-23
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the
value as a string.
import java.util.Scanner;
class ScannerTest{
int rollno=sc.nextInt();
String name=sc.next();
double fee=sc.nextDouble();
sc.close(); } }
JAVA PROGRAMMING UNIT-I 2022-23
INTRODUCING CLASSES
✓ A class is that it defines a new data type.
✓ Once defined, this new type can be used to create objects of that type.
✓ Thus, a class is a template for an object, and an object is an instance of a class
A class is declared by use of the class keyword. The general form of a class definition is
shown here:
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
Eg:
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
JAVA PROGRAMMING UNIT-I 2022-23
}
}
Declaring Objects
First, declare a variable of the class type. This variable does not define an object. Instead, it is
simply a variable that can refer to an object.
Second, acquire an actual, physical copy of the object and assign it to that variable. You can
do this using the new operator. The new operator dynamically allocates (that is, allocates at
run time) memory for an object and returns a reference to it. This reference is, more or less,
the address in memory of the object allocated by new. This reference is then stored in the
variable. Thus, in Java, all class objects must be dynamically allocated.
Introducing Methods
1. Modifiers—such as public, private, and others you will learn about later.
2. The return type—the data type of the value returned by the method, or void if the
method does not return a value.
3. The method name—the rules for field names apply to method names as well, but the
convention is a little different.
JAVA PROGRAMMING UNIT-I 2022-23
CONSTRUCTORS
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
JAVA PROGRAMMING UNIT-I 2022-23
Parameterized Constructors
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
ACCESS CONTROL
Encapsulation links data with the code that manipulates it. However, encapsulation provides
another important attribute: access control.
Through encapsulation, you can control what parts of a program can access the members of a
class. By controlling access, you can prevent misuse.
• default
• public
• private
• protected
✓ When a member of a class is modified by the public specifier, then that member can
be accessed by any other code.
✓ When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
✓ When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package. In the classes
developed so far, all members of a class have used the default access mode, which is
essentially public.
Here is an example:
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +
ob.b + " " + ob.getc());
}
}
✓ Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword.
✓ this can be used inside any method to refer to the current object.
✓ That is, this is always a reference to the object on which the method was invoked.
JAVA PROGRAMMING UNIT-I 2022-23
✓ You can use this anywhere a reference to an object of the current class‘ type is
permitted.
✓ As you know, it is illegal in Java to declare two local variables with the same name
inside the same or enclosing scopes.
✓ We can have local variables, including formal parameters to methods, which overlap
with the names of the class‘ instance variables.
✓ However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
✓ This is why width, height, and depth were not used as the names of the parameters to
the Box( ) constructor inside the Box class. If they had been, then width would have
referred to the formal parameter, hiding the instance variable width. While it is
usually easier to simply use different names, there is another way around this situation.
✓ Because this lets you refer directly to the object, you can use it to resolve any name
space collisions that might occur between instance variables and local variables.
GARBAGE COLLECTION
✓ Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
✓ In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
✓ Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
✓ It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed. There is
no explicit need to destroy objects as in C++. Garbage collection only occurs
sporadically (if at all) during the execution of your program.
✓ Sometimes an object will need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or
JAVA PROGRAMMING UNIT-I 2022-23
window character font, then you might want to make sure these resources are freed
before an object is destroyed.
✓ To handle such situations, Java provides a mechanism called finalization.
✓ By using finalization, we can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
✓ To add a finalizer to a class, you simply define the finalize( ) method. The Java run
time calls that method whenever it is about to recycle an object of that class.
✓ Inside the finalize( ) method you will specify those actions that must be performed
before an object is destroyed.
✓ The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
✓ Right before an asset is freed, the Java run time calls the finalize( ) method on the
object.
METHOD OVERLOADING
✓ 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 implements polymorphism.
✓ When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
✓ Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
✓ When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
JAVA PROGRAMMING UNIT-I 2022-23
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
CONSTRUCTOR OVERLOADING
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists. The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
JAVA PROGRAMMING UNIT-I 2022-23
OUTPUT:
111 Karan 0
222 Aryan 25
There are many differences between constructors and methods. They are given below.
Constructor must not have return type. Method must have return type.
Constructor name must be same as the class Method name may or may not be
name. same as class name.
PARAMETER PASSING
In general, there are two ways that a computer language can pass an argument to a subroutine.
1. Call-by-value
2. Call-by-reference
✓ The first way is call-by-value. This method copies the value of an argument into the
formal parameter of the subroutine. Therefore, changes made to the parameter of the
subroutine have no effect on the argument.
✓ The second way an argument can be passed is call-by-reference. In this method, a
reference to an argument (not the value of the argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in
JAVA PROGRAMMING UNIT-I 2022-23
the call. This means that changes made to the parameter will affect the argument used
to call the subroutine.
As you will see, Java uses both approaches, depending upon what is passed. In Java, when
you pass a simple type to a method, it is passed by value. Thus, what occurs to the parameter
that receives the argument has no effect outside the method.
RECURSION
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
✓ When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.
✓ A recursive call does not make a new copy of the method. Only the arguments are
new.
JAVA PROGRAMMING UNIT-I 2022-23
✓ As each recursive call returns, the old local variables and parameters are removed
from the stack, and execution resumes at the point of the call inside the method.
✓ Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls.
Disadvantage:
Many recursive calls to a method could cause a stack overrun. Because storage for parameters
and local variables is on the stack and each new call creates a new copy of these variables, it
is possible that the stack could be exhausted. If this occurs, the Java run-time system will
cause an exception.
Advantage:
The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives.
In Java a string is a sequence of characters. But, unlike many other languages that implement
strings as character arrays, Java implements strings as objects of type String.
The String class supports several constructors. To create an empty String, you call the
default constructor. For example,
String s = new String();
will create an instance of String with no characters in it.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the
length( ) method, shown here:
int length( )
The following fragment prints ―3‖, since there are three characters in the string s:
String Concatenation
In general, Java does not allow operators to be applied to String objects. The one exception to
this rule is the + operator, which concatenates two strings, producing a String object as the
result. This allows you to chain together a series of + operations.
JAVA PROGRAMMING UNIT-I 2022-23
Character Extraction
The String class provides a number of ways in which characters can be extracted from a
String object. Each is examined here. Although the characters that comprise a string within a
String object cannot be indexed as if they were a character array, many of the String methods
employ an index (or offset) into the string for their operation. Like arrays, the string indexes
begin at zero.
charAt( )
To extract a single character from a String, you can refer directly to an individual
character via the charAt( ) method. It has this general form:
Here, where is the index of the character that you want to obtain.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( )
method. It has this general form:
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This
method is called getBytes( ), and it uses the default character-to-byte conversions provided by
the platform. Here is its simplest form:
byte[ ] getBytes( )
toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest
way is to call toCharArray( ). It returns an array of characters for the entire string. It has this
general form:
char[ ] toCharArray( )
String Comparison
JAVA PROGRAMMING UNIT-I 2022-23
The String class includes several methods that compare strings or substrings within
strings. Each is examined here.
To compare two strings for equality, use equals( ). It has this general form:
String defines two routines that are, more or less, specialized forms of regionMatches( ). The
startsWith( ) method determines whether a given String begins with a specified string.
Conversely, endsWith( ) determines whether the String in question ends with a specified
string. They have the following general forms:
equals( ) Versus ==
It is important to understand that the equals( ) method and the == operator perform two
different operations. As just explained, the equals( ) method compares the characters inside a
String object. The == operator compares two object references to see whether they refer to
the same instance. The following program shows how two different String objects can
contain the same characters, but references to these objects will not compare as equal:
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
}
}
The variable s1 refers to the String instance created by ―Hello‖. The object referred to by s2
is created with s1 as an initializer. Thus, the contents of the two String objects are identical,
but they are distinct objects. This means that s1 and s2 do not refer to the same objects and
are, therefore, not ==, as is shown here by the output of the preceding example:
compareTo( )
JAVA PROGRAMMING UNIT-I 2022-23
Often, it is not enough to simply know whether two strings are identical. For sorting
applications, you need to know which is less than, equal to, or greater than the next. A string
is less than another if it comes before the other in dictionary order. A string is greater than
another if it comes after the other in dictionary order. The String method compareTo( )
serves this purpose. It has this general form:
Here, str is the String being compared with the invoking String. The result of the
comparison is returned and is interpreted as shown here:
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
Searching Strings
The String class provides two methods that allow you to search a string for a specified
character or substring:
■ indexOf( ) Searches for the first occurrence of a character or substring.
■ lastIndexOf( ) Searches for the last occurrence of a character or substring.
substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
concat( )
replace( )
The replace( ) method replaces all occurrences of one character in the invoking string
with another character. It has the following general form:
trim( )
The trim( ) method returns a copy of the invoking string from which any leading and
JAVA PROGRAMMING UNIT-I 2022-23
The method toLowerCase( ) converts all the characters in a string from uppercase to
lowercase. The toUpperCase( ) method converts all the characters in a string from lowercase
to uppercase. Nonalphabetical characters, such as digits, are unaffected.
Here are the general forms of these methods:
String toLowerCase( )
String toUpperCase( )
STRINGBUFFER
StringBuffer is a peer class of String that provides much of the functionality of strings. As
you know, String represents fixed-length, immutable character sequences. In contrast,
StringBuffer represents growable and writeable character sequences. StringBuffer may have
characters and substrings inserted in the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and often has more characters
preallocated than are actually needed, to allow room for growth. Java uses both classes
heavily, but many programmers deal only with String and let Java manipulate StringBuffers
behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
The current length of a StringBuffer can be found via the length( ) method, while the total
allocated capacity can be found through the capacity( ) method. They have the following
general forms:
int length( )
int capacity( )
ensureCapacity( )
If you want to preallocate room for a certain number of characters after a StringBuffer has
been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if
you know in advance that you will be appending a large number of small strings to a
StringBuffer. ensureCapacity( ) has this general form:
setLength( )
To set the length of the buffer within a StringBuffer object, use setLength( ). Its general
form is shown here:
void setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative. When you
increase the size of the buffer, null characters are added to the end of the existing buffer. If
you call setLength( ) with a value less than the current value returned by length( ), then the
characters stored beyond the new length will be lost.
The value of a single character can be obtained from a StringBuffer via the charAt( )
method. You can set the value of a character within a StringBuffer using setCharAt( ).
Their general forms are shown here:
getChars( )
To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has
this general form:
append( )
The append( ) method concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object. It has overloaded versions for all the built-in types
and for Object. Here are a few of its forms:
insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the
simple types, plus Strings and Objects. Like append( ), it calls String.valueOf( ) to obtain
the string representation of the value it is called with. This string is then inserted into the
invoking StringBuffer object. These are a few of its forms:
reverse( )
You can reverse the characters within a StringBuffer object using reverse( ), shown here:
StringBuffer reverse( )
Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and
deleteCharAt( ). These methods are shown here:
replace( )
substring( )
Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It
has the following two forms:
o The static variable can be used to refer to the common property of all objects (which
is not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Final Keyword:
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
JAVA PROGRAMMING UNIT-I 2022-23
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
}
3) Java final class
final class Bike{}