Java Unit-1
Java Unit-1
Introduction to Object Oriented Programming Object-oriented programming organizes a program around its data (that is, objects) and a set
of well-defined methods to that data. An object-oriented program can be characterized as
Introduction: One Characteristic that is constant in the software industry today is the
data controlling access to code.
These include techniques such as modular programming, top-down programming, bottom-up Data Abstraction: Abstraction refers to the act of representing essential features without
programming and structured programming. The primary motivation in each case has been the including the background details or explanations. Classes use the concept of abstraction.
concern to handle the increasing complexity of programs that are reliable and maintainable.
Principles of OOP: The following are the 3 principles of OOP
With the advent of languages such as C, structured programming became very popular and was
1. Encapsulation
programmers to write moderately complex programs fairly easy. However, as the programs grew 2. Inheritance
3. Polymorphism
larger, even the structured approach failed to show the desired results in terms of bug-free, easy-
to-maintain, and reusable programs.
1. Encapsulation: Wrapping up of the data and methods into a single unit is known as
Object-Oriented Programming (OOP) is an approach to program organization and development, Encapsulation. Encapsulation is the mechanism that binds together code and the data it
which attempts to eliminate some of the pitfalls of conventional programming methods by manipulates, and keeps both safe from outside interference and misuse.
incorporating the best of structured programming features with several new concepts. Java is a
In Java the basis of encapsulation is the class. A class defines the structure and behavior
pure object oriented language.
(data and code) that will be shared by a set of objects. Each object of a given class contains
Need of OOP: Two Paradigms of Programming: All computer programs consist of two the structure and behavior defined by the class, as if it were stamped out by a mold in the
elements: code and data. Furthermore, a program can be conceptually organized around its code shape of the class. For this reason, objects are sometimes referred to as instances of a class.
or around its data. That is, some programs are written around what is happening and others are Thus, a class is a logical construct; an object has physical reality.
written around who is being affected. These are the two paradigms that govern how a program is
2. Inheritance: Inheritance is the process by which objects of one class acquire the properties of
constructed.
objects of another class. A class inherits state and behavior from its superclass. Inheritance
provides a powerful and natural mechanism for organizing and structuring software
The first way is called the process-oriented model. This approach characterizes a program as
programs.
a series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success.
Reusability is main advantage in inheritance by which we can add additional features to an
Problems with this approach appear as programs grow larger and more complex. To manage
existing class without modifying it. This is possible by deriving a new class from the existing
increasing complexity, the second approach, called object-oriented programming, was
one. The new class will have the combined features of both the classes.
conceived.
Java Programming Dept of CSE, VVIT Page 1 Java Programming Dept of CSE, VVIT Page 2
UNIT 1 Introduction to OOP UNIT 1 Introduction to OOP
3. Polymorphism: Polymorphism means the ability to take more than one form. For example, an Characteristics of POP:
operation may exhibit different behavior in different instances. The behavior depends upon Emphasis is on doing actions.
the types of data used in the operation. For example, consider the operation of addition. For Large programs are divided into smaller programs known as functions.
two numbers, the operation will generate a sum. If the operands are strings, then the Most of the functions shared global data.
operation would produce a third string by concatenation. Data move openly around the program from function to function.
Functions transform data from one form to another.
Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed
Employs top-down approach in program design.
in response to the call. Dynamic Binding is that the code associated with a given procedural call
is not known until the time of call at runtime. Dynamic Binding is associated with polymorphism OOP: OOP allows us to decompose a problem into a number of entities called objects and
and inheritance. then builds data and methods around these entities.
Message Communication: An OOP consists of a set of objects that communicate with each Def: OOP is an approach that provides a way of modularizing programs by creating portioned
other. The processing of programming in an OO language involves the following steps: memory area for both data and methods that can used as templates for creating copies of such
modules on demand.
1) Creating classes that define objects and their behavior.
OOP Characteristics:
2) Creating Objects form class definitions.
Emphasis on data.
3) Establishing communication among objects.
Programs are divided into what are known as methods.
Objects communicate with one another by sending and receiving information much the same Data structures are designed such that they characterize the objects.
way as people messages to one another. Methods that operate on the data of an object are tied together.
Data is hidden.
Procedure oriented Programming Vs Object Oriented Programming
Objects can communicate with each other through methods.
Procedure oriented Programming:
Reusability.
In this approach, the problem is always considered as a sequence of tasks to be done. A
Follows bottom-up approach in program design.
number of functions are written to accomplish these tasks. Here primary focus on Functions
and little attention on data. Applications of OOPs:
There are many high level languages like COBOL, FORTRAN, PASCAL, C used for Real time systems Neural networks and parallel
conventional programming commonly known as Procedure oriented Programming. Simulation and modeling programming
Procedure oriented Programming basically consists of writing a list of instructions for the OO database Decision support and office automation
computer to follow, and organizing these instructions into groups known as functions. Hypertext, hypermedia and expert-text systems
AI and expert systems CAM/CAD systems.
Java Programming Dept of CSE, VVIT Page 3 Java Programming Dept of CSE, VVIT Page 4
UNIT II Programming Constructs UNIT II Programming Constructs
Advantages of OOPs: There were five primary goals in the creation of the Java language
This eliminates redundant code and extends the use of classes with the concept of It should use the object-oriented programming methodology.
inheritance. It should allow the same program to be executed on multiple operating systems.
This can build the programs from the standard working modules that communicate with one It should contain built-in support for using computer networks.
another, rather than having to start writing the code from beginning. This leads to saving of It should be designed to execute code from remote sources securely.
development time and higher productivity. It should be easy to use by selecting what was considered the good parts of other object
The principle of data hiding helps the programmer to build secure programs that cannot be oriented languages.
invaded by code in other parts of the program.
It is possible to have multiple instance of an object to exist without any interference. The Creation of Java: Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed
Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the
Software complexity can be managed.
OO systems can be easily upgraded from small to large systems.
Between the initial implementation of Oak in the fall of 1992 and the public announcement of
History of JAVA: Java is related to C++, which is a direct descendant of C. Much of the
Java in the spring of 1995, many more people contributed to the design and evolution of the
character of Java is inherited from these two languages. From C, Java derives its syntax. Many of
language. Bill Joy, Arthur van Ho, Jonathan Payne, Frank Yellin, and Tim Lindholm were key
-
contributors to the maturing of the original prototype.
characteristics come from or are responses to its predecessors. Moreover, the creation of Java
was deeply rooted in the process of refinement and adaptation that has been occurring in
Java was designed not for the Internet, the primary motivation was the need for a platform-
computer programming languages for the past several decades.
independent (that is, architecture- neutral) language that could be used to create software to be
embedded in various consumer electronic devices, such as microwave ovens and remote
By the end of the 1980s and the early 1990s, object-oriented programming using C++ took hold.
controls. The trouble with C and C++ (and most other languages) is that they are designed to be
Indeed, for a brief moment it seemed as if programmers had finally found the perfect language.
compiled for a specific target. Although it is possible to compile a C++ program for just about
Because C++ blended the high efficiency and stylistic elements of C with the object-oriented
any type of CPU, to do so requires a full C++ compiler targeted for that CPU. The problem is
paradigm, it was a language that could be used to create a wide range of programs. However, just
that compilers are expensive and time-consuming to create. An easier and more cost
as in the past, forces were brewing that would, once again, drive computer language evolution
efficient solution was needed.
forward. Within a few years, the World Wide Web and the Internet would reach critical mass.
This event would precipitate another revolution in programming.
In an attempt to find such a solution, Gosling and others began work on a portable, platform-
independent language that could be used to produce code that would run on a variety of CPUs
under differing environments. This effort ultimately led to the creation of Java.
Java Programming Dept of CSE, VVIT Page 13 Java Programming Dept of CSE, VVIT Page 14
UNIT II Programming Constructs UNIT II Programming Constructs
Because of the similarities between Java and C++, Java should not be considered enable that program to execute on different systems. For example, in the case of an
Even though Java was influenced by C++, it is applet, the same applet must be able to be downloaded and executed by the wide variety
not an enhanced version of C++. For example, Java is neither upwardly nor downwardly of CPUs, operating systems, and browsers connected to the Internet. It is not practical to
compatible with C++. Of course, the similarities with C++ are significant. One other point: Java have different versions of the applet for different computers. The same code must work
was not designed to replace C++. Java was designed to solve a certain set of problems. C++ was on all computers.
designed to solve a different set of problems. Both will coexist for many years to come.
Java Virtual Machine:
Java and Internet: The Internet helped Java to the forefront of programming, and Java, in
Byte Code: The key that allows Java to solve both the security and the portability problems is
turn, had a profound effect on the Internet. In addition to simplifying web programming in
that the output of a Java compiler is not executable code. Rather, it is byte code.
general, Java innovated a new type of networked program called the applet that changed the way
the online world thought about content. Java also addressed some of the issues associated with
Byte code is a highly optimized set of instructions designed to be executed by the Java run-time
the Internet: portability and security.
system, which is called the Java Virtual Machine (JVM). In essence, the original JVM was
designed as an interpreter for byte code.
1. Java Applets: An applet is a special kind of Java program that is designed to be
transmitted over the Internet and automatically executed by a Java-compatible web
Translating a Java program into byte code makes it much easier to run a program in a wide
browser. Furthermore, an applet is downloaded on demand, without further interaction
variety of environments because only the JVM needs to be implemented for each platform. Once
with the user. If the user clicks a link that contains an applet, the applet will be
the run-time package exists for a given system, any Java program can run on it. Remember,
automatically downloaded and run in the browser. Applets are intended to be small
although the details of the JVM will differ from platform to platform, all understand the same
programs. The creation of the applet changed Internet programming because it expanded
Java byte code. Thus, the execution of byte code by the JVM is the easiest way to create truly
the universe of objects that can move about freely in cyberspace.
portable programs.
2. Security:
are taking a risk, because the code you are downloading might contain a virus, Trojan A Java program is executed by the JVM also helps to make it secure. Because the JVM is in
horse, or other harmful code. At the core of the problem is the fact that malicious code control, it can contain the program and prevent it from generating side effects outside of the
can cause its damage because it has gained unauthorized access to system resources. For system. As you will see, safety is also enhanced by certain restrictions that exist in the Java
example, a virus program might gather private information, such as credit card numbers, language.
bank account balances, and passwords, by searching the contents
In general, when a program is compiled to an intermediate form and then interpreted by a virtual
local file system. Java achieved this protection by conning an applet to the Java execution
machine, it runs slower than it would run if compiled to executable code. However, with Java,
environment and not allowing it access to other parts of the computer.
the differential between the two is not so great. Because byte code has been highly optimized, the
3. Portability: Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it. If a Java program were to be use of byte code enables the JVM to execute programs much faster than you might expect.
run on virtually any computer connected to the Internet, there needed to be some way to
Java Programming Dept of CSE, VVIT Page 15 Java Programming Dept of CSE, VVIT Page 16
UNIT II Programming Constructs UNIT II Programming Constructs
Just-In-Time (JIT) compiler: When a JIT compiler is part of the JVM, selected portions of byte management problems. Java also incorporates the concepts of exception handling which
code are compiled into executable code in real time, on a piece-by-piece, demand basis. It is captures series errors and eliminates any risk of crashing the system. Java systems not
important to understand that it is not practical to compile an entire Java program into executable only verify all memory access but also ensure that no viruses are communicated with an
code all at once, because Java performs various run-time checks that can be done only at run applet. The absence of pointers in java ensures that programs cannot gain access to
time. JIT compiles parts of the byte code that have similar functionality at the same time, and memory locations without proper authorization.
hence reduces the amount of time needed for compilation. It is used to improve the performance. f) Distributed: Java is designed as a distributed language for creating applications on
networks. It has the ability to share both data and programs. Java applications can open
Java Features: The Java language was invented not only for portability and security, but
and access remote objects on Internet as easily as they can do in local system. This
also there are many other features played an important role. The following are the features of
enables multiple programmers at multiple remote locations to collaborate and work
java
together on a single project.
a) Simple, Small and Familiar: Java is a simple and familiar language because it contains
g) Multithreaded and Interactive: Multithreaded means handling multiple tasks
many features of other Languages like c and C++. Java removes complexity because it
simultaneously. Java supports multithreaded programming. This means that we not wait
for the application to finish one task before beginning another. The java runtime comes
Multiple Inheritance and operator overloading.
with tools that support multiprocess synchronization and construct smoothly running
b) Compiled and Interpreted: Java combines the features of both compiled and interpreted
interactive systems.
approaches. First, Java compiler translates source code into what is known as byte code
h) High Performance: Java performance is impressive for an interpreted language, mainly
instructions. Byte codes are not machine instructions. Second, Java interpreter generates
due to the use of intermediate byte code. Java speed is comparable to the native C/C++.
machine code that can be directly executed by the machine that is running the java
Java architecture is also designed to reduce the overheads during runtime. Further, the
program. Java is both compiled and interpreted language.
incorporation of multithreading enhances the overall execution speed of java programs.
c) Platform-Independent and Portable: Java programs can be easily moved from one
i) Dynamic and Extensible: Java is a dynamic language. Java is capable of dynamically
computer system to another, anywhere and anytime. Changes and upgrades in operating
linking a new class libraries, methods, and objects. Java can also determine the type of
systems, processors and system resources will not force any changes in java programs.
class through a query, making it possible to dynamically link or abort the program,
Java ensures portability in two ways. First, Java compiler generates byte code instruction
depending on the response. Java programs support functions written in other languages
that can be implemented on any machine. Secondly, the sizes of the primitive data types
such as C and C++. These functions are known as native methods. Native methods are
are machine independent.
linked dynamically at runtime.
d) 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.
e) Robust and Secure: Java is a robust language. It provides many safeguards to ensure
reliable code. It has strict compile time and run time checking for data types. It is
designed as a garbage-collected language relieving the programmers virtually all memory
Java Programming Dept of CSE, VVIT Page 17 Java Programming Dept of CSE, VVIT Page 18
UNIT II Programming Constructs UNIT II Programming Constructs
Java Program Structure: A java program may contain many classes of which only one e) Class Definitions: A java program may contain multiple class definitions. Classes are the
class defines a main method. Classes contain data members and methods that operate on the data primary and essential elements of a java program. These classes are used to map the
members of the class. Methods may contain data type declarations and executable statements. objects of real-world problems.
The Java program contains the sections as in following figure. f) Main Method Class: Every stand-alone program requires a main method as its starting
point; this class is the essential part of a java program. The main method creates objects
of various classes and establishes communications between them. On reaching the end of
main, the program terminates and the control passes back to the operating system.
Programming Constructs
Variables: The variable is the basic unit of storage. 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.
Fig: General Structure of a Java Program
Declaring a Variable, in java all variables must be declared before they can be used.
a) Documentation Section: This Section comprises a set of comment lines giving the name Syntax: type identifier [= value] [, identifier [= value] ...];
of the program, the author and other details. Comments must explain why and what of The type atomic types, or the name of a class or interface. The identifier is the
classes. Java uses three styles of comments. One is single-line comment (//), Second one name of the variable. You can initialize the variable by specifying an equal sign and a value.
is multi- and the third one is That the initialization expression must result in a value of the same (or compatible) type as that
*/). specified for the variable. To declare more than one variable of the specified type, use comma
b) Package Statement: The first statement allowed in a java file is a package statement. separated list.
This statement declares a package name and informs the compiler that the classes defined E.g.: int a, b, c; or int a = 3, b = 5, c; byte d = 22; double pi = 3.14159; char s='s';
here belong to this package. Example: package student; The Package statement is
Dynamic Initialization: Although the preceding examples have used only constants as
optional.
initializers, Java allows variables to be initialized dynamically, using any expression valid at the
c) Import Statements: After a package statement there can be any number of import
time the variable is declared.
statements. This is similar to the #include statement in C. Example: import
java.util.Scanner;. This statement instructs the interpreter to load the Scanner class
//Dynamic initialization.
contained in the package java.util. Using import statements, we can have access to import java.util.Scanner;
class DynInit
classes that are part of other named packages.
{
d) Interface Statements: An interface is like a class but includes a group of method public static void main(String args[])
{
declarations. This is an optional section.
int num1,num2,num3;
Java Programming Dept of CSE, VVIT Page 19 Java Programming Dept of CSE, VVIT Page 20
UNIT II Programming Constructs UNIT II Programming Constructs
i. byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from
Data Types: Java defines 8 types of data: byte, short, int, long, char, float, double, and 128 to 127. Variables of type byte
boolean. Data types can be divided into 2 types of data from a network or f
1. Primitive Data Types (byte, short, int, long, float, double, char, boolean) -in types. Byte variables are
2. Non- Primitive Data Types (class, String, arrays, interfaces) declared by use of the byte keyword. E.g.: byte b, c;
Primitive Data types: The primitive types are defined to have an explicit range and ii. short: short is a signed 16-bit type. It has a range from 32,768 to 32,767. It is probably
mathematical behavior. the least-used in Java. E.g.: short s;
1. Integers: This group includes byte, short, int, and long, which are for whole-valued signed iii. int: int is a signed 32-bit type that has a range from 2,147,483,648 to 2,147,483,647. In
numbers, positive & negative numbers. addition to other uses, variables of type int are commonly employed to control loops and to
2. Floating-point numbers: This group includes float and double, which represent numbers index arrays. Therefore, int is often the best choice when an integer is needed. E.g.: int a,
with fractional precision. b, c;
3. Characters: This group includes char, which represents symbols in a character set, like iv. long: long is a signed 64-bit type and is useful for those occasions where an int type is not
letters and numbers. large enough to hold the desired value. The range of a long is quite large. This makes it
4. Boolean: This group includes boolean, which is a special type for representing true/false useful when big, whole numbers are needed.
values.
2. Floating point numbers: Floating point numbers are also known as real numbers. These are
1. Integers: Java defines four integer types: byte, short, int, and long. All of these are signed,
used for representing the fractional numbers. There are two types float and double
positive and negative values.
Width and ranges of floating types
a. Java does not support unsigned, positive-only integers.
Name Width(bits) Approximate Range
b. Many other computer languages support both signed and unsigned integers.
float 32 1.4e-045 to 3.4e+038
c. Java manages the meaning of the high-
double 64 4.9e-324 to 1.8e+308
d. The Java run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them. i. float: float specifies a single precision value that uses 32 bits of storage. Float is useful
when you need a fractional component. E.g.: float a, b;
Width and ranges of integer types
Java Programming Dept of CSE, VVIT Page 21 Java Programming Dept of CSE, VVIT Page 22
UNIT II Programming Constructs UNIT II Programming Constructs
ii. double: Its representation is faster than the float representation. It can be used for high b is true
This is executed.
speed calculations. E.g.: double a, b, c;
10 > 9 is true.
3. Characters: In Java, the data type used to store characters is char. char in Java is not the
Non-Primitive (Reference) Data type: A reference data type is used to refer to an object. A
same as char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java.
reference variable is declared to be of specific and that type can never be change.
Instead, Java uses Unicode to represent characters. It is a unification of dozens of character
sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For Identifiers: - Identifiers must start with a letter, a currency character ($), or a connecting
this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 character such as the underscore _.
to 65,536. There are no negative chars. The standard set of characters known as ASCII still a. Identifiers cannot start with a number.
ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-1, ranges b. After the first character, identifiers can contain any combination of letters, currency
from 0 to 255. E.g.: char ch1, ch2; ch1 = 'Y'; ch2 = 88; // code for X; characters, connecting characters, or numbers.
4. Booleans: Java has a primitive type, called boolean, for logical values. It can have only one c. There is no limit to the number of characters an identifier can contain.
of two possible values, true or false. This is the type returned by all relational operators, as d. You can't use a Java keyword as an identifier.
in the case of a < b. boolean is also the type required by the conditional expressions that e. Identifiers in Java are case-sensitive; foo and FOO are two different identifiers.
govern the control statements such as if and for. f. A legal identifier for a variable is also a legal identifier for a method or a class.
E.g.: Program
Naming Conventions: Java naming convention is a rule to follow as you decide what to name
class BoolTest
{ your identifiers such as class, package, variable, constant, method etc. But, it is not forced to
public static void main(String args[])
follow. So, it is known as convention not rule. All the classes, interfaces, packages, methods and
{
boolean b; fields of java programming language are given according to java naming convention.
b = false;
Advantage of naming conventions in java: By using standard Java naming conventions, you
System.out.println("b is " + b);
b = true; make your code easier to read for yourself and for other programmers. Readability of Java
System.out.println("b is " + b);
program is very important. It indicates that less time is spent to figure out what the code does.
// a boolean value can control the if statement
if(b)
System.out.println("This is executed."); Name Convention
b = false;
if(b) should start with uppercase letter and be a noun e.g. String, Color, Button,
System.out.println("This is not executed."); class name
System, Thread etc.
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9)); should start with uppercase letter and be an adjective e.g. Runnable, Remote,
interface
} name ActionListener etc.
}
Output: should start with lowercase letter and be a verb e.g. actionPerformed(), main(),
b is false method name
print(), println() etc.
Java Programming Dept of CSE, VVIT Page 23 Java Programming Dept of CSE, VVIT Page 24
UNIT II Programming Constructs UNIT II Programming Constructs
variable should start with lowercase letter e.g. firstName, orderNumber etc. Primitive types boolean, byte, char, double, float, int, long, short
name
Error handling assert, catch, finally, throw, throws, try
package should be in lowercase letter e.g. java, lang, sql, util etc.
name Enumeration enum
constants should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc. Others super, this, void
name
Unused const, goto
Keywords: The Java programming language has total of 50 reserved keywords which have
special meaning for the compiler and cannot be used as variable names. Following is a list of Literals: Literals in Java are a sequence of characters (digits, letters, and other characters)
Java keywords in alphabetical order, click on an individual keyword to see its description and that represent constant values to be stored in variables. Literals can be any number, text, or other
usage example. information that represents a value. Java language specifies five major types of literals. They
abstract assert boolean break byte case are: Integer literals, Floating literals, Character literals, String literals, and Boolean literals. Each
catch char class const continue default of them has a type associated with it. The type describes how the values behave and how they
do double else enum extends final are stored.
finally float for goto if implements
import instanceof int interface long native 1. Integer literals: Integer data types consist of the following primitive data types: int, long,
new package private protected public return byte, and short. byte, int, long, and short can be expressed in decimal(base10),
short static strictfp super switch synchronized hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate
this throw throws transient try void octal and prefix 0x indicates hexadecimal when using these number systems for literals.
volatile while Examples: int decimal = 100; int octal = 0144; int hexa = 0x64;
Points regarding Java keywords: 2. Floating-point literals: Floating-point numbers are like real numbers in mathematics, for
example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and
o const and goto are resevered words but not used.
o true, false and null are literals, not keywords. double. The default type when you write a floating-point literal is double, but you can
o all keywords are in lower-case. designate it explicitly by appending the D (or d) suffix. However, the suffix F (or f) is
Category Keywords appended to designate the data type of a floating-point literal as float. We can also specify a
Access modifiers private, protected, public floating-point literal in scientific notation using Exponent (short E ore), for instance: the
Class, method, abstract, class, extends, final, implements, double literal 0.0314E2 is interpreted as: 0.0314 *10² (i.e. 3.14).
variable modifiers interface, native,new, static, strictfp, synchronized, transient, volatile float ff = 89.0f; double dou = 89.0D; double doub = 89.0d;
float f = 89.0; // Type mismatch: cannot convert from double to float
Flow control break, case, continue, default, do, else, for, double doubl = 89.0; //OK, by default floating point literal is double
if, instanceof,return, switch, while
3. Boolean Literals: The values true and false are treated as literals in Java programming.
Package control import, package
When we assign a value to a boolean variable, we can only use these two values. Unlike C,
Java Programming Dept of CSE, VVIT Page 25 Java Programming Dept of CSE, VVIT Page 26
UNIT II Programming Constructs UNIT II Programming Constructs
we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. 6. String Literals: The set of characters in represented as String literals in Java. Always use
We have to use the values true and false to represent a Boolean value. Example boolean "double quotes" for String literals. There are few methods provided in Java to
chosen = true; combine strings, modify strings and to know whether to strings have the same values.
4. Null Literals: The final literal that we can use in Java programming is a null literal. We
specify the Null literal in the source code as 'null'. To reduce the number of references to an "" The empty string
"\"" A string containing
object, use null literal. The type of the null literal is always null. We typically assign null "This is a string" A string containing 16 characters
literals to object reference variables. For instance s = null; actually a string-valued constant expression, formed
"This is a " + "two-line string"
from two string literals
5. Character literals: char data type is a single 16-bit Unicode character. We can specify a
Standard Default Values: In j
character literal as a single printable character in a pair of single quote characters such as 'a',
variable when it is first created, java provides default value to that variable type automatically as
'#', and '3'. You must know about the ASCII character set. The ASCII character set includes
shown in following table:
128 characters including letters, numerals, punctuation etc. Below table shows a set of these
special characters. Type of Variable Default Value
Byte 0 (byte)
Short 0 (short)
Escape Meaning
int 0
\n New line
Long 0L
\t Tab
Float 0.0f
\b Backspace Double 0.0d
\r Carriage return Char null character
\f Formfeed Boolean false
\\ Backslash Reference null
Single quotation
\'
mark
Double quotation
\" Operators: Java provides a rich set of operators. An operator is a symbol that tells the
mark
\d Octal computer to perform certain mathematical or logical manipulations. Operators are used in
\xd Hexadecimal programs to manipulate data and variables.
\ud Unicode character
The following table shows the related categories:
If we want to specify a single quote, a backslash, or a non-printable character as a character
literal use an escape sequence. An escape sequence uses a special syntax to represents a Category Operators
character. The syntax begins with a single backslash character. Simple assignment =
Arithmetic + - * / %
Unary + - ++ -- !
Relational == != > >= < <=
Conditional && || ? : (ternary)
Type comparison instanceof
Java Programming Dept of CSE, VVIT Page 27 Java Programming Dept of CSE, VVIT Page 28
UNIT II Programming Constructs UNIT II Programming Constructs
Bitwise and Bit ~ << >> >>> & ^ | public static void main(String[] args)
shift {
String firstName = "James";
String lastName = "Gosling";
String greeting = "Hello " + firstName + " " + lastName;
1. Simple assignment: This is the most commonly used operator. It assigns the value on its right System.out.println(greeting);
to the operand on its left. Here are some examples: }
}
Output:
Assigning numbers: int x = 10; float y = 3.5F; Hello James Gosling!
3. Unary operators: The unary operators involve in only a single operand. The following table
lists all unary operators in Java:
2. Arithmetic operators: The arithmetic operators are used to perform mathematic calculations
just like basic mathematics in school. The following table lists all arithmetic operators in Java: Operator Meaning
+ Unary plus operator; indicates positive value
Operator Meaning (numbers are positive by default, without this
+ Addition (and strings concatenation) operator operator).
- Subtraction operator - Unary minus operator; negate an expression.
* Multiplication operator ++ Increment operator; increments a value by 1.
/ Division operator -- Decrement operator; decrements a value by 1;
% Remainder operator ! Logical complement operator; inverts value of
a boolean.
Example Program: result = y / x;
public class ArithmeticDemo System.out.println("y / x = " + result); Example Program:
{ result = x % 3; public class UnaryDemo
public static void main(String[] args) System.out.println("x % 3 = " + result); {
{ } public static void main(String[] args)
int x = 10; } {
int y = 20; Output: int x = 10;
int result = x + y; x + y = 30 int y = 20;
System.out.println("x + y = " + result); x - y = -10 int result = +x;
result = x - y; x * y = 200 System.out.println("+x = " + result);
System.out.println("x - y = " + result); y/x=2 result = -y;
result = x * y; x%3=1 System.out.println("-y = " + result);
System.out.println("x * y = " + result); result = ++x;
System.out.println("++x = " + result);
The addition operator (+) can also be used for joining two or more strings together (strings
result = --y;
System.out.println("++y = " + result);
boolean ok = false;
System.out.println(ok);
public class StringConcatDemo
System.out.println(!ok);
{
}
Java Programming Dept of CSE, VVIT Page 29 Java Programming Dept of CSE, VVIT Page 30
UNIT II Programming Constructs UNIT II Programming Constructs
} 4. Relational operators: The relational operators are used to compare two operands or two
Output:
expressions and result is a boolean. The following table lists all relational operators in Java.
+x = 10
-y = -20
++x = 11 Operator Meaning
++y = 19 == equal to
false != not equal to
true > greater than
>= greater than or equal to
< less than
<= less than or equal to
Note that the increment and decrement operators can be placed before (prefix) or after (postfix)
the operand, e.g. ++x or x++, --y or y--. When using these two forms in an expression, the
difference is: public class RelationalDemo
Prefix form: the operand is incremented or decremented before used in the expression. {
public static void main(String[] args)
Postfix form: the operand is incremented or decremented after used in the expression. {
The following example illustrates the prefix/postfix: int x = 10;
int y = 20;
boolean result = x == y;
public class PrefixPostfixDemo System.out.println("x == y? " + result);
{ result = x != y;
public static void main(String[] args) System.out.println("x != y? " + result);
{ result = x > y;
int x = 10; System.out.println("x > y? " + result);
int y = 20; result = x >= y;
System.out.println(++x); System.out.println("x >= y? " + result);
System.out.println(x++); result = x < y;
System.out.println(x); System.out.println("x < y? " + result);
System.out.println(--y); result = x <= y;
System.out.println(y--); System.out.println("x <= y? " + result);
System.out.println(y); }
} }
} Output:
Output: x == y? false
11 x != y? true
11 x > y? false
12 x >= y? false
19 x < y? true
19 x <= y? true
18
Java Programming Dept of CSE, VVIT Page 31 Java Programming Dept of CSE, VVIT Page 32
UNIT II Programming Constructs UNIT II Programming Constructs
5. Conditional operators: The conditional operators (&& and ||) are used to perform Example:
conditional-AND and conditional-OR operations on two boolean expressions and result in a public class TernaryDemo
{
-
public static void main(String[] args)
{
For the && operator: if the left expression is evaluated to false, then the right expression is not int x = 10;
int y = 20;
evaluated. Final result is false.
int result = (x > 10) ? x : y;
System.out.println("result 1 is: " + result);
For the || operator: if the left expression is evaluated to true, then the right expression is not result = (y > 10) ? x : y;
System.out.println("result 2 is: " + result);
evaluated. Final result is true.
}
Operator Meaning }
&& conditional -AND operator Output: result 1 is: 20
|| conditional-OR operator result 2 is: 10
? : ternary operator in form of: A ? B : C 6. Type comparison operator (instanceof): The instanceof operator tests if an object is an
Example Program:
instance of a class, a subclass or a class that implements an interface; and result in a boolean
public class ConditionalDemo
{
public static void main(String[] args)
{ public class InstanceofDemo
int x = 10; {
int y = 20; public static void main(String[] args)
if ((x > 8) && (y > 8)) {
{ String name = "Java";
System.out.println("Both x and y are greater than 8"); if (name instanceof String)
} {
if ((x > 10) || (y > 10)) System.out.println("an instance of String class");
{ }
System.out.println("Either x or y is greater than 10"); }
} }
} Output:
} an instance of String class
Output:
Both x and y are greater than 8
Either x or y is greater than 10 7. Bitwise and Bit shift operators: These operators perform bitwise and bit shift operations on
only integral types, not float types. They are rarely used so the listing here is just for reference:
Other conditional operators are ? and : which form a ternary (three operands) in the following
form: result = A ? B : C. This is interpreted like this: if A evaluates to true, then evaluates B and Operator Meaning
~ unary bitwise complement; inverts a bit pattern
assign its value to the result. Otherwise, if A evaluates to false, then evaluates C and assign its << signed left shift
>> signed right shift
value to the result. For short, we can say: If A then B else C. So this is also referred as shorthand >>> unsigned right shift
for an if-then-else statement. & bitwise AND
Java Programming Dept of CSE, VVIT Page 33 Java Programming Dept of CSE, VVIT Page 34
UNIT II Programming Constructs UNIT II Programming Constructs
^ bitwise exclusive OR If all operators in an expression have same priority in such case the second property associated
| bitwise inclusive OR
with an operator comes into play, which is associativity. Associativity tells the direction of
public class BitDemo
{ execution of operators that can be either left to right or right to left.
public static void main(String[] args)
For example, in expression a = b = c = 8 the assignment operator is executed from right to left
{
int x = 10; that means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by
int result = x << 2;
b. You can parenthesize this expression as (a = (b = (c = 8))).
System.out.println("Before left shift: " + x);
System.out.println("After left shift: " + result);
}
The following is the Table which lists Java operators - precedence chart highest to lowest.
}
Output:
Before left shift: 10
After left shift: 40
Expressions: An arithmetic expression is a combination of variables, constants, and Precedence Operator Description Associativity
operators arranged as per the syntax of the language. Java can handle any complex mathematical 1 [] array index Left -> Right
expressions. () method call
. member access
Algebraic expression Java expression 2 ++ pre or postfix increment Right -> Left
-- pre or postfix decrement
ab-c a*b-c +- unary plus, minus
~ bitwise NOT
! logical NOT
(m+n)(x+y) (m+n)*(x+y)
3 (type type cast Right -> Left
3x2+2x+1 3*x*x+2*x+1 cast) object creation
Evaluation of Expression: Expressions in java are evaluated using an assignment of the form new
variable = expression; variable is any valid java variable name. When the statement is 4 * multiplication Left -> Right
/ division
encountered, the expression is evaluated first and the result then replaces the previous value of % modulus (remainder)
the variable on the left-hand side. All variables used in the expression must be assigned values 5 +- addition, subtraction Left -> Right
before evaluation is attempted. + string concatenation
6 << left shift Left -> Right
Precedence rules and Associativity: Java operators have two properties those are >> signed right shift
>>> unsigned or zero-fill right shift
precedence, and associativity. Precedence is the priority order of an operator, if there are two or
7 < less than Left -> Right
more operators in an expression then the operator of highest priority will be executed first then <= less than or equal to
higher, and then high. For example, in expression 1 + 2 * 5, multiplication (*) operator will be > greater than
>= greater than or equal to
processed first and then addition. It's because multiplication has higher priority or precedence instanceof reference test
than addition. 8 == equal to Left -> Right
Java Programming Dept of CSE, VVIT Page 35 Java Programming Dept of CSE, VVIT Page 36
UNIT II Programming Constructs UNIT II Programming Constructs
!= not equal to The double x is explicitly converted to int y. The thumb rule is, on both sides, the same data type
9 & bitwise AND Left -> Right should exist.
10 ^ bitwise XOR Left -> Right
3. Boolean casting: A boolean value cannot be assigned to any other data type. Except boolean,
11 | bitwise OR Left -> Right
all the remaining 7 data types can be assigned to one another either implicitly or explicitly; but
12 && logical AND Left -> Right
boolean cannot. We say, boolean is incompatible for conversion. Maximum we can assign a
13 || logical OR Left -> Right
boolean value to another boolean.
14 ?: conditional (ternary) Right -> Left
Following raises error.
15 = += -= assignment and short hand assignment Right -> Left
boolean x = true;
*= /= %= operators
int y = x; // error
&= ^= |=
<<= >>= boolean x = true;
>>>= int y = (int) x; // error
Primitive Type Conversion and Casting: Java supports two types of castings primitive
byte > short > int > long > float > double
data type casting and reference type casting. Reference type casting is nothing but assigning one
Java object to another object. Type casting comes with 3 categories. In the above statement, left to right can be assigned implicitly and right to left requires explicit
casting. That is, byte can be assigned to short implicitly but short to byte requires explicit
1. Implicit casting (widening conversion): A data type of lower size (occupying less memory)
casting.
is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is
widened to higher size. This is also named as automatic type conversion. Example:
Examples: public class Demo
int x = 10; // occupies 4 bytes {
double y = x; // occupies 8 bytes public static void main(String args[])
System.out.println(y); // prints 10.0 {
In the above code 4 bytes integer value is assigned to 8 bytes double value. char ch1 = 'A';
double d1 = ch1;
2. Explicit casting (narrowing conversion): A data type of higher size (occupying more
System.out.println(d1); // prints 65.0
memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM System.out.println(ch1 * ch1); // prints 4225 , 65 * 65
and requires explicit casting; a casting operation to be performed by the programmer. The higher
double d2 = 66.0;
size is narrowed to lower size. char ch2 = (char) d2;
double x = 10.5; // 8 bytes System.out.println(ch2); // prints B
int y = x; // 4 bytes ; raises compilation error }
In the above code, 8 bytes double value is narrowed to 4 bytes int value. It raises error. Let us }
explicitly type cast it.
double x = 10.5;
int y = (int) x;
Java Programming Dept of CSE, VVIT Page 37 Java Programming Dept of CSE, VVIT Page 38
UNIT II Programming Constructs UNIT II Programming Constructs
Flow of Control: A Java program is a set of statements, which are normally executed Here if condition is true then statement1 will be executed. if condition is false then
sequentially in the order in which they appear. This happens when options or repetitions of statement2 will be executed. statement1 and statement2 represent either a single statements or
certain calculations are not necessary. more than one statement. If more than one statement is used then they should be enclosed in
angular bracket {}.
When a program breaks the sequential flow and jumps to another part of the code, it is called
E.g.: if(a>b)
branching. When the branching is based on a particular condition, it is known as conditional
else
branching. It the branching takes place without any decision, it is known as unconditional
branching.
b) Nested if statement: A nested if is an if statement that is the target of another if or else.
1. Conditional Statements: these conditional statements include the following Nested ifs are very common in programming. When you nest ifs, the main thing to remember is
a) if else statement that an else statement always refers to the nearest if statement that is within the same block as the
b) nested if statement else and that is not already associated with an else.
c) if else if ladder
d) switch case statement Syntax: if(condition1)
{
2. Iteration Statements: these iteration statements include the following
if(condition2)
a) while loop //Statements1;
else
b) do while loop
//Statements2;
c) for loop }
else
3. Jump Statements: these jump statements include the following
//Statements3;
a) break E.g.: if(i == 10)
{
b) continue
if(j < 20)
c) return a = b;
else
1. Conditional Statements:
a = c; // associated with this else
a) if else statement: This statement is used to perform a task depending upon whether the given }
else
condition is true or false. Here a task represents single statement or group of statements.
a = d; // this else refers to if(i == 10)
Syntax: if(condition)
{
c) if-else-if Ladder: A common programming construct that is based upon a sequence of nested
//statements;
} ifs is the if-else-if ladder.
else
Syntax: if(condition)
{
// statement;
//Statements;
else if(condition)
}
// statement;
Java Programming Dept of CSE, VVIT Page 39 Java Programming Dept of CSE, VVIT Page 40
UNIT II Programming Constructs UNIT II Programming Constructs
else if(condition) The expression must be of type byte, short, int, or char; each of the values specified in the
// statement;
case statements must be of a type compatible with the expression.
else
//statement; Each case value must be a unique literal (that is, it must be a constant, not a variable).
The if statements are executed from the top down. As soon as one of the conditions controlling
Duplicate case values are not allowed.
the if is true, the statement associated with that if is executed, and the rest of the ladder is
E.g.: switch(i)
bypassed. If none of the conditions is true, then the final else statement will be executed. The {
case 0: System.out.println("i is zero.");
final else acts as a default condition; that is, if all other conditional tests fail, then the last else
break;
statement is performed. If there is no final else and all other conditions are false, then no action case 1: System.out.println("i is one.");
break;
will take place.
case 2: System.out.println("i is two.");
E.g.: int fib(int m) break;
{ case 3: System.out.println("i is three.");
if(m==1) break;
return 1; default: System.out.println("i is greater than 3.");
else }
if(m==2)
return 1;
else 2. Iteration Statements: are for, while, and do-while. These
return (fib(m-1)+fib(m-2));
statements create what we commonly call loops. As you probably know, a loop repeatedly
}
executes the same set of instructions until a termination condition is met.
d) switch: The switch a) while loop: The while l loop statement. It repeats a statement
dispatch execution to different parts of your code based on the value of an expression. As such, it or block while its controlling expression is true.
often provides a better alternative than a large series of if-else-if statements. Syntax: while(condition)
{
Syntax: switch (expression)
// body of loop
{
}
case value1:
The condition can be any Boolean expression. The body of the loop will be executed as long as
// statement sequence
break; the conditional expression is true. When condition becomes false, control passes to the next line
case value2:
of code immediately following the loop. The curly braces are unnecessary if only a single
// statement sequence
break; statement is being repeated.
...
E.g.: while(c<n)
case valueN:
{
// statement sequence
a=b;
break;
b=c;
default:
c=a+b;
// default statement sequence
}
}
Java Programming Dept of CSE, VVIT Page 41 Java Programming Dept of CSE, VVIT Page 42
UNIT II Programming Constructs UNIT II Programming Constructs
b) do-while loop: If the conditional expression controlling a while loop is initially false, then the // body
}
body of the loop will not be executed at all. However, sometimes it is desirable to execute the
E.g.: for(i=1;i<=n;i++)
body of a loop at least once, even if the conditional expression is false to begin with. In other {
a=b;
words, there are times when you would like to test the termination expression at the end of the
b=c;
loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do- c=a+b;
}
while. The do-while loop always executes its body at least once, because its conditional
Declaring Loop Control Variables Inside the for Loop
expression is at the bottom of the loop. for(datatype initialization; condition; iteration)
{
Syntax: do
// body
{
// body of loop
}
} while (condition);
E.g.: for(int i=1;i<=n;i++)
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
{
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop a=b;
b=c;
condition must be a Boolean expression.
c=a+b;
The do-while loop is especially useful when you process a menu selection, because you will 3. Jump Statements: Java supports three jump statements: break, continue, and return. These
usually want the body of a menu loop to execute at least once. Consider the following program, statements transfer control to another part of your program.
a) break: In Java, the break statement has three uses.
E.g.: int n=10; it terminates a statement sequence in a switch statement.
do
{ it can be used to exit a loop.
System.out.println(n);
n--;
}while(n>0); The last two uses are explained here.
Using break to Exit a Loop: By using break, you can force immediate termination of a loop,
c) for loop: The traditional form that has been in use since the original version of Java. When the bypassing the conditional expression and any remaining code in the body of the loop. When a
loop starts, the initialization portion of the loop is executed. Initialization expression executed break statement is encountered inside a loop, the loop is terminated and program control
only once and then condition is evaluated. This must be a Boolean expression. Check the resumes at the next statement following the loop.
condition; if the condition is true, then the body of the loop is executed. If it is fail, the loop E.g.: for(int i=0; i<100; i++)
terminates. Next, the iteration portion of the loop is executed and goes to increment or decrement {
if(i == 10)
the loop control variable and again checks the condition if it is true, then the body of the loop is break; // terminate loop if i is 10
executed. This process is repeated up to the condition is fail. System.out.println("i: " + i);
}
Syntax: traditional for statement: Labelled break: java supports labelled break
for(initialization; condition; iteration)
{ Syntax: break label;
boolean t = true;
Java Programming Dept of CSE, VVIT Page 43 Java Programming Dept of CSE, VVIT Page 44
UNIT II Programming Constructs UNIT II Programming Constructs
b) continue: The continue statement performs such an action. In while and do-while loops, a The General Form of a Class
class ClassName [extends SuperClassName]
continue statement causes control to be transferred directly to the conditional expression that
{
controls the loop. In a for loop, control goes first to the iteration portion of the for statement and [type instanceVariable1;]
[type instanceVariable2;]
then to the conditional expression. For all three loops, any intermediate code is bypassed.
[type methodName1(parameter-list)
E.g.: for(int i=0; i<10; i++) {
{ // body of method
System.out.print(i + " "); }]
if (i%2 == 0) continue; [type methodName2(parameter-list)
System.out.println(""); {
} // body of method
}]
}
c) return: The last control statement is return. The return statement is used to explicitly return
from a method. That is, it causes program control to transfer back to the caller of the method. As
Everything inside the square brackets is optional. Therefore, the following is a valid class
such, it is categorized as a jump statement. At any time in a method the return statement can be
definition:
used to cause execution to branch back to the caller of the method. Thus, the return statement
class Empty
immediately terminates the method in which it is executed. Here, return causes execution to {
}
return to the Java run-time system, since it is the run-time system that calls main( ).
E.g.: int fib(int m)
The data, or variables, defined within a class are called instance variables. The code is contained
{
if(m==1) within methods. Collectively, the methods and variables defined within a class are called
return 1;
Java Programming Dept of CSE, VVIT Page 45 Java Programming Dept of CSE, VVIT Page 46
UNIT II Programming Constructs UNIT II Programming Constructs
members of the class. Variables defined within a class are called instance variables because each Output:
Num1 value is 12 Num2 value is 22
instance of the class (that is, each object of the class) contains its own copy of these variables.
Methods: Classes usually consist of two things: instance variables and methods. Method is a
Object: An object in java is essentially a block of memory that contains space to store the
large one because Java gives them so much power and flexibility. This is the general form of a
instance variables. Creating an object is also refers to as instantiating an object. Objects are
method:
created using operator. The new operator dynamically allocates memory for an object and
return type methodName(parameter-list)
returns reference to that object.
{
ClassName cn; //declare the reference variable // body of method
}
cn=new ClassName(); //instantiate the object
Here, return type specifies the type of data returned by the method. This can be any valid type,
The first statement declares a variable to hold the object reference and the second one actually
including class types that you create. If the method does not return a value, its return type must
assigns the object reference to the variable. The variable cn is now an object of the ClassName.
be void.
Both Statements can be combined into one statement: ClassName cn=new ClassName();
Method name can be any legal identifier other than those already used by other items within
It is important to understand that any changes to the variables of one object have no effect on the
the current scope.
variables of another.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters
Accessing Class Members: Each object of a class is having its own set of variables, we should
are essentially variables that receive the value of the arguments passed to the method when it is
assign values to these variables in order to use them in our program. The following is the
called.
procedure for accessing a variable and a method respectively.
If the method has no parameters, then the parameter list will be empty.
objectname.variablename = value;
Methods that have a return type other than void return a value to the calling routine using the
objectname.methodname();
following form of the return statement: return value; here, value is the value returned.
Example: Program to illustrate class members:
Example:
import java.util.*;
class MethodDemo
class Example
{
{
int a,b,c;
int num1,num2;
int show()
void method()
{
{
return a*b*c;
}
}
void var(int x,int y, int z)
public static void main(String args[])
{
{
a=x;
Example e=new Example();
b=y;
e.num1=12;
c=z;
e.num2=22;
}
e.method();
}
}
class ParaMain
}
Java Programming Dept of CSE, VVIT Page 47 Java Programming Dept of CSE, VVIT Page 48
UNIT II Programming Constructs UNIT II Programming Constructs
{ }
public static void main(String args[]) Output: Default Constructor
{
Note: If there is no constructor in a class, compiler automatically creates a default constructor.
int d;
MethodDemo mdr=new MethodDemo(); Parameterized constructor: Parameterized constructor is used to provide different values to the
md.var(10,2,3);
distinct objects.
d=md.show();
System.out.println("D value: "+d); Example:
}
class ConstructorDemoOne
}
{
Output:
int num1,num2;
D value: 60
ConstructorDemoOne(int n1,int n2)
{
Constructors: Constructor in java is a special type of method that is used to initialize the num1=n1;
num2=n2;
object. Java constructor is invoked at the time of object creation. It constructs the values i.e.
}
provides data for the object that is why it is known as constructor. void display()
{
There are basically two rules defined for the constructor.
N n N
Constructor name must be same as its class name }
public static void main(String args[])
Constructor must have no explicit return type {
There are two types of constructors: ConstructorDemoOne cd=new ConstructorDemoOne(2,5);
cd.display();
Default constructor (no-arg constructor): A constructor that has no parameter is known as }
default constructor. }
Output:
Parameterized constructor: A constructor that has parameters is known as parameterized Num1 value is 2 Num2 value is 5.
constructor. Constructor Overloading: A constructor can also be overloaded. Overloaded constructors
Default constructor: Default constructor provides the default values to the object like 0, null etc. are differentiated on the basis of their type of parameters or number of parameters. Constructor
depending on the type. overloading is not much different than method overloading. In case of method overloading you
Example: have multiple methods with same name but different signature, whereas in Constructor
class ConstructorDemo overloading you have multiple constructor with different signature but only difference is that
{
ConstructorDemo() Constructor doesn't have return type in Java. Constructor overloading is done to construct object
{ in different ways.
} Example:
public static void main(String args[]) class ConstructorOLDemo {
{ { num1=num2=0;
ConstructorDemo cd=new ConstructorDemo(); int num1,num2; }
} ConstructorOLDemo() ConstructorOLDemo(int n1,int n2)
Java Programming Dept of CSE, VVIT Page 49 Java Programming Dept of CSE, VVIT Page 50
UNIT II Programming Constructs UNIT II Programming Constructs
} finalize() method: The finalize() method is invoked each time before the object is garbage
public static void main(String args[]) collected. This method can be used to perform cleanup processing. This method is defined in
{
CopyDemo cd=new CopyDemo(); Object class as: protected void finalize(){}
cd.display();
CopyDemo cd1=new CopyDemo(2,5);
cd1.display();
Java Programming Dept of CSE, VVIT Page 51 Java Programming Dept of CSE, VVIT Page 52
UNIT II Programming Constructs UNIT II Programming Constructs
Note: The Garbage collector of JVM collects only those objects that are created by new Box(double width, double height, Box b=new Box();
double length) double vol=b.volume();
keyword. So if you have created any object without new, you can use finalize method to perform
{
cleanup processing (destroying remaining objects). this.width=width;
this.height=height; Box b1=new Box(12,12,12);
this.length=length; b1.volume();
gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
}
processing. The gc() is found in System and Runtime classes. public static void gc(){}. double volume() of B
{ }
return width*length*height; }
Note: Neither finalization nor garbage collection is guaranteed.
} Output:
public static void main(String args[]) Volume of Box is -1
{ Volume of Box is 1728
Example: TestGarbage1 s2=new Example for this() can be used to invoke current class constructor.
public class TestGarbage1 TestGarbage1(); class ThisDemo
{ s1=null; {
public void finalize() s2=null; int num1,num2;
{ System.gc(); ThisDemo(int num1,int num2)
System.out.println("object is } {
garbage collected"); } this.num1=num1;
} Output: this.num2=num2;
public static void main(String args[]) object is garbage collected }
{ object is garbage collected ThisDemo(int num1)
TestGarbage1 s1=new {
this(num1,num1);
TestGarbage1(); }
ThisDemo()
this keyword: this is a reference variable that refers to the current object. The following {
this(0);
are the usages of this keyword. }
public static void main(String args[])
this keyword can be used to refer current class instance variable.
{
this() can be used to invoke current class constructor. ThisDemo td=new ThisDemo();
}
this keyword can be used to invoke current class method (implicitly) }
this can be passed as an argument in the method call. Explanation: this() is used for calling the current class constructor. this(0) calls the constructor
this can be passed as argument in the constructor call. which is having a single parameter constructor of type integer. this(num1,num1) calls the
this keyword can also be used to return the current class instance. constructor which is having two parameters of type integer.
Example for this keyword can be used to refer current class instance variable.
class Box { Static Keyword: If we want to define a class member where that will be used
{ width=length=height=-1; independently of any object of that class. Normally, a class member must be accessed only in
double width,height,length; }
Box() conjunction with an object of its class. But, it is possible to create a member that can be used by
Java Programming Dept of CSE, VVIT Page 53 Java Programming Dept of CSE, VVIT Page 54
UNIT II Programming Constructs UNIT II Programming Constructs
itself, without reference to a specific instance. To create such a member, precede its declaration { Static block initialized.
UseStatic.meth(42); x = 42
with the keyword static.
} a=3
When a member is declared static, it can be accessed before any objects of its class are created, } b = 12
and without reference to any object. You can declare both methods and variables to be static. The Output:
most common example of a static member is main( ). main( ) is declared as static because it must
be called before any objects exist.
The members that are declared as static are called static members. Since these members are Arrays: An array is a group of variables that are referred to by a common name. Arrays of
associated with the class itself rather than individual objects, the static variables and static any type can be created and may have one or more dimensions. A specific element in an array is
methods are referred as class variables and class methods in order to distinguish them from accessed by its index.
instance variables and instance methods. One-Dimensional Arrays: A one-dimensional array is a list of variables.
Static variables are used when we want to have a variable common to all instances of a class. To create an array, first you must create an array variable of the desired type.
Java creates only one copy for a static variable which can be used even if the class in not Syntax: type[] var-name;
instantiated. o type declares the base type of the array.
Methods declared as static have several restrictions: o The base type determines the data type of each element that comprises the `array. Thus,
They can only directly call other static methods. the base type for the array determines what type of data the array will hold.
They can only directly access static data. new is a special operator for allocating memory.
They cannot refer to this or super in any way. Syntax var-name = new type[size];
We can declare static block that gets executed exactly once, when the class is first loaded. static o type specifies the type of data being allocated.
variables and static methods can be used independently of any object. For this, we need to o size specifies the number of elements in the array which must be a numeric constant.
specify the name of their class followed by the dot operator. o var-name is the array variable that is linked to the array.
Syntax: ClassName.staticVariable; The elements in the array allocated by new will automatically be initialized to zero.
ClassName.staticMethod();
E.g.: int[] numbers = new int[3];
Example: // Demonstrate static variables, static
An array is a two-step process:
methods, and blocks. {
class UseStatic System.out.println("Static block o You must declare a variable of the desired array type.
{ initialized."); o You must allocate the memory that will hold the array, using new, and assign it to the
static int a = 3;
static int b; array variable.
static void meth(int x) b = a * 4;
Thus, in Java all arrays are dynamically allocated. Once you have allocated an array, you can
{ }
System.out.println("x = " + x); } access a specific element in the array by specifying its index within square brackets. All array
System.out.println("a = " + a); class StaticDemo
indexes start at zero.
System.out.println("b = " + b); {
} public static void main(String args[]) // Demonstrate a one-dimensional array.
Java Programming Dept of CSE, VVIT Page 55 Java Programming Dept of CSE, VVIT Page 56
UNIT II Programming Constructs UNIT II Programming Constructs
Java Programming Dept of CSE, VVIT Page 57 Java Programming Dept of CSE, VVIT Page 58
UNIT II Programming Constructs UNIT II Programming Constructs
Java Programming Dept of CSE, VVIT Page 59 Java Programming Dept of CSE, VVIT Page 60