0% found this document useful (0 votes)
4 views

Java Notes Upto Control Statements

Uploaded by

gyamini2020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Notes Upto Control Statements

Uploaded by

gyamini2020
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 1

Object-Oriented Thinking

When computers were first invented, programming was done manually by toggling in a binary machine
instructions by use of front panel. As programs began to grow, high level languages were introduced that gives
the programmer more tools to handle complexity. The first widespread high level language is FORTRAN. Which
gave birth to structured programming in 1960’s. The Main problem with the high level language was they have
no specific structure and programs becomes larger, the problem of complexity also increases. So C became the
popular structured oriented language to solve all the above problems.

However in SOP(Standard Operating Procedure), when project reaches certain size its complexity
exceeds. So in 1980’s a new way of programming was invented and it was Object Oriented Programming. Object
Oriented Programming is a programming methodology that helps to organize complex programs through the use
of inheritance, encapsulation & polymorphism. Object Oriented Programming is a Revolutionary idea totally
unlike anything that has came before in programming.

To illustrate the major ideas in object-oriented programming, let us consider how we might go about handling a

A Way of Viewing World


real-world situation and then ask how we could make the computer more closely model the techniques employed.
Suppose I wish to send flowers to a friend who lives in a city many miles away. Let me call my friend Sally. So
I chooce a agent called Flora to carry flowers to my friend.I tell Flora the variety and quantity of flowers I wish
to send and give Sally's address, and I can be assured the flowers will be delivered expediently and automatically

Figure 1.1: The community of agents helping me

1.1 Agents and Communities


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 2

Let me emphasize that the mechanism I used to solve my problem was to find an appropriate agent
(namely, Flora) and to pass to her a message containing my request. It is the responsibility of Flora to satisfy my
request. There is some method or some algorithm or set of operations used by Flora to do this. I do not need to
know the particular method that Flora will use to satisfy my request; indeed, often I do not want to know the
details. This information is usually hidden from my inspection.

If I investigated however, I might discover that Flora delivers a slightly diferent message to another againt in my
friend's city. That agent , in turn, perhaps has a subordinate who makes the flowers arrangement. The agent then
passes the flowers , along with yet another message, to a delivery person, and so on. Earlier, the agent in Sally's
city had obtained her flower from a flower wholesaler who, in turn, had interactions with the flower growers,
each of whom had to manage a team of gardeners.

So, our first observation of object-oriented problem solving is that the solution to my problem required
the help of many other individuals (Figure 1.1). Without their help, my problem could not be easily solved. We
phrase this in a general fashion as the following:

An object oriented program is structured as a community of interacting agents, called objects. Each object has a
role to play. Each object provides a service, or performs an action, that is used by other members of the
community.

1.2 Messages and Methods

The chain reaction that ultimately resulted in the solution to my program began with my request to Flora. This
request lead to other requests, which lead to still more requests, until my flowers ultimately reached my friend.
We see, therefore, that members of this community interact with each other by making requests. So, our next
principle of object- oriented problem solving is the vehicle by which activities are initiated:

Action is initiated in object-oriented programming by the transmission of a message to an agent (an object)
responsible for the action. The message encodes the request for an action and is accompanied by any additional
information (arguments) needed to carry out the request. The receiver is the object to whom the message is sent.
If the receiver accepts the message, it accepts the responsibility to carry out the indicated action. In response to
a message, the receiver will perform some method to satisfy the request.

We have noted the important principle of information hiding in regard to message passing that is, the
client sending the request need not know the actual means by which the request will be honored. There is

another principle, all too human, that we see is implicit in message passing. If there is a task to perform, the first
thought of the client is to find somebody else he or she can ask to do the work. This second reaction often
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 3

becomes thin in many programmers with extensive experience in conventional techniques. Frequently, a dificult
hurdle to overcome is the idea in the programmer's mind that he or she must write everything and not use the
services of others.

An important part of object-oriented programming is the development of reusable components, and an


important first step in the use of reusable components is a willingness to trust software written by others.

Information hiding is also an important aspect of programming in conventional languages. In what sense
is a message difierent from, say, a procedure call? In both cases, there is a set of well-defined steps that will be
initiated following the request. But, there are two important distinctions. The first is that in a message there is a
designated receiver for that message; the receiver is some object to which the message is sent. In a procedure
call, there is no designated receiver.The second is that the interpretation of the message is dependent on the
receiver and can vary with difierent receivers.

. Usually, the specific receiver for any given message will not be known until run time, so the
determination of which method to invoke cannot be made until then. Thus, we say there is late binding between
the message (function or procedure name) and the code fragment (method) used to respond to the message. This
situation is in contrast to the very early (compile-time or link-time) binding of name to code fragment in
conventional procedure calls.

1.3 Responsibilities

A fundamental concept in object-oriented programming is to describe behavior in terms of responsibilities. My


request for action indicates only the desired outcome (flowers for my friend). Flora is free to pursue any
technique that achieves the desired objective and is not hampered by interference on my part.

By discussing a problem in terms of responsibilities we increase the level of abstraction. This permits
greater independence between objects, a critical factor in solving complex problems. The entire collection of
responsibilities associated with an object is often described by the term protocol.

A traditional program often operates by acting on data structures, for example changing fields in an
array or record. In contrast, an object oriented program requests data structures (that is, objects) to perform a
service. This difference between viewing software in traditional, structured terms and viewing it from an
object-oriented perspective can be summarized by a twist on a well-known quote

“Ask not what you can do to your data structures, but rather ask what your data structures can do for you”.

1.4 Classes and Instances


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 4

Although I have only dealt with Flora a few times, I have a rough idea of the behavior I can expect when
I go into her shop and present her with my request. I am able to make certain assumptions because I have
information about forists in general, and I expect that Flora, being an instance of this category, will fit the general
pattern. We can use the term Florist to represent the category (or class) of all forists. Let us incorporate these
notions into our next principle of object-oriented programming:

All objects are instances of a class.The method invoked by an object in response to a message is
determined by the class of the receiver. All objects of a given class use the same method in response to
similar messages.

Figure 1.2: The category surrounding Flora

1.5 Class Hierarches - Inheritance

I have more information about Flora not necessarily because she is a florist but because she is a shopkeeper. I
know, for example, that I probably will be asked for money as part of the transaction, and that in return for
payment I will be given a receipt. These actions are true of grocers, stationers, and other shopkeepers. Since the
category Florist is a more specialized form of the category Shopkeeper, any knowledge I have of Shopkeepers
is also true of Florists and hence of Flora.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 5

One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy of categories
(see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper. Furthermore, a Shopkeeper
is also a Human; so I know, for example, that Flora is probably bipedal. A Human is a Mammal (therefore they
nurse their young and have hair), and a Mammal is an Animal (therefore it breathes oxygen), and an Animal is
a Material Object (therefore it has mass and weight). Thus, quite a lot of knowledge that I have that is applicable
to Flora is not directly associated with her, or even with her category Florist.

Figure 1.3: A class hirearchy for various meteral objects

The principle that knowledge of a more general category is also applicable to a more specific category is
called inheritance. We say that the class Florist will inherit attributes of the class (or category) Shopkeeper.

There is an alternative graphical technique often used to illustrate this relationship, particularly when there
are many individuals.. This technique shows classes listed in a hierarchical tree-like structure, with more abstract
classes (such as Material Object or Animal) listed near the top of the tree, and more specific classes, and finally
individuals, are listed near the bottom. Figure 1.3 shows this class hierarchy for Flora.

“Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit attributes
from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for which there are no
direct instances; it is used only to create subclasses.”

1.6 Method Binding, Overriding and Exceptions


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 6

we know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To
accommodate this, we need to find a technique to encode exceptions to a general rule.

We do this by declearing that information contained in a subclass can override information inherited from
a parent class. Most often, implementations of this approach takes the form of a method in a subclass having the
same name as a method in the parent class, combined with a rule for how the search for a method to match a
specific message is conducted:

The search for a method to invoke in response to a given message begins with the class of the receiver. If no appropriate
method is found, the search is conducted in the parent class of this class. The search continues up the parent class chain
until either a method is found or the parent class chain is exhausted. In the former case the method is executed; in the
latter case, an error message is issued. If methods with the same name can be found higher in the class hierarchy, the
method executed is said to override the inherited behavior.

Even if the compiler cannot determine which method will be invoked at run time, in many object-oriented
languages, such as Java, it can determine whether there will be an appropriate method and issue an error message
as a compile-time error diagnostic rather than as a run-time message.

If the task of delivering folwers is given to Elizabeth who follow different method in when compare to
florist Flora is an example of one form of polymorphism. As explained, that I do not, and need not, know exactly
what method Flora will use to honor my message is an example of information hiding.

1.7 Summary of Object - Oriented Concepts

The following are fundamental to OOP :

 Everything is an object.
 An object is a runtime entity in an object oriented programming
 Computation is performed by objects communicating with each other. Objects communicate by
sending and receiving messages. A message is a request for action bundled with whatever arguments
may be necessary to complete the task.
 Each object has its own memory, which consists of other objects.
 Every object is an instance of a class. A class simply represents a grouping of similar objects, such
as integers or lists.
 The class is the repository for behavior associated with an object. That is, all objects that are
instances of the same class can perform the same actions.
 Classes are organized into a singly rooted tree structure, called the inheritance hierarchy. Memory
and behavior associated with instances of a class are automatically available to any class associated
with a descendant in this tree structure.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 7

 Wrapping of data and methods into a single unit (called class)is known as “encapsulation”
 Encapsulation makes it possible to treat Object as a blackbox each performing a specific task
without any conceren for internal implementation.
 Insulation of the data from direct acess by the program is called as “data hiding”.
 Abstraction refers to the act of representing essential features without including background details
or exaplanations
 Inheritance is the process by which objects of one class acquire the properties of objects of another
class.Inheritance supports the concept of hierarchical classification as shown below.

Figure 1.4:Property inheritance

 Polymorphism means the ability to take more than one form.For example ,an operation may
exhibit different behaviour in different instance.

Figure 1.5:Polymorphism

1.8 Java Buzzwords or Features of Java


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 8

The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as java buzzwords.
A list of most important features of Java language is given below .

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

Figure 1.6: Features of Java


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 9

Simple:

Java language is simple because:


Syntax is based on C++ (so easier for programmers to learn it after C++).
Removed many confusing and/or rarely-used features
Ex.; explicit pointers, operator overloading etc.
No need to remove unreferenced objects ,to do this Automatic Garbage Collection in java.
Object-oriented :
Object-Oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour. Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing some principles. They are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independence :
Java provides software-based platform. The Java platform differs from most other platforms in the sense
that it's a software-based platform that runs on top of other hardware-based platforms. It has two
components:
Runtime Environment
API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,SunSolaris,Mac/OS etc. Java code is
compiled by the compiler and converted into bytecode.This bytecode is a platform independent code
because it can be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).

Figure 1.7: platform independency


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 10

Secured:
Java is secured because

There is no explicit pointers.

Programs run inside virtual machine sandbox.

Robust :

Robust simply means strong. Java uses strong memory management. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in java. All these points
makes java robust.

Architecture-neutral:

There are no implementation dependent features Ex.;size of primitive types is set

Portable :

We may carry the java bytecode to any platform.

High-performance:

Java is faster than traditional interpretation since byte code is "close" to native code still somewhat slower
than a compiled language (e.g., C++)

Distributed :

We can create distributed applications in java. RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the internet.

Multi-threaded:

A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it shares
the same memory. Threads are important for multi-media, Web applications etc
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 11

1.9 An Overview of Java


Java is a Programming Language and a Platform.

Platform : Any hardware or software environment in which a program runs, known as a platform. Since Java has
its own Runtime Environment (JRE) and API, it is called platform.

History of Java

Java team members (also known as Green Team), initiated a revolutionary task to develop a language for
digital devices such as set-top boxes, televisions etc. It was best suited for internet programming. Later, Java
technology as incorporated by Netscape.

Firstly, it was called "Greentalk" by James Gosling and file extension as .gt. After that, it was called Oak and
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies. Java is an
island of Indonesia where first coffee was produced (called java coffee).

Note: Java is just a name not an acronym.

Applications using Java: There are mainly 4 type of applications that can be created using java

 Standalone Application:
o It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in
java for creating standalone applications.
 Web Application:
o An application that runs on the server side and creates dynamic page, is called web application.
Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in
java.
 Enterprise Application:
o An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
 Mobile Application:
o An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 12

JDK, JRE and JVM

Java DevelopMent Kit(JDK)

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.

Figure 1.8: Java Development Kit (JDK)

Java Runtime Environment (JRE) :

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

Figure 1.9: Java Runtime Environment (JRE)

Java Virtual Machine (JVM)

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.JVMs are available for many hardware and software platforms. JVM, JRE
and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent

The JVM performs following main tasks:

 Loads code
 Verifies code
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 13

 Executes code
 Provides runtime environment

Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by Sun
and other companies.
2. An implementationIts implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.

JVM provides definitions for the:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
 Fatal error reporting etc.

Figure 1.10: Java Runtime Environment (JRE)

1. Classloader:Classloader is a subsystem of JVM that is used to load class files.


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 14

2. Class(Method) Area:Class(Method) Area stores per-class structures such as the runtime constant pool,
field and method data, the code for methods.
3. Heap:It is the runtime data area in which objects are allocated
4. Stack: Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.Each thread has a private JVM stack, created at the same time as thread. A
new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
5. Program Counter Register:PC (program counter) register. It contains the address of the Java virtual
machine instruction currently being executed.
6. Native Method Stack:It contains all the native methods used in the application
7. Execution Engine:It contains:

1) A virtual processor
2) Interpreter:Readbytecode stream then execute the instructions.
3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the amount
of time needed for compilation.Here the term compiler refers to a translator from the
instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Writing and Execution of simple Program

1.Open a simple text editor program such as Notepad and type the following content:

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}

2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java

3.Compile your first Java program

Now let’s compile our first program in the HelloWorld.java file using javac tool.
Syntax: javac programname.java
Type the following command to change the current directory to the one where the source file is stored:
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 15

4.Run your first Java program

It’s now ready to run our first Java program. To run java program use following Syntax

Syntax: java programname

That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or .class
extension). You would see the following output:

1.10 Data Types

Every variable has a type, every expression has a type and all types are strictly define more over every
assignment should be checked by the compiler by the type compatibility hence java language is considered as
strongly typed language. In java, There are two types of Data Types:

Primitive Data Types


Non-Primitive Data Types

1. Primitive Data Types

Data Types make a variable to store a single value at a time

Figure 1.11: DATA TYPES


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 16

The Eight Primitive data types in Java are:


The integral types:

 byte
 short
 int
 long

The floating-point types:

 float
 double

Values of class type are references. Strings are references to an instance of class String.

Type Size(bytes) Range Default


byte 1 -128 .. 127 0
short 2 -32768 to32767 0
Int 4 -2147483648 to 2147483647 0

-9223372036854775808 to
long 8 0
9223372036854775807

float 4 3.4 e38 to 1.4 e-45 0.0


double 8 1.e-308 to 4.9e-324 0.0
boolean JVM Specific true or false FALSE
char 2 0 ..65535 \u0000

2. Non-Primitive Data Types:Derived data types are those that are made by using any other data type and
can make a variable to store multiple values ,for example, arrays.
3. User Defined Data Types: User defined data types are those that user / programmer himself defines.
For example, classes, interfaces.

In java char uses 2 byte in java because java uses unicode system rather than ASCII code system. \u0000
is the lowest range of unicode system.

Unicode System:
Unicode is a universal international standard character encoding that is capable of representing most of the
world's written languages
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 17

1.11 Variables

Introduction of variables:

Variable is name of reserved area allocated in memory

A variable has these attributes:

 Name

1. The string of letters in a program used to designate a variable.


2. A name should start with a letter and consist of letters and/or digits.
3. Variables in names are case sensitive (capitalization matters).
4. The naming convention in Java is to start a variable name with a lower case letter.
5. New words within a name with a name start with a capital letter(example: numberOfCustomers).

 Value
The binary data contained in memory. The value is interpreted according to the variable's datatype.

 Address
The location in memory where the value is stored.

 Size
The number of bytes that the variable occupies in memory.

 Datatype
The interpretation of the value.

 Range
The minimum and maximum values of the variable. The range of a variable depends on its size. In
general, the bigger the size in bytes, the bigger the range.

Declaration of variables:

Syntax:

Datatype variable_name;

Example on variable declarations:


int maxAge;
int x, y, selectedIndex;
char a, b;
boolean flag;
double maxVal, massInKilos;
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 18

Initialization of Variable at the time of declaration:

Syntax:

Datatype variable_name=value;

Example on Variable initialization in declaration:


int timeInSeconds = 245;
char a = 'K', b = '$';
boolean flag = true;
double maxVal = 35.875;

Dynamic initialization of variable:

Datatype variable_name=Expression;

Example on Dynamic initialization

double a =10.0,b=20.0;

double d=Math.squart(49)+a+b;

Types of Variable

There are three types of variables in java


 Local Variable
 Instance Variable
 Static Variable

Local Variable

A variable that is declared inside the method is called Local variable.

Instance Variable

A variable that is declared inside the class but outside the method is called instance variable .

It is not declared as static.


Static variable

A Variable that is declared as static is called static variable. It cannot be local.


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 19

Example to understand the types of variables

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class

Scope and life time of a variable: The scope determines what objects are visible to other parts of program
and also determine Lifetime of the objects. In java, scope is defined by the class and by the method. The
instance variables and static variables are declared which the class and out of any method ,so this types
variables are available throughout the class The local variables are declared inside the method .so this variables
are available with the block in which there are declared.

Type conversion and casting

The process of converting one data type to another data type is called as Casting

Types of castings:

There are two type of castings

1. Explicit type conversion (or) Narrowing conversion


2. Implicit type conversion (or ) Widening conversion

1.Casting Incompatible Types or explicit type conversion or narrowing conversion

Casting larger data type into smaller data type may result in a loss of data.

This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the
value narrower.

To create a conversion between two incompatible types, you must use a cast. A cast is

simply an explicit type conversion.


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 20

It has this general form:

type variable1=(target-type) variable;


Example:

int m=50;

byte n=(byte)m;

2.Java’s Automatic Conversions or implicit type conversion or widening conversion

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:

a. The two types are compatible.


b. The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place.

Example:

byte b=75;

int a=b;

The int type is always large enough to hold all valid byte values, so no explicit cast statement is

required. class typecastdemo


{
public static void main(String args[])
{
float f=3.141,x;
int I,j=30;
i=(int)f;//explicit conversion
x=j;//implicit conversion
System.out.println(“i value is”+i);
System.out.println(“x value is”+x);
}
}

Output: i value is 3

x value is 30.00
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 21

1.12 Arrays

Definition of Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

 Java array is an object the contains elements of similar data type.


 It is a data structure where we store similar elements.
 We can store only fixed set of elements in a java array.
 Array in java is index based, first element of the array is stored at 0 index.
 An array is an indexed collection of fixed number of homogeneous data elements.

Types of Array in java

There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array.

1.Single Dimensional Array:

Single dimensional array declaration:

Sytax:
Datatype arrayname[ ];
Or
Datatype[ ] arrayname;

Example :

int a[ ];

int[ ] a; //recommended to use because name is clearly separated from the type int [ ]a;

At the time of declaration we can’t specify the size otherwise we will get compile time error.

Creation of Array construction:

Every array in java is an object hence we can create by using new operator.

Syntax for Creating:

arrayname=new datatype[size];

Example :
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 22

a= new int[3];

we can also combine declaration and creation into one step

Syntax Datatype[ ] arrayname= new datatype[size];

Example:

int[] a=new int[3];

Diagram:

For every array type corresponding classes are available but these classes are part of java language
and not available to the programmer level.
Rules for creating an Array
Rule 1 :

 At the time of array creation compulsory we should specify the size otherwise we will get compile time
error.

Rule 2:

 It is legal to have an array with size zero in java.

Rule 3 :

 If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.

Rule 4:

 The allowed data types to specify array size are byte, short, char, int. By mistake if we are using any
other type we will get compile time error.

Rule 5 :

 The maximum allowed array size in java is maximum value of int size [2147483647].
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 23

Array initialization:

Syntax for initialization of Single Dimensional Array:

arrayname[subscript]=value;

Example:

int[] a=new int[4];

a[0]=10; a[1]=20;a[2]=30;

a[3]=40; a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4

a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4

Diagram:

Note:if we are trying to access array element with out of range index we will get
RuntimeException saying ArrayIndexOutOfBoundsException

Declaration construction and initialization of an array in a single line:

 We can perform declaration construction and initialization of an array in a single line.

Example:

int [] a={10,20,30};//valid

String[] s={"abc","def","jog","lmn”};(valid)
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 24

Whenever we are creating an array every element is initialized with default value automatically.

Example 1:

int[] a=new int[3];


System.out.println(a);//
System.out.println(a[0]);
Diagram :

Array Length:

length Vs length():

length:

 It is the final variable applicable only for arrays.


 It represents the size of the array.

length() method:

 It is a final method applicable for String objects.


 It returns the no of characters present in the String.

Example:

int[] x=new int[3];

System.out.println(x.length);//3

System.out.println(x.length());//C.E: cannot find symbol

Example:

String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 25

Example on Single Dimensional Array :


class Testarray1
{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output :
33
3
4
5

Array and Functions (or)Passing single dimensional array to a function

Passing Array to method in java. We can pass the java array to method so that we can reuse the same logic
on any array.

Let's see the simple example to get minimum number of an array using method.

class Testarray2 {

static void min(int arr[]) {


int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a); //passing array to method
}
}
Output: 3
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 26

2. Multidimensional Array

Two dimensional array

In java multidimensional arrays are implemented as array of arrays approach but not matrix form.

 The main advantage of this approach is to improve memory utilization.

Two dimensional array declaration:

Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;

Alternate two dimensional array Declaration Syntax

int [ ][ ]a; int [ ][ ]a; int a[ ] [ ]; int [ ] [ ]a; int [ ] a[ ]; int [ ]a[ ];

Example :

Creation of Two- Dimensional array:

syntax:

arrayname=new datatype[size] [size];

Example:

int a[ ] [ ];

a=new int[3][2];

we can also combine declaration and creation into one step

Syntax

Datatype[ ][ ] arrayname= new datatype[size] [size];


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 27

Example1:

Variable Size Array:

int[][] a=new int[3][];

a[0]=new int[2];

a[1]=new int[4];

a[2]=new int[3];

Two- Dimensional Array initialization :

Syntax for initialization of Two- Dimensional Array:

datatype [subscript][subscript] arrayname ={list of value};

Example:

int[][] a={{10,20,30},{40,50}};`

Diagram:

If we want to use this short cut compulsory we should perform declaration, construction and initialization in
a single line. If we are trying to divide into multiple lines then we will get compile time error.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 28

Two Dimensional array length

Length variable applicable only for arrays where as length()method is applicable for String objects.

Example :

int[][] a=new int[6][3];


System.out.println(a.length);//6
System.out.println(a[0].length);//3

Diagram:

Examples on Two Dimensional array


Example : program to declare,create,initialize and access the elements of 2-D array
class array2d

public static void main(String args[]) {

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

for(int i=0;i<3;i++) {

for(int j=0;j<3;j++) {

System.out.print(arr[i][j]+" ");

System.out.println();

}
}
}
Output:1 2 3
245
445
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 29

Alternate Three dimensional array declaration Syntax:

int[ ][ ][ ] a;

int [ ][ ][ ]a;

int a[ ][ ][ ]; All are valid statements

int [ ] a[ ][ ];

int [ ][ ]a[ ];

Anonymous Arrays:

Sometimes we can create an array without name such type of nameless arrays are called anonymous arrays.

The main objective of anonymous arrays is “just for instant use”.


We can create anonymous array as follows.

new int[]{10,20,30,40}; (valid)


new int[][]{{10,20},{30,40}}; (valid)

At the time of anonymous array creation we can’t specify the size otherwise we will get compile time error.

Example :

new int[3]{10,20,30,40};//C.E:';' expected(invalid)

Advantage of Java Array

o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of the code
will be improved

Disadvantage of Java Array

o Fixed in size that is once we created an array there is no chance of increasing or decreasing the size
based on our requirement that is to use arrays concept compulsory we should know the size in
advance which may not possible always. We can resolve this problem by using collections.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 30

1.13 Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −

 Arithmetic Operators

 Relational Operators

 Bitwise Operators

 Logical Operators

 Assignment Operators

 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10

* (Multiplication) Multiplies values on either side of the operator. A * B will give 200

/ (Division) Divides left-hand operand by right-hand operand. B / A will give 2

% (Modulus) Divides left-hand operand by right-hand operand and B % A will give 0


returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 31

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes


== (equal to) (A == B) is not true.
then condition becomes true.

Checks if the values of two operands are equal or not, if


!= (not equal to) (A != B) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of


> (greater than) (A > B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (less than) (A < B) is true.
right operand, if yes then condition becomes true.

>= (greater than Checks if the value of left operand is greater than or equal to
(A >= B) is not true.
or equal to) the value of right operand, if yes then condition becomes true.

<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) is true.
equal to) value of right operand, if yes then condition becomes true.

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary
format they will be as follows −

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators −


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 32

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

Operator Description Example

Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12
& (bitwise and)
both operands. which is 0000 1100

(A | B) will give 61
| (bitwise or) Binary OR Operator copies a bit if it exists in either operand.
which is 0011 1101

Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49
^ (bitwise XOR)
but not both. which is 0011 0001

(~A ) will give -61 which


~ (bitwise Binary Ones Complement Operator is unary and has the effect is 1100 0011 in 2's
compliment) of 'flipping' bits. complement form due to
a signed binary number.

Binary Left Shift Operator. The left operands value is moved A << 2 will give 240
<< (left shift)
left by the number of bits specified by the right operand. which is 1111 0000

Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15
>> (right shift)
right by the number of bits specified by the right operand. which is 1111

Shift right zero fill operator. The left operands value is moved
>>> (zero fill A >>>2 will give 15
right by the number of bits specified by the right operand and
right shift) which is 0000 1111
shifted values are filled up with zeros.

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Show Examples
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 33

Operator Description Example

Called Logical AND operator. If both the


&& (logical
operands are non-zero, then the condition (A && B) is false
and)
becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses


the logical state of its operand. If a condition is
! (logical not) !(A && B) is true
true then Logical NOT operator will make
false.

The Assignment Operators

Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from right side operands C = A + B will assign
=
to left side operand. value of A + B into C

Add AND assignment operator. It adds right operand to the left C += A is equivalent
+=
operand and assign the result to left operand. to C = C + A

Subtract AND assignment operator. It subtracts right operand from C -= A is equivalent


-=
the left operand and assign the result to left operand. to C = C – A

Multiply AND assignment operator. It multiplies right operand with C *= A is equivalent


*=
the left operand and assign the result to left operand. to C = C * A

Divide AND assignment operator. It divides left operand with the C /= A is equivalent to
/=
right operand and assign the result to left operand. C=C/A
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 34

Modulus AND assignment operator. It takes modulus using two C %= A is equivalent


%=
operands and assign the result to left operand. to C = C % A

C <<= 2 is same as C
<<= Left shift AND assignment operator.
= C << 2

C >>= 2 is same as C
>>= Right shift AND assignment operator.
= C >> 2

C &= 2 is same as C =
&= Bitwise AND assignment operator.
C&2

bitwise exclusive OR and assignment operator. C ^= 2 is same as C =


^=
C^2

bitwise inclusive OR and assignment operator. C |= 2 is same as C =


|=
C|2

Miscellaneous Operators

Miscellaneous operators includes

 Conditional Operator ( ? : )
 instanceof Operator
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used
to evaluate Boolean expressions. The goal of the operator is to decide, which value should be assigned to the
variable. The operator is written as −

variable x = (expression) ? value if true : value if false


Following is an example −

Example

publicclassTest {
publicstaticvoid main(String args[]){
int a, b;
a =10;
b =(a ==1)?20:30;
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 35

System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}

This will produce the following result −

Output

Value of b is : 30
Value of b is : 20

instanceof Operator

This operator is used only for object reference variables. The operator checks whether the object is of a particular
type (class type or interface type). instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface
type on the right side, then the result will be true. Following is an example −

Example

publicclassTest{
publicstaticvoid main(String args[]) {
String name ="James";
// following will return true since name is type of String
boolean result = name instanceof(String);
System.out.println( result );
}
}

This will produce the following result −

Output

true
This operator will still return true, if the object being compared is the assignment compatible with the type
on the right.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 36

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it
first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

1.14 Expressions

Expressions, Statements, and Blocks

Definition: An expression is a series of variables, operators, and method calls (constructed according to the
syntax of the language) that evaluates to a single value

// other primitive types

char ch = 'S';

// display them all

System.out.println("have a nice day”); //statement

...

if (Character.isUpperCase(aChar)) //Block

... }
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 37

1.15 Control Statements

A control statement works as a determiner for deciding the next task of the other statements whether to execute
or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute first between
the two. In Java, the control statements are divided into three categories which are selection statements, iteration
statements, and jump statements. A program can execute from top to bottom but if we use a control statement.
We can set order for executing a program based on values and logic.

» Decision Making in Java

 Simple if Statement
 if…else Statement
 Nested if statement
 if...else if…else statement
 Switch statement

» Looping Statements in Java

 While
 Do…while
 For
 For-Each Loop

» Branching Statements in Java

 Break
 Continue
 Return
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 38

Decision Making in Java

Decision making statements are statements which decides what to execute and when. They are similar to decision
making in real time. Control flow statements control the flow of a program’s execution. Here flow of execution
will be based on state of a program. We have 4 decision making statements available in Java.

Simple if Statement :

Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code should
be executed based on the condition.

Syntax:
if (condition)
{
Statemen 1; //if condition becomes true then this will be executed
}
statement 2; //this will be executed irrespective of condition becomes true
or false

Example:
class ifTest {
public static void main(String args[]) {
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Output:
After if statement

if…else Statement :

In if…else statement, if condition is true then statements in if block will be executed but if it comes out as false
then else block will be executed.

Syntax: if (condition) {

Statemen 1; //if condition becomes true then this will be executed

}
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 39

Example:

class ifelseTest {
public static void main(String args[]) {
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Output:
i is less than 10
After if else statement

Nested if statement :

Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside
another if…else statement.

Syntax: if (condition1)
{
Statemen 1; //executed when condition1 is true
if (condition2)
{
Statement 2; //executed when condition2 is true
}
else
{
Statement 3; //executed when condition2 is false
}
}

Example:
class nestedifTest {
public static void main(String args[]) {
int x = 25;
if (x > 10) {
if (x%2==0)
System.out.println("i is greater than 10 and even number");
else
System.out.println("i is greater than 10 and odd number");
}
else {
System.out.println("i is less than 10");
}
System.out.println("After nested if statement");
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 40

}
}
Output:
i is greater than 10 and odd number
After nested if statement
if…else statement :

if…else if statements will be used when we need to compare the value with more than 2 conditions. They are
executed from top to bottom approach. As soon as the code finds the matching condition, that block will be
executed. But if no condition is matching then the last else statement will be executed.

if (condition1) {
Syntax: Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
....
....
else {
Statement 3; //executed when no matching condition found
}

Example:
class ifelseifTest {
public static void main(String args[]) {
int x = 2;
if (x > 10) {
System.out.println("i is greater than 10");
}
else if (x <10)
System.out.println("i is less than 10");
}
else {
System.out.println("i is 10");
}
System.out.println("After if else if ladder statement");
}
}
Output:
i is less than 10
After if else if ladder statement
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 41

Switch statement :

Java switch statement compares the value and executes one of the case blocks based on the condition. It is same
as if…else if ladder. Below are some points to consider while working with switch statements:

» case value must be of the same type as expression used in switch statement
» case value must be a constant or literal. It doesn’t allow variables
» case values should be unique. If it is duplicate, then program will give compile time error

Let us understand it through one example.

class switchDemo{
public static void main(String args[]) {
int i=2;
switch(i)
{
case 0:
System.out.println("i is 0");
break;
case 1:
System.out.println("i is 1");
break;
case 2:
System.out.println("i is 2");
break;
case 3:
System.out.println("i is 3");
break;
case 4:
System.out.println("i is 4");
break;
default:
System.out.println("i is not in the list");
break;
}
}
}

Output:
i is 2
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 42

Looping Statements in Java :

Looping statements are the statements which execute a block of code repeatedly until some condition meet to the
criteria. Loops can be considered as repeating if statements. There are 3 types of loops available in Java.

While :

While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes the
body of loop. This is repeated until the condition becomes false. Condition in while loop must be given as a
Boolean expression. If int or string is used instead, compile will give the error.

Syntax:
Initialization;
while (condition)
{
statement1;
increment/decrement;
}

Example:
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10) {
System.out.println(j);
j = j+2;
}
}
}
Output:
1 3 5 7 9
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 43

Do…while :

Do…while works same as while loop. It has only one difference that in do…while, condition is checked after the
execution of the loop body. That is why this loop is considered as exit control loop. In do…while loop, body of
loop will be executed at least once before checking the condition

Syntax: do
{
statement1;
}while(condition);

Example:

class dowhileLoopTest {

public static void main(String args[]) {

int j = 10;

do {

System.out.println(j);

j = j+1;

} while (j <= 10) ;

Output: 10

For Statement :

It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in code as
initialization of a variable, a condition and increment/decrement are declared only in a single line of code. It is
easy to debug structure in Java.

Syntax: for (initialization; condition; increment/decrement)

statement;

}
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 44

Example:

class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:

For-Each Loop :

For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.

Example:

class foreachDemo {

public static void main(String args[]) {

int a[] = {10,15,20,25,30};

for (int i : a) {

System.out.println(i);

Output:

10

15

20

25

30
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 45

Branching Statements in Java :

Branching statements jump from one statement to another and transfer the execution flow. There are 3 branching
statements in Java.

Break :

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly used in
loop to stop the execution and comes out of loop. When there are nested loops then break will terminate the
innermost loop.

Example:

class breakTest {

public static void main(String args[]) {

for (int j = 0; j < 5; j++) {

// come out of loop when i is 4.

if (j == 4)

break;

System.out.println(j);

System.out.println("After loop");

Output:

4
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 46

After loop

Continue :

Continue statement works same as break but the difference is it only comes out of loop for that iteration and
continue to execute the code for next iterations. So it only bypasses the current iteration.

Example:

class continueTest {

public static void main(String args[]) {

for (int j = 0; j < 10; j++) {

// If the number is odd then bypass and continue with next value

if (j%2 != 0)

continue;

// only even numbers will be printed

System.out.print(j + " ");

Output:

02468

Return :

Return statement is used to transfer the control back to calling method. Compiler will always bypass any sentences
after return statement. So, it must be at the end of any method. They can also return a value to the calling method.
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 47

1.16 Introducing Classes

Definition:

A class is a sort of template which has attributes and methods. An object is an instance of a class, e.g.
Ram is an object of type Person.

class classname {
// declare instance variables
type var1;
type var2;
// ... type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}

The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of program).

A Simple Class

Let’s begin our study of the class with a simple example. Here is a class called Box that defines three instance
variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon).

class Box {
JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 48

double width;

double height;

double depth;

As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use this
name to declare objects of type Box. It is important to remember that a class declaration only creates a template;
it does not create an actual object. Thus, the preceding code does not cause any objects of type Box to come into
existence.

To create an object of the class we use new keyword as shown below syntaxt

classname objectname=new classname( );


To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality. For the
moment, don’t worry about the details of this statement.

As mentioned earlier, each time you create an instance of a class, you are creating an object that contains its
own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of
the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The
dot operator links the name of the object with the name of an instance variable.

To set the values of the parameters we use the following syntax:

object.member=value;

For example, to assign the width variable of mybox the value 100, you would use the following statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object the
value of 100. In general, you use the dot operator to access both the instance variables and the methods within an
object.

Here is a complete program that uses the Box class:


JAVA PROGRAMMING CHAPTER 1: Object-Oriented Thinking PAGE NO: 49

/* A program that uses the Box class. Call this file BoxDemo.java */

class Box {

double width;

double height;

double depth;

// This class declares an object of type Box.

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

Output:

Volume is 3000

You might also like