0% found this document useful (0 votes)
9 views58 pages

Module-I Java - Notes

Uploaded by

nainalashalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views58 pages

Module-I Java - Notes

Uploaded by

nainalashalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

JAVA PROGRAMMING UNIT-I 2022-23

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)

THE BENEFITS OF INHERITANCE


❖ Software Reusability
When behavior is inherited from another class, the code that provides that behavior does not
have to be rewritten. With objet oriented techniques, the functions can be written once and
reused.

❖ 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.

DIFFERENCES BETWEEN OBJECT ORIENTED & PROCEDURE ORIENTED


PROGRAMMING

Object Oriented Programming:

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

6. OOP supports polymorphism, encapsulation, and inheritance concepts.


7. For solving the problems, the problem is divided into a number of modules. These modules
are a logical collection of classes and objects.
8. OOP supports data abstraction.

Procedure Oriented Programming:

1. A procedure oriented program consists of instructions in groups, known as functions. High


level language like FORTRAN, PASCAL, and C are commonly known as procedure oriented
languages.

Global Data

2. POP employs top-down 1 ramming


Functionprog 2 w here a problem
approach
Function Functionis3 vi ewed as a sequence
of tasks to be per formed.
Data Data Data
3. POP has 2 ma jor drawbacks. (1) da ta move freely around the program and are therefore
vulnerable to changes caused by any function in the program, (2) it does not model
3. Data in procedure oriented language is open and can be accessed by any function.
4. Function overloading and operator overloading are not possible.
5. Local variables can be declared only at the beginning of the block.
6. Program controls are through jumps and calls to subroutines.
7.Polymorphism, encapsulation and inheritance are not possible.
For solving the problems, the problem is divided into a number of modules. Each module is a
subprogram.
8. Data abstraction property is not supported by procedure oriented language.

Difference between Procedure Oriented Programming and OOP:


JAVA PROGRAMMING UNIT-I 2022-23

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.

THE JAVA VIRTUAL MACHINE

• 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.‖

Interpreted and High Performance

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

• Comments in a program are called inline documentation


• They should be included to explain the purpose of the program and describe
processing steps
• They do not affect how a program works

Java comments can take three forms:

// this comment runs to the end of the line

/* this comment runs to the terminating symbol, even across line breaks */

/** this is a javadoc comment */

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.

Integer Data Types: These data types store integer numbers


JAVA PROGRAMMING UNIT-I 2022-23

// Compute distance light travels using long variables.


class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.

Float Data Types: These data types handle floating point numbers

// Compute the area of a circle.


class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Character Data Type: This data type represents a single character. char data type in java
uses two bytes of memory also called Unicode system. Unicode is a specification to include
alphabets of all international languages into the character set of java.
JAVA PROGRAMMING UNIT-I 2022-23

Here is a program that demonstrates char variables:


// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:
ch1 and ch2: X Y

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:

// char variables behave like integers.


class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
The output generated by this program is shown here:
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1
containing Y, the next character in the ASCII (and Unicode) sequence.

Boolean Data Type: can handle truth values either true or false
e.g.:- boolean response = true;

Here is a program that demonstrates the boolean type:

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
JAVA PROGRAMMING UNIT-I 2022-23

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:

type identifier [ = value][, identifier [= value] ...] ;

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;

Eg: int n=10, m=20;

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);
}
}

THE SCOPE AND LIFETIME OF VARIABLES

✓ Java allows variables to be declared within any block.


✓ A block is begun with an opening curly brace and ended by a closing curly brace. A
block defines a scope. Thus, each time you start a new block, you are creating a new
scope.
✓ A scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
✓ Most other computer languages define two general categories of scopes: global and
local.
✓ In Java, the two major scopes are those defined by a class and those defined by a
method.
✓ The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method‘s scope.
✓ As a general rule, variables declared inside a scope are not visible (that is, accessible)
to code that is defined outside that scope. Thus, when you declare a variable within a
scope, you are localizing that variable and protecting it from unauthorized access
and/or modification.
✓ Indeed, the scope rules provide the foundation for encapsulation.
✓ Scopes can be nested. The outer scope encloses the inner scope This means that
objects declared in the outer scope will be visible to code within the inner scope.
However, the reverse is not true. Objects declared within the inner scope will not be
visible outside it.

// Demonstrate block scope.


class Scope {
public static void main(String args[]) {
int x;
x = 10;
if(x == 10) {
int y = 20;
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

✓ 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.

// Demonstrate lifetime of a variable.


class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

TYPE CONVERSION AND CASTING

✓ Type casting is to assign a value of one type to a variable of another type.


✓ If the two types are compatible, then Java will perform the conversion automatically.
For example, it is always possible to assign an int value to a long variable.
✓ For instance, there is no conversion defined from double to byte. To do so, you must
use a cast, which performs an explicit conversion between incompatible types.

Java’s Automatic Conversions

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:

■ The two types are compatible.


■ The destination type is larger than the source type.

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

Casting Incompatible Types

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);
}
}

Conversion of int to byte.


i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

OPERATORS

An operator is a symbol that performs an operation. An operator acts on variables called


operands.

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.

Relational operators: These operators are used for comparison purpose.

Logical operators: Logical operators are used to construct compound conditions. A


compound condition is a combination of several simple conditions.
JAVA PROGRAMMING UNIT-I 2022-23

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.

Ternary Operator or Conditional Operator (? :):

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.

e.g.: max = (a>b) ? a: b;

Program 1: Write a program to perform arithmetic operations

//Addition of two numbers


class AddTwoNumbers
{ public static void mian(String args[])
{ int i=10, j=20;
System.out.println("Addition of two numbers is : " + (i+j));
System.out.println("Subtraction of two numbers is : " + (i-j));
System.out.println("Multiplication of two numbers is : " + (i*j));
System.out.println("Quotient after division is : " + (i/j) );
JAVA PROGRAMMING UNIT-I 2022-23

System.out.println("Remainder after division is : " +(i%j) );


}
}

Program 2: Write a program to perform Bitwise operations


//Bitwise Operations
class Bits
{ public static void main(String args[])
{ byte x,y;
x=10;
y=11;
System.out.println ("~x="+(~x));
System.out.println ("x & y="+(x&y));
System.out.println ("x | y="+(x|y));
System.out.println ("x ^ y="+(x^y));
System.out.println ("x<<2="+(x<<2));
System.out.println ("x>>2="+(x>>2));
System.out.println ("x>>>2="+(x>>>2));
}
}

OPERATOR HIERARCHY

➢ An expression is a sequence of operands and operators that reduce to a single


value.
➢ Expressions can be simple or complex.
JAVA PROGRAMMING UNIT-I 2022-23

➢ An operator is a syntactical token that requires an action be taken.


➢ An operand is an object on which an operation is performed; it receives an
operator‘s action .
➢ A simple expression contains only one operator.
Ex: 2+5
➢ A complex expression contains more than one operator.
Ex: 2+5*7
➢ An expression always reduces to a single value.
➢ We can divide simple expressions into six categories based on number of
operands, relative position of the operand and operator and the precedence of
operator.

ENUMERATED TYPES
Enumeration:
• An enumeration is created using the enum keyword. For example, here is a
simple

enumeration that lists various apple varieties:

• The identifiers Jonathan, GoldenDel, and so on, are called enumeration


constants. Each is their type is the type of the enumeration in which they are
declared, which is Apple in this case.

• Once defined an enumeration, you can create a variable of that type.


• However, even though enumerations define a class type, you do not instantiate an
enum using new.
• declare and use an enumeration variable in much the same way as you do one
of the primitive types.
• For example, this declares ap as a variable of enumeration type Apple:
Apple ap;
ap is of type Apple, the only values that it can be assigned (or can contain) are those
defined by the enumeration.
• For example, this assigns ap the value RedDel:
ap = Apple.RedDel;
RedDel is preceded by Apple.
JAVA PROGRAMMING UNIT-I 2022-23

// An enumeration of apple varieties.

enum Apple
{

Jonathan, GoldenDel, RedDel, Winesap, Cortland


}

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

The output from the program is shown here:


Value of ap: RedDel
ap contains GoldenDel.
Golden Delicious is yellow.

CONTROL STATEMENTS

Statements are divided into three groups:

STATEMENTS

SELECTION ITERATION/ JUMP


LOOP

Java’s Selection 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.

The else clause is optional.


The if works like this: If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed. In no case will both statements be executed. For example,
consider the following:

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)

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested ifs is the if-else-if
ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

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.

Here is the general form of a switch statement:

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

Java‘s iteration statements are

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.

Syntax: while (condition)


{
statements;
}
JAVA PROGRAMMING UNIT-I 2022-23

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
while (i <= 20)
{ System.out.print (i + ―\t‖);
i++;
}
}
}

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);

Program: Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
do
{ System.out.print (i + ―\t‖);
i++;
} while (i <= 20);
}
}

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.

Syntax: for (expression1; expression2; expression3)


{ statements;
}
Here, expression1 is used to initialize the variables, expression2 is used for condition
checking and expression3 is used for increment or decrement variable value.

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i;
for (i=1; i<=20; i++)
JAVA PROGRAMMING UNIT-I 2022-23

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.

Program : Write a program to use break as a civilized form of goto.

//using break as a civilized form of goto


class BreakDemo
{ public static void main (String args[])
{ boolean t = true;
first:
{
second:
{
third:
{
System.out.println (―Before the break‖);
if (t) break second; // break out of second block
System.out.println (―This won‘t execute‖);
}
System.out.println (―This won‘t execute‖);
}
System.out.println (―This is after second 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;

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural
{ public static void main (String args[])
{ int i=1;
while (true)
JAVA PROGRAMMING UNIT-I 2022-23

{ 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

Program : Write a program to demonstrate return statement.


//Demonstrate return
class ReturnDemo
{ public static void main(String args[])
{ boolean t = true;
System.out.println (―Before the return‖);
if (t)
return;
System.out.println (―This won‘t execute‖);
}}

SIMPLE JAVA STAND ALONE PROGRAM

• As all other programming languages, Java also has a structure.


• The first line of the C/C++ program contains include statement. For example,
<stdio.h> is the header file that contains functions, like printf (), scanf () etc. So if we
want to use any of these functions, we should include this header file in C/ C++
program.
• Similarly in Java first we need to import the required packages. By default java.lang.*
is imported. Java has several such packages in its library. A package is a kind of
directory that contains a group of related classes and interfaces. A class or interface
contains methods.
• Since Java is purely an Object Oriented Programming language, we cannot write a
Java program without having at least one class or object. So, it is mandatory to write a
class in Java program. We should use class keyword for this purpose and then write
class name.
JAVA PROGRAMMING UNIT-I 2022-23

• 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

The general form of a onedimensional array declaration is

type var-name[ ];

Here, type declares the base type of the array.

eg: int month_days[];


you must allocate one using new and assign it to month_days. new is a special operator
that allocates memory.

The general form of new as it applies to one-dimensional arrays appears as follows:

array-var = new type[size];

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.");
}
}

the following code creates an initialized array of integers:


JAVA PROGRAMMING UNIT-I 2022-23

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

In Java, multidimensional arrays are actually arrays of arrays.


To declare a multidimensional array variable, specify each additional index using another set
of square brackets.

int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD.

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
01234
56789
10 11 12 13 14
15 16 17 18 19

// Initialize a two-dimensional array.


class Matrix {
public static void main(String args[]) {
double m[][] = {
{ 0*0, 1*0, 2*0, 3*0 },
JAVA PROGRAMMING UNIT-I 2022-23

{ 0*1, 1*1, 2*1, 3*1 },


{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
When you run this program, you will get the following output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

Alternative Array Declaration Syntax

There is a second form that may be used to declare an array:

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:

int al[] = new int[3];


int[] a2 = new int[3];

The following declarations are also equivalent:

char twod1[][] = new char[3][4];


char[][] twod2 = new char[3][4];

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

CONSOLE INPUT AND OUTPUT

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.

To accept data from the keyboard:


· Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.

InputSteamReader obj = new InputStreamReader (System.in);

· Connect InputStreamReader to BufferReader, which is another input type of stream. We are


using BufferedReader as it has got methods to read data properly, coming from the stream.

BufferedReader br = new BufferedReader (obj);

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.

Accepting a Single Character from the Keyboard:

· Create a BufferedReader class object (br).


· Then read a single character from the keyboard using read() method as:
char ch = (char) br.read();
JAVA PROGRAMMING UNIT-I 2022-23

· 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.

Accepting a String from Keyboard:

· Create a BufferedReader class object (br).


· Then read a string from the keyboard using readLine() method as:
String str = br.readLine ();

· 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.

Accepting an Integer value from Keyboard:

· 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().

Accepting a Float value from Keyboard:

· 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.

Accepting a Double value from Keyboard:

· 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.

Accepting Other Types of Values:

· To accept a byte value: byte n = Byte.parseByte (br.readLine () );


· To accept a short value: short n = Short.parseShort (br.readLine () );
· To accept a long value: long n = Long.parseLong (br.readLine () );
· To accept a boolean value: boolean x = Boolean.parseBoolean (br.readLine () );
If read () / readLine () method could not accept values due to some reason (like insufficient
memory or illegal character), then it gives rise to a runtime error which is called by the name
IOException, where IO stands for Input/Output and Exception represents runtime error.But
we do not know how to handle this exception, in Java we can use throws command to throw
the exception without handling it by writing:

throws IOException at the side of the method where read ()/ readLine () is used.

Program 1: Write a program to accept and display student details.


// Accepting and displaying student details.
import java.io.*;
class StudentDemo
{ public static void main(String args[]) throws IOException
{ // Create BufferedReader object to accept data
BufferedReader br =new BufferedReader (new InputStreamReader (System.in));
//Accept student details
System.out.print ("Enter roll number: ");
int rno = Integer.parseInt (br.readLine());
System.out.print (―Enter Gender (M/F): ―);
char gender = (char)br.read();
br.skip (2);
System.out.print ("Enter Student name: ");
String name = br.readLine ()
System.out.println ("Roll No.: " + rno);
System.out.println ("Gender: " + gender);
System.out.println ("Name: " + name);
}
}

Java Scanner class

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.

There is a list of commonly used Scanner class methods:

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.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double nextDouble() it scans the next token as a double value.

import java.util.Scanner;

class ScannerTest{

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

System.out.println("Enter your rollno");

int rollno=sc.nextInt();

System.out.println("Enter your name");

String name=sc.next();

System.out.println("Enter your fee");

double fee=sc.nextDouble();

System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);

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

The General Form of a Class

A class is declared by use of the class keyword. The general form of a class definition is
shown here:

Access specifier class classname {


type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method

}
// ...
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

Obtaining objects of a class is a two-step process.

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.

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

The above two statements can be written as a single statement as

Box mybox = new Box();

Introducing Methods

This is the general form of a method:

modifier type name(parameter-list)


{
// body of method
}

More generally, method declarations have six components, in order:

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

4. The parameter list in parenthesis—a comma-delimited list of input parameters,


preceded by their data types, enclosed by parentheses, (). If there are no parameters,
you must use empty parentheses.
5. An exception list—to be discussed later.
6. The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.

CONSTRUCTORS

✓ A constructor initializes an object immediately upon creation.


✓ It has the same name as the class in which it resides and is syntactically similar to a
method.
✓ Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
✓ Constructors have no return type, not even void. This is because the implicit return
type of a class‘ constructor is the class type itself.

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

The constructors that take parameters are called parameterized constructors.

class Box {
double width;
double height;
double depth;

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}

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);
}
}

The output from this program is shown here:


Volume is 3000.0
Volume is 162.0

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.

Java‘s access specifiers are:


JAVA PROGRAMMING UNIT-I 2022-23

• 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());
}
}

The this Keyword

✓ 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.

Box(double w, double h, double d) {


this.width = w;
this.height = h;
this.depth = d;
}

Instance Variable Hiding:

✓ 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.

// Use this to resolve name-space collisions.


Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth; }

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.

The finalize( ) Method

✓ 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.

The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}

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.

Here is a simple example that illustrates method overloading:

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);
}
}

This program generates the following output:


No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625

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

public static void main(String args[]){


Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}

OUTPUT:
111 Karan 0
222 Aryan 25

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an Method is used to expose behaviour


object. of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default Method is not provided by compiler


constructor if you don't have any constructor. in any case.

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.

// Simple types are passed by value.


class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +
a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +
a + " " + b);
}
}

The output from this program is shown here:


a and b before call: 15 20
a and b after call: 15 20

// Objects are passed by reference.


class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
JAVA PROGRAMMING UNIT-I 2022-23

System.out.println("ob.a and ob.b after call: " +


ob.a + " " + ob.b);
}
}

This program generates the following output:


ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

RECURSION

✓ Java supports recursion.


✓ Recursion is the process of defining something in terms of itself. As it relates to Java
programming, recursion is the attribute that allows a method to call itself.
✓ A method that calls itself is said to be recursive.
✓ The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N. For
example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use
of a recursive method:

// A simple example of recursion.


class Factorial {
// this is a recursive function
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}

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));
}
}

The output from this program is shown here:


Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

✓ 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.

EXPLORING STRING CLASS

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 Constructors

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:

char chars[] = { 'a', 'b', 'c' };


String s = new String(chars);
System.out.println(s.length());

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

For example, the following fragment concatenates three strings:

String age = "9";


String s = "He is " + age + " years old.";
System.out.println(s);

This displays the string ―He is 9 years old.‖

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:

char charAt(int where)

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:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

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.

equals( ) and equalsIgnoreCase( )

To compare two strings for equality, use equals( ). It has this general form:

boolean equals(Object str)

startsWith( ) and endsWith( )

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:

boolean startsWith(String str)


boolean endsWith(String str)

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:

Hello equals Hello -> true


Hello == Hello -> false

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:

int compareTo(String str)

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( )

You can concatenate two strings using concat( ), shown here:


String concat(String str)

replace( )

The replace( ) method replaces all occurrences of one character in the invoking string
with another character. It has the following general form:

String replace(char original, char replacement)


Here, original specifies the character to be replaced by the character specified by
replacement. The resulting string is returned. For example,
String s = "Hello".replace('l', 'w');
puts the string ―Hewwo‖ into s.

trim( )

The trim( ) method returns a copy of the invoking string from which any leading and
JAVA PROGRAMMING UNIT-I 2022-23

trailing whitespace has been removed. It has this general form:


String trim( )
Here is an example:
String s = " Hello World ".trim();

Changing the Case of Characters Within a String

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)

length( ) and capacity( )

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:

void ensureCapacity(int capacity)


JAVA PROGRAMMING UNIT-I 2022-23

Here, capacity specifies the size of the buffer.

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.

charAt( ) and setCharAt( )

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:

char charAt(int where)


void setCharAt(int where, char ch)

getChars( )

To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has
this general form:

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

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:

StringBuffer append(String str)


StringBuffer append(int num)
StringBuffer append(Object obj)

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:

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
JAVA PROGRAMMING UNIT-I 2022-23

reverse( )

You can reverse the characters within a StringBuffer object using reverse( ), shown here:

StringBuffer reverse( )

delete( ) and deleteCharAt( )

Java 2 added to StringBuffer the ability to delete characters using the methods delete( ) and
deleteCharAt( ). These methods are shown here:

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

replace( )

Another method added to StringBuffer by Java 2 is replace( ). It replaces one set of


characters with another set inside a StringBuffer object. Its signature is shown here:

StringBuffer replace(int startIndex, int endIndex, String str)

substring( )

Java 2 also added the substring( ) method, which returns a portion of a StringBuffer. It
has the following two forms:

String substring(int startIndex)


String substring(int startIndex, int endIndex)

Java static keyword:


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to
the class than an instance of the class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
JAVA PROGRAMMING UNIT-I 2022-23

1) Java static variable

If you declare any variable as static, it is known as a static variable.

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.

Example of static variable


//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
JAVA PROGRAMMING UNIT-I 2022-23

void display (){System.out.println(rollno+" "+name+" "+college);}


}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}

2) Java static method

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.

Example of static method

/Java Program to demonstrate the use of a static method.


class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
JAVA PROGRAMMING UNIT-I 2022-23

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

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}

2) Java final method


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
JAVA PROGRAMMING UNIT-I 2022-23

}
3) Java final class
final class Bike{}

class Honda1 extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

You might also like