SlideShare a Scribd company logo
Java™:
TheComplete Reference
UNIT – 1 & Chapter - 1
Syllabus
• TheHistory and Evolution of Java:Java’s Lineage,
The Creation of java, how java changed the internet,
Java’s magic: The byte code, Servlets: java on the
server side, java Buzzwords, Evolution of java.
• An Overview of Java: Object Oriented Programming,
Two control statements, Using blocks of codes,
Lexical issues, The java class Libraries.
• Data Types, Arrays and Variables: Primitive Types,
Integers, Floating-point Types, Characters, Booleans,
literals, variables, Type conversion and casting,
Automatic Type Promotion in Expressions, Arrays,
strings, Pointers.
Java’sLineage
• Java is related to C++, which is a direct
descendant of C.
• Much of the character of Java is inherited from
these two languages.
• From C,Java derives its syntax.
• Many of Java’s object-oriented features were
influenced by C++.
The Birth of Modern Programming: C
• The C language shook the computer world.
• When a computer language is designed, trade-offs are often
made, such as the following:
– Ease-of-use versus power
– Safety versus efficiency
– Rigidity versus extensibility
• Invented and first implemented by Dennis Ritchie on a DEC PDP-
11 running the UNIX operating system, C was the result of a
development process that started with an older language called
BCPL, developed by Martin Richards.
• BCPL influenced a language called B, invented by Ken
Thompson, which led to the development of C in the 1970s.
• C was formally standardized in December 1989, when the
American National Standards Institute (ANSI) standard for C was
adopted.
• C is a language designed by and for programmers.
C++:TheNext Step
• C is a successful and useful language,you might ask
why a need for something else existed.
The answer is complexity.
• Tosolve this problem, a new way to program was
invented, called object-oriented programming (OOP).
• C++ was invented by Bjarne Stroustrup in 1979, while
he was working at Bell Laboratories in Murray Hill,
New Jersey.
• Stroustrup initiallycalled the new language “Cwith
Classes.”
• However, in 1983, the name was changed to C++. C++
extends C by adding object-oriented features.
TheStage Is Set for Java
• By the end of the 1980s and the early 1990s,
object-oriented programming using C++ took
hold.
• Within a few years, the World Wide Web and the
Internet would reach critical mass.
• This event would precipitate another revolution in
programming.
TheCreation 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 first working
version. This language was initially called “Oak,”but
was renamed “Java”in 1995.
• Primary motivation was the need for a platform-
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 controls.
• The problem is that compilers are expensive and
time-consuming to create.
• Solution, a portable, platform-independent language
TheCreation of Java
• The second force was, of course, the World Wide
Web.
• The emergence of the World Wide Web, Javawas
propelled to the forefront of computer language
design, because the Web, too, demanded portable
programs.
• The Internet ultimately led to Java’s large-scale
success.
• Java is simply the “Internet version of C++.”
• Javawas to Internet programming what C was to
system programming: a revolutionary force that
changed the world.
TheC#Connection
• C#. Created by Microsoft to support the .NET
Framework.
• C# is closely related to Java.
• For example, both share the same general syntax,
support distributed programming, and utilize the
same object model.
How JavaChanged the Internet
• 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 thorniest issues
associated with the Internet: portability and
security.
JavaApplets
• An applet is a special kind of Java program that is
designed to be transmitted over the Internet and
automaticallyexecutedby a Java-compatible web
browser.
• Applets are intended to be small programs.
• They are typically used to display data provided by
the server, handle user input, or provide simple
functions, such as a loan calculator, that execute
locally,rather than on the server.
• In essence, the applet allows some functionality to be
moved from the server to the client.
• The creation of the applet changed Internet
programming because it expanded the universe of
objects that can move about freely in cyberspace.
JavaApplets
• Two very broad categories of objects that are transmitted
between the server and the client:
• passive information and
– e-mail, you are viewing passive data.
• dynamic, active programs.
– the applet is a dynamic, self-executingprogram.
• As desirable as dynamic, networked programs are, they also
present serious problems in the areas of security and portability.
• Obviously, a program that downloads and executes
automatically on the client computer must be prevented from
doing harm.
• It must also be able to run in a variety of different environments
and under different operating systems.
• As you will see, Java solved these problems in an effective and
elegant way.
Security
• Every time you download a “normal” program, a risk,
because the code you are downloading might contain a
virus, Trojanhorse, or other harmful code.
• For example, a virus program might gather private
information, such as credit card numbers, bank account
balances, and passwords, by searching the contents of your
computer’s local file system.
• Java enabled applets, to be downloaded and executed on
the client computer safely.
• Java achieved this protection by confining an applet to the
Java execution environment and not allowing it access to
other parts of the computer.
• The ability to download applets with confidence that no
harm will be done and that no security will be breached is
considered by many to be the single most innovative aspect
of Java.
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 Javaprogram were to be run on virtually any computer
connectedto the Internet, there needed to be some way to
enable that program to execute on different systems.
• For example, applet must be able to be downloaded and
executed by the wide variety of CPUs, operating systems,
and browsers connectedto the Internet.
• It is not practical to have different versions of the applet for
different computers.
• The same code must work on all computers. Therefore,
some means of generating portable executable code was
needed.
Java’sMagic: The Bytecode
• The key that allows Java to solve both the security
and the portability, the output of a Java compiler
is not executable code. Rather, it is bytecode.
• Bytecode is a highly optimized set of instructions
designed to be executed by the Java run-time
system, which is called the Java Virtual Machine
(JVM).
• In essence, the original JVM was designed as an
interpreter for bytecode.
Java’sMagic: The Bytecode
• Translating a Java program into bytecode makes it much
easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each
platform.
• Once the run-time package exists for a given system, any
Javaprogram can run on it.
• Remember, although the details of the JVM will differ from
platform to platform, all understand the same Java
bytecode.
• The execution of bytecode by the JVM is the easiest way to
create truly portable programs.
• The Javaprogram is executed by the JVM helps to make it
secure. Because the JVM is in control, it can contain the
program and prevent it from generating side effects outside
of the system.
Java’sMagic: The Bytecode
• In general, when a program is compiled to an
intermediate form and then interpreted by a virtual
machine, it runs slower than it would run if compiled
to executable code.
• However, with Java,the differential between the two
is not so great.
• Because bytecode has been highly optimized, the use
of bytecode enables the JVM to execute programs
much faster than you might expect.
• Java was designed as an interpretedlanguage, there
is nothing about Java that prevents on-the-fly
compilation of bytecode into native code in order to
boost performance.
• Sun began supplying its HotSpot technology.
HotSpot
• HotSpot provides a Just-In-Time (JIT)compiler for bytecode.
• When a JITcompiler is part of the JVM, selected portions of
bytecode are compiled into executable code in real time, on a
piece-by-piece, demand basis.
• It is important to understand that it is not practical to compile
an entire Java program into executable code all at once, because
Java performs various run-time checks that can be done only at
run time. Instead, a JITcompiler compiles code as it is needed,
during execution.
• Furthermore, not all sequences of bytecode are compiled—only
those that will benefit from compilation. The remaining code is
simply interpreted.
• However, the just-in-time approach still yields a significant
performance boost.
• Even when dynamic compilation is applied to bytecode, the
portability and safety features still apply, because the JVM is still
in charge of the execution environment.
Servlets: Javaon the Server Side
• As useful as applets can be, they are just one half of the client/server
equation.
• At Serverside, servlet.
• A servlet is a small program that executeson the server.Just as applets
dynamically extend the functionality of a web browser, servlets
dynamically extend the functionality of a web server.
• Thus, with the advent of the servlet, Javaspanned both sides of the
client/server connection.
• Servlets are used to create dynamically generated content that is then
served to the client. For example, an online store might use a servlet to
look up the price for an item in a database.
• Dynamically generated content is availablethrough mechanisms such as
CGI (Common Gateway Interface).
• Because servlets (like all Javaprograms) are compiled into bytecode and
executedby the JVM, they are highly portable.Thus, the same servlet
can be used in a variety of different server environments. The only
requirementsare that the server support the JVM and a servlet
container.
JVM
• A Virtual Machine is a software
implementation of a physical machine. Java
was developed with the concept of WORA
(WriteOnce Run Anywhere), which runs on
a VM.
• The compiler compiles the Java file into a
Java .class file, then that .class file is input into
the JVM, which loads and executes the class
file.
myprog.c myprog.exe
OS/Hardware
machine code
C source code
gcc
Platform Dependent
JVM
myprog.class
bytecode
Java source code
myprog.java
javac
OS/Hardware
Platform Independent
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
TheJavaBuzzwords
• The key considerations were summed up by the Java
team in the following list of buzzwords:
– Simple
– Secure
– Portable
– Object-oriented
– Robust
– Multithreaded
– Architecture-neutral
– Interpreted
– High performance
– Distributed
– Dynamic
TheJavaBuzzwords :Simple
• Based on popular languages called C and C++
• C:old, pretty bare bones language
• C++: newer, more complicated language
• Start from C and add some of C++’s more useful features
“Java omits many rarely used, poorly understood, confusing
features of C++ that in our experience bring more grief than
benefits” (Gosling)
TheJavaBuzzwords :Secure
TheJavaBuzzwords :Portable
TheJavaBuzzwords :ObjectOriented
• The object-oriented paradigm
– problems and their solutions are packaged in terms of classes
– the information in a class is the data
– the functionality in a class is the method
– a class provides the framework for building objects
• Object-oriented programming (OOP) allows pieces of programs to
be used in other contexts more easily
TheJavaBuzzwords :Robust
• program must execute reliably in a variety of systems.
• Java is a strictly typed language, it checks your code at compile
time. However, it also checks your code at run time.
• A robust program may not do exactly what it is supposed to do, but
it should not bring down other unrelated programs down with it
• Reliability
– early (compile time) checking
– dynamic (runtime) checking
– eliminating situations that are error prone.
• Example: Two of the main reasons for program failure: memory
management mistakes and mishandled exceptional conditions (that
is, run-time errors).
TheJavaBuzzwords:Multithread
• Java supports multithreadedprogramming, which allows you to
write programs that do many things simultaneously.
• A thread is a part of the program that can operate independently of
its other parts
• Multi-threaded programs can do multiple things at once
– example:
• download a file from the web while still looking at other web
pages
• Question: What is the problem with multiple agents working at the
same time?
– synchronization
TheJavaBuzzwords :Architecture-
Neutral
• Goal was “write once; run anywhere, any time, forever.”
• One of the main problems facing programmers is that no guarantee
exists that if you write a program today, it will run tomorrow—even
on the same machine.
• Operating system upgrades, processor upgrades, and changes in
core system resources can all combine to make a program
malfunction.
TheJavaBuzzwords :Interpreted and
High Performance
• Java enables the creation of cross-platform programs by compiling
into an intermediate representation called Java bytecode. This code
can be executed on any system that implements the Java Virtual
Machine.
• Most previous attemptsat cross-platform solutions have done so at
the expense of performance.
• The Java bytecode was carefully designed so that it would be easy
to translate directly into native machine code for very high
performance by using a just-in-time compiler (JIT).
• Java run-time systems that provide this feature lose none of the
benefits of the platform-independent code.
TheJavaBuzzwords:Distributed
• Java is designed for the distributed environment
of the Internet because it handles TCP/IP
protocols.
• In fact, accessing a resource using a URL is not
much different from accessing a file.
• Java also supports Remote Method Invocation
(RMI). This feature enables a program to invoke
methods across a network.
TheJavaBuzzwords: Dynamic
• Java programs carry with them substantial
amounts of run-time type information that is used
to verify and resolve accesses to objects at run
time.
• This makes it possible to dynamically link code in
a safe and expedient manner.
• This is crucial to the robustness of the Java
environment, in which small fragments of
bytecode may be dynamically updated on a
running system.
TheEvolution of Java
• JDK 1.02 (1995)
• JDK 1.1 (1996)
• Java2 SDK v 1.2 (a.k.aJDK 1.2, 1998)
• Java2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
• Java2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications such
as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile devices
such as cell phones.
Typesof JavaPrograms
• Standalone applications (J2SE)
– AWT (Abstract Window Toolkit)and swing are used to
create stand alone application.
• Web applications (JSP)
– Applet, Servlet, jsp, jsf which are used to create web
applications.
• Enterprise applications (J2EE)
– designed for corporate sides such as banking business
systems
• Mobile applications (J2ME)
– Mobile application is developed for run the mobile
phones and tablets.
JavaIDE Tools
• Forte by Sun MicroSystems
• Borland JBuilder
• Microsoft Visual J++
• WebGain Café
• IBM Visual Age for Java
• ECLIPSE
Java™:
The Complete
Reference
UNIT – 1 & Chapter - 2
What you learn in Previous
Class
Today’s Agenda
• OOP Concepts
• First Java
Program
• About main()
Object-Oriented
Programming
• Two Paradigms
– All computer programs consist of two elements: code
and data.
• Furthermore, a program can be conceptually
organized around its code or around its data. That
is, some programs are written around “what is
happening” and others are written around “who
is being affected.”
• These are the two paradigms that govern how a
program is constructed.
Object-Oriented
Programming
• process-oriented model
– The process-oriented model can be thought of as code
acting on data.
– C employ this model.
• object-oriented programming
– Object-oriented programming organizes a program
around its data (that is, objects) and a set of well-
defined interfaces to that data.
– An object-oriented program can be characterized as
data controllingaccess to code.
Abstraction
• An essential element of object-oriented
programming is abstraction.
• Humans manage complexity through abstraction.
• Example, people do not think of a car as a set of
tens of thousands of individual parts. Instead,
they are free to utilize the object as a whole.
• A powerful way to manage abstraction is through
the use of hierarchical classifications.
• This allows you to layer the semantics of complex
systems, breaking them into more manageable
pieces.
Abstracti
on
• Hierarchical abstractions of complex systems can also be
applied to computerprograms.
• The data from a traditional process-orientedprogram can
be transformed by abstraction into its component objects.
• A sequence of process steps can become a collection of
messages between these objects.Thus, each of these
objects describes its own unique behavior.
• You can treat these objects as concrete entities that
respond to messages telling them to do something.
• This is the essence of object-oriented programming.
• Object-oriented programming is a powerful and natural
paradigm for creating programs that survive the inevitable
changes accompanying the life cycle of any major software
project, including conception, growth, and aging.
The Three OOP Principles
1. Encapsulation
2. Inheritance
3. Polymorphism
Encapsulation
• Encapsulation is the mechanism that binds
together code and the data itmanipulates, and
keeps both safe from outside interference and
misuse.
• One way to think about encapsulation is as a
protective wrapper that prevents the code and
data from being arbitrarily accessed by other code
defined outside the wrapper.
• To relate this to the real world, You can’t affect the
transmission by using the turn signal or windshield
wipers, for example.
Encapsulation
• In Java, the basis of encapsulation is the class.
• A class defines the structure and behavior (data
and code) that will be shared by a set of objects.
• Each object of a given class contains the structure
and behavior defined by the class, as if it were
stamped out by a mold in the shape of the class.
• For this reason, objects are sometimes referred to
as instances of a class.
• Thus, a class is a logical construct; an object has
physical reality.
Encapsulation
• When you create a class, you will specify the code
and data that constitute that class. Collectively,
these elements are called members of the class.
• Specifically, the data defined by the class are
referred to as member variables or instance
variables. The code that operates on that data is
referred to as member methods or just methods.
• Since the purpose of a class is to encapsulate
complexity, there are mechanisms for hiding the
complexity of the implementation inside the class.
• Each method or variable in a class may be marked
private or public.
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
class
{
//memberdata
int x;
int y;
//membermethod
public void getxy()
{
//code
}
public void putxy()
{
//code
}
}
FIGURE 2-1 Encapsulation: public methods can be used to
protect private data
Inheritan
ce
• Inheritance is the process by which one object
acquires the properties of another object. This is
important because it supports the concept of
hierarchical classification.
• Inheritance, an object need only define those
qualities that make it unique within its class. It can
inherit its general attributes from its parent.
• Thus, it is the inheritance mechanism that makes it
possible for one object to be a specific instance of a
more general case.
• A deeply inherited subclass inherits all of the
attributes from each of its ancestors in the class
hierarchy.
Object Oriented concept-JAVA-Module-1-PPT.pptx
FIGURE 2-2 Labrador
inherits the encapsulation
of all its superclasses
Grand Parent
Parent
Child
Object Oriented concept-JAVA-Module-1-PPT.pptx
Inheritance
• Inheritance interacts with encapsulation as well. If
a given class encapsulates some attributes, then
any subclass will have the same attributes plus any
that it adds as part of its specialization.
• This is a key concept that lets object-oriented
programs grow in complexity linearly rather than
geometrically.
• A new subclass inherits all of the attributes of all
of its ancestors. It does not have unpredictable
interactions with the majority of the rest of the
code in the system.
Polymorphi
sm
• Polymorphism (from Greek,meaning “many forms”) is a
feature that allows one interfaceto be used for a general
class of actions.
• Ex:- Consider a stack (which is a last-in, first-out list).
• The concept of polymorphism is often expressed by the
phrase “one interface,multiple methods.”
• This means that it is possible to design a generic interface to
a group of related activities.
• This helps reduce complexity by allowing the same interface
to be used to specify a general class of action.
• It is the compiler’sjob to select the specific action (that is,
method) as it applies to each situation. You,the
programmer, do not need to make this selection manually.
You need only remember and utilize the general interface.
• Example:a dog’s sense of smell is polymorphic.
Polymorphism,
Encapsulation, and
Inheritance Work Together
• When properly applied, polymorphism, encapsulation,
and inheritance combine to produce a programming
environment that supports the development of far more
robust and scalable programs than does the process-
oriented model.
• A well-designed hierarchy of classes is the basis for
reusing the code in which you have invested time and
effort developing and testing.
• Encapsulation allows you to migrate your
implementations over time without breaking the code
that depends on the public interface of your classes.
• Polymorphism allows you to create clean, sensible,
readable, and resilient code.
Object Oriented concept-JAVA-Module-1-PPT.pptx
A First Simple Program
• Enter the program
and save as
Example.java
• Compile the Program
c:myjavajavac
Example.java
• Run the Program
c:myjavajavac
Example
Comments
• The contents of a comment are ignored by the
compiler. Instead, a comment describes or explains
the operation of the program to anyone who is
reading its source code.
• Java supports three styles of comments.
1. multiline comment (/*
2. single-linecomment (//
3. documentation comment
(/**
*/
) )
*/
)
– This type of comment is used to produce an HTML file
that documents your program.
public static void main(String
args[])
• The public keyword is an access specifier, which allows the
programmer to control the visibility of class members.
• When a class member is preceded by public, then that
member may be accessedby code outside the class in which
it is declared.
• The keyword static allows main( ) to be called
without having to instantiate a particular instance of
the class.
• This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made.
• The keyword void simply tells the compiler that main()
does not return a value.
• In main( ),there is only one parameter,String args[ ]
declares a parameter named args, which is an array of
instances of the class String.
System.out.println();
• println( ) displays the string which is passed to it.
• System is a predefined class that provides access
to the system, and out is the output stream that is
connected to the console.
• All statements in Java end with a semicolon.
• A variable is a named memory location that may
be assigned a value by your program. The value of
a variable may be changed during the execution of
the program.
class Example2 {
public static void main(String args[]) {
int num;
num = 100;
//this declares a variable called num
//this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("Thevalue of num * 2 is ");
System.out.println(num);
}
}
type var-name;
type specifies thetype of variable being declared,
and var-name is the name of the variable.
Using Blocks of Code
• Java allows two or more statements to be grouped
into blocks of code, also called code blocks.
• This is done by enclosing the statements between
opening and closing curly braces.
• Once a block of code has been created, it becomes
a logical unit that can be used any place that a
single statement can.
if(x < y) {
x = y;
y = 0;
}
//begin a block
//end of block
/* Demonstrate a block of code. */
}
Output:
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
class BlockTest {
public static void main(String args[]) {
int x,y;
y = 20;
//the target of this loop is a block
for(x = 0; x<10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
Lexical
Issues
• Java programs are a collection of whitespace,
identifiers, literals, comments, operators, separators,
and keywords.
• Whitespace
– Java is a free-form language. This means that you do not
need to follow any special indentation rules.
– In Java, whitespace is a space, tab,or newline.
• Identifiers
– Identifiers are used for class names, method names, and
variable names.
– An identifier may be any descriptivesequence of uppercase
and lowercase letters, numbers, or the underscore and
dollar-sign characters.
– They must not begin with a number.
– Java is case-sensitive.
Lexical
Issues
• Literals
– A constant value in Javais created by using a literal
representation of it.
• Comments
– Three types of comments defined by Java.
Lexical
Issues
• Separators
– In Java, there are a few characters that are used as
separators.
– The most commonly used separator in Javais the
semicolon.
Lexical
Issues
• The Java Keywords
– There are 50 keywords currently defined in the Java
language
– These keywords cannot be used as names for a variable,
class, or method.
– In addition to the keywords, Java reserves the following:
true, false, and null. These are values defined by
Java.
The Java Class Libraries
• println( ) and print( ),these methods are
members of the System class.
End of today session:
Student can be able
to understand OOP
concepts
Session
Outcome
Java™:
TheComplete Reference
UNIT – 1 & Chapter - 3
JavaIs a Strongly TypedLanguage
• Java is a strongly typed language.
• First, every variable has a type, every expression has
a type, and every type is strictly defined.
• Second, all assignments, whether explicit or via
parameter passing in method calls, are checked for
type compatibility.
• There are no automatic coercions or conversions of
conflicting types as in some languages.
• The Java compiler checks all expressions and
parameters to ensure that the types are compatible.
• Any type mismatches are errors that must be
corrected before the compiler will finish compiling
the class.
Data Typesin Java
• Data types specify the different sizes and values that can be
stored in the variable.
• There are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
• Integers: This group includes byte, short, int, and long,
which are for whole-valued signed numbers.
• Floating-point numbers: This group includes float and
double, which represent numbers with fractional precision.
• Characters :This group includes char,which represents
symbols in a characterset, like letters and numbers.
• Boolean: This group includes boolean, which is a special
type for representing true/false values.
Object Oriented concept-JAVA-Module-1-PPT.pptx
Data
Type
Default
Value
Default
size
Example Range
boolean false 1 bit Boolean
one = false
true and false
char 'u0000' 2 byte char ch =
'A'
'u0000' (or 0) to 'uffff' (or 65,535)
(or) 0 to 65,536
byte 0 1 byte byte a = 10 -128 to 127
Short 0 2 byte short s =
10000
–32,768 to 32,767
int 0 4 byte int a =
100000
–2,147,483,648 to 2,147,483,647
long 0L 8 byte long a =
100000L
–9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 0.0f 4 byte float f1 =
234.5f
1.4e–045 to 3.4e+038
double 0.0d 8 byte double d1
= 12.3
4.9e–324 to 1.8e+308
char uses 2 byte in javaand u0000, javauses Unicode system not ASCII code system.
//Compute the area of a circle.
class Area {
public static void main(String args[]) {
double pi, r,a;
r = 10.8; //radius of circle
pi = 3.1416; //pi, approximately
a = pi * r * r;//compute area
System.out.println("Area of circle is " + a);
}
}
//Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; //code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
output:
ch1 and ch2: X Y
//char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; //increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output:
ch1 contains X
ch1 is now Y
Exercises
• Addition of two numbers.
• Convert Fahrenheit to Celsius.
• Area of circle
• Simple Interest.
int x = 10; int
y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
Integer Literals
• Any whole number value is an integer literal. Examples are
1, 2, 3, and 42. These are all decimal values, meaning they
are describing a base 10 number.
• There are two other bases which can be used in integer
literals, octal (base eight) and hexadecimal (base 16).
• Octal values are denoted in Java by a leading zero. Ex:05
• Normal decimal numbers cannot have a leading zero.
• Hexadecimal constant with a leading zero-x,(0xor 0X). Ex:
0x5
• The range of a hexadecimal digit is 0to 15,so A through F
(or a through f).
• For binary, leading 0b or 0B
• Ex:0b1000001; (‘A’)
public class Test
{
public static void main(String args[])
{
char c = 0b1000001; //Binary
System.out.println(c);
c=0101; //Octal
System.out.println(c);
c=0x41; //Hexadecimal
System.out.println(c);
}
}
Floating-Point Literals
• Floating-point numbers represent decimal values with
a fractional component.
• They can be expressed in either standard or scientific
notation.
• Standard notation consists of a whole number
component followed by a decimal point followed by a
fractional component (ex, 2.0, 3.14159, and 0.6667).
• Scientific notation uses a standard-notation, floating-
point number plus a suffix that specifies a power of 10
by which the number is to be multiplied.
• The exponent is indicatedby an E or e followed by a
decimal number,which can be positive or negative.
• Examples include 6.022E23, 314159E–05,and 2e+100.
Floating-Point Literals
• Floating-point literals in Java default to double
precision.
• Tospecify a float literal, you must append an F or f
to the constant.
• Ex:3.4f
• explicitly specify a double literal by appending a D
or d.
• Ex:2.5d
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Boolean Literals
• Boolean literals are simple.
• There are only two logical values that a boolean
value can have, true and false.
• The values of true and false do not convert into
any numerical representation.
• The true literal in Java does not equal 1, nor does
the false literal equal 0.
Character Literals
• Characters in Java are indices into the Unicode
character set.
• They are 16-bit values that can be converted into
integers and manipulated with the integer
operators, such as the addition and subtraction
operators.
• A literal character is represented inside a pair of
single quotes.
• Ex:‘a’,‘z’
,and ‘@’.
• For characters that are impossible to enter
directly, escape sequences, ‘’’ for the single-quote
character and ‘n’ for the newline character.
Character Literals
• There is also a mechanism for directly entering the
value of a character in octal or hexadecimal.
• For octal notation, use the backslash followed by
the three-digit number.
• For example, ‘141’ is the letter‘a’.
• For hexadecimal, enter a backslash-u (u), then
exactly four hexadecimal digits.
• For example, ‘u0061’ is the ISO-Latin-1 ‘a’
because the top byte is zero. ‘ua432’ is a
Japanese Katakana character.
TABLE 3-1 Character Escape Sequences
public class EscapeExample
{
public static void main(String args[])
{
String str = new String ("My name is 'abcd'");
System.out.println(str);
str = "My Lab is "JAVA LAB"";
System.out.println(str);
str = "My work files are in D:Work Projectsjava";
System.out.println(str);
str = "First Line nSecond Line";
System.out.println(str);
str = "Ravindrabb" + "College";
System.out.println(str);
str = "Ravindra rCollege";
System.out.println(str);
str = "Ravindra fCollege";
System.out.println(str);
}
}
String Literals
• String literals in Java are specified by enclosing a
sequence of characters between a pair of double
quotes.
• One important thing to note about Java strings is
that they must begin and end on the same line.
• There is no line-continuation escape sequence as
there is in some other languages.
• Ex: “Hello World”
“twonlines”
“”This is in quotes”“
Variables
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a
type, and an optional initializer.
• In addition, all variables have a scope, which defines their
visibility, and a lifetime.
Declaring a Variable
• In Java,all variables must be declared before they can be
used.
syntax
type identifier [ = value][, identifier [= value] ...];
• The type is one of Java’satomic types,or the name of a
class or interface.
• The identifier is the name of the variable.
• Initialize the variable by specifying an equal sign and a value
Variables
• Todeclare more than one variable of the specified
type, use a comma separated list.
int a,b, c;
int d = 3, e,f = 5;
byte z= 22;
//declares three ints, a,b, and c.
//declares three more ints, initializing
//d and f.
//initializes z.
double pi = 3.14159; //declares an approximation of pi.
char x = 'x'; //the variable x has the value 'x'.
Dynamic Initialization
• Java allows variables to be initialized dynamically, using
any expression valid at the time the variable is declared.
//Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
//c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
TheScope and Lifetimeof Variables
• A block defines a scope.
• A scope determines what objects are visible to other parts of
your program.
• It also determines the lifetime of those objects.
• In Java, the two major scopes are
– those defined by a class and
– those defined by a method. The scope defined by a method begins
with its opening curly brace.
• As a general rule, variables declared inside a scope are not
visible (that is, accessible) to code that is defined outside that
scope.
• Thus, when you declare a variable within a scope, you are
localizing that variable and protecting it from unauthorized
access and/or modification.
• Scopes can be nested.
• Objects declared within the inner scope will not be visible
outside it.
//Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x;//known to all code within main
x = 10;
if(x == 10) { //start new scope
int y = 20; //known only to this block
//x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
//y = 100; //Error! y not known here
//x is still known here.
System.out.println("x is " + x);
}
}
//Demonstrate lifetime of a variable.
class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; //y is initialized each time block is entered
System.out.println("y is: " + y); //this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
//This program will not compile
class ScopeErr {
public static void main(String args[]) {
int b = 1;
{ //creates a new scope
int b = 2; //Compile-time error – b already defined!
}
}
}
TypeConversion and Casting
• If the two types are compatible, then Javawill perform the
conversion automatically.
• Ex:assign an int value to a long variable
• no automatic conversion defined from double to byte.
• Conversion between incompatible types, use a cast, which
performs an explicit conversion between incompatible
types.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Java’sAutomatic Conversions
• When one type of data is assigned to another type
of variable, an automatic type conversion will take
place if the following two conditions are met:
– The two types are compatible.
– The destination type is larger than the source type.
• Java also performs an automatic type conversion
when storing a literal integer constant into
variables of type byte, short, long, or char.
Object Oriented concept-JAVA-Module-1-PPT.pptx
Casting Incompatible Types
• Tocreate a conversion between two incompatible types,
you must use a cast.
• A cast is simply an explicit type conversion.
Syntax:
(target-type) value
• Assign an int value to a byte variable, byte is smaller than an
int, This kind of conversion is sometimes called a narrowing
conversion
• A different type of conversion will occur when a floating-
point value is assigned to an integer type: truncation.
Object Oriented concept-JAVA-Module-1-PPT.pptx
//Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
OUTPUT:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Automatic TypePromotion in
Expressions
• In an expression, the precision required of an
intermediate value will sometimes exceed the range
of either operand.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b /c;
• The result of the intermediateterm a * b easily
exceeds the range of either of its byte operands. To
handle this kind of problem, Javaautomatically
promotes each byte, short, or char operand to int
when evaluating an expression.
Automatic TypePromotion in
Expressions
byte b = 50;
b = b * 2; //Error! Cannot assign an int to a byte!
• The operands were automatically promoted to int
when the expression was evaluated, the result has
also been promoted to int.
byte b = 50;
b = (byte)(b * 2);
• which yields the correct value of 100.
TheTypePromotion Rules
• Java defines several type promotion rules that
apply to expressions. They are as follows:
• First, all byte, short, and char values are promoted
to int.
• Then, if one operand is a long, the whole
expression is promoted to long.
• If one operand is a float, the entire expression is
promoted to float.
• If any of the operands is double, the result is
double.
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i /c) - (d * s);
System.out.println((f * b) + " + " + (i /c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
OUTPUT:
238.14 + 515 - 126.3616
result = 626.7784146484375
End of today session:
Student can be able to
understand Data type concepts
along with programs
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Session Outcome
Java™:
TheComplete Reference
UNIT – 1 & Chapter - 3
Scanner class
• The Scanner class in Javais used for taking
input from the user.
• The Scanner class can take input of all the
data types.
• Scanner splits the input after every
whitespace.
• This class is present in java.util.Scanner
package.
Scanner class
• There are two constructors of the Scanner class
that are used. One is the InputStream object and
other takes a FileReader object.
• Syntax:
Scanner in = new Scanner(System.in); //InputStream
Scanner inFile = new Scanner(new FileReader(“File_Object”));
• If file is not found “FileNotFoundException” is
thrown.
Scanner class Methods
• public String nextLine() :-Moves the scanner to the next
line and returns the skipped input.
• public String next() :- Returns the token before delimiter
• public byte nextByte() :-Scans next token as byte value
• public short nextShort() :-Scans next token as short value
• public int nextInt() :- Scans next token as integer value
• public long nextLong() :-Scans next token as long value
• public float nextFloat():- Scans next token as float value
• public double nextDouble() :- Scans next token as double
value
• void close:- Scanner is closed
Arrays
• An array is a group of like-typed variables that are
referred to by a common name.
• Arrays of any type can be created and may have one
or more dimensions.
• A specific element in an array is accessed by its index.
• Arrays offer a convenient means of grouping related
information.
• If you are familiar with C/C++, be careful.Arrays in
Java work differentlythan they do in those languages.
• Normally, an array is a collection of similar type of
elements which have a contiguous memory location.
One-Dimensional Arrays
• A one-dimensional array is, essentially, a list
of like-typed variables.
type var-name[ ]; (or)
dataType[] arr; (or)
dataType []arr;
• Here, type declares the base type of the
array
int month_days[];
myarray = new int[10];
One-Dimensional Arrays
int month_days[];
• This declaration establishes the fact that
month_days is an array variable, no array actually
exists. In fact, the value of month_days is set to
null, which represents an array with no value.
• To link month_days with an actual, physical array
of integers, you must allocate one using new and
assign it to month_days.
• new is a special operator that allocates memory.
array-var = new type[size];
month_days = new int[12];
int month_days[];
month_days = new int[12];
• After this statement executes, month_days will
refer to an array of 12 integers.
• Further, all elements in the array will be initialized
to zero.
• Obtaining an array is a two-step process.
– First, you must declare a variable of the desired array
type.
– Second, you must allocate the memory that will hold
the array,using new, and assign it to the array variable.
• Thus, in Java all arrays are dynamically allocated.
• Once you have allocated an array, you can access a
specific element in the array by specifying its index
within square brackets.
• All array indexes start at zero.
month_days[1] = 28;
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the of array
System.out.println(a[i]);
}
}
• Arrays can be initialized when they are declared.
• The process is much the same as that used to
initialize the simple types.
• An array initializer is a list of comma-separated
expressions surrounded by curly braces. The
commas separate the values of the array
elements.
• The array will automatically be created large
enough to hold the number of elements you
specify in the array initializer.
• There is no need to use new.
int a[]={1,2,3,4,5};
For-each Loop for Java
Array
• We can also print the Java array using for-each
loop.
• The Java for-each loop prints the array elements
one by one.
• It holds an array element in a variable, then
executes the body of the loop.
for(data_type variable :array){
//body of the loop
public class PrintArray {
public static void main(String [] args){
String[] array = { "hi", "hello", "java"};
for(String str :array) {
System.out.println(str);
}
}
}
//Print month name along with no of days
class MonthArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
String month_names[] = {"Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
for(int i=0;i<12;i++)
{
System.out.println(month_names[i] + " is having " + month_days[i] + " days.");
}
}
}
Home Task
• Print array elements
• Print array elements in reverse order
• Print odd elements
• Merge two arrays into third array
• Copy even elements to even array and odd
elements to odd array from the original array.
• Sort array elements
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of
arrays.
• Todeclare a multidimensional array variable, specify
each additional index using another set of square
brackets.
int twoD[][] = new int[4][5];
• This allocatesa 4 by 5 array and assigns it to twoD.
Syntax:
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
//Demonstrate a two-dimensional array.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i,j,k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Object Oriented concept-JAVA-Module-1-PPT.pptx
Jagged Array in Java
• Creating odd number of columns in a 2D array, it
is known as a jagged array.
• In other words, it is an array of arrays with
different number of columns.
//Manually allocate differing size second dimensions.
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i,j,k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
This program generates the following output:
0
1 2
3 4 5
6 7 8 9
• It is possible to initialize multidimensional arrays.
Todo so, simply enclose each dimension’s
initializer within its own set of curly braces.
int arr[][]={
{1,2,3},
{2,4,5},
{4,4,5}
};
class Testarray3{
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
2 4 5
4 4 5
//Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i,j,k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j* k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
output:
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 1 2 3 4
0 2 4 6 8
0 3 6 9 12
0 0 0 0 0
0 2 4 6 8
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax
• There is a second form used to declare an array:
type[ ] var-name;
int a1[] = new int[3];
int[] a2 = new int[3];
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
int[] nums, nums2, nums3; //create three arrays
String
• Java’s string type, called String, is not a simple type.
Nor is it simply an array of characters. Rather, String
defines an object.
• The String type is used to declare string variables.
• Also declare arrays of strings.
• A quoted string constant can be assigned to a String
variable.
• A variable of type String can be assigned to another
variable of type String.
String str = "this is a test";
System.out.println(str);
class StrDemo {
public static void main(String args[]) {
String str1 = new String();
str1 = "Hello World";
System.out.println(str1);
String str2 = "Bye Bye";
System.out.println(str1+str2);
}
}
Pointers
• Javadoes not support or allow pointers.
• Java cannot allow pointers, because doing so would
allow Java programs to breach the firewall between
the Java execution environment and the host
computer.
• (Remember, a pointer can be given any address in
memory—even addresses that might be outside the
Javarun-time system.)
• Javais designed in such a way that as long as you stay
within the confines of the execution environment, you
will never need to use a pointer, nor would there be
any benefit in using one.
End of today session:
Students can be able to
implement programs.
Session Outcome
Java™:
TheComplete Reference
UNIT – 1 & Chapter - 4
What you learn in Previous
Class
Today’s Agenda
• Operators: Arithmetic Operators, The Bitwise
Operators, Relational Operators, Boolean Logic
operators, The assignment operator, The ?
Operator, Operator Precedence, Using
Parentheses.
Operators
• Java provides a rich operator environment. Most
of its operators can be divided into the following
four groups:
– arithmetic,
– bitwise,
– relational, and
– logical.
• Java also defines some additional operators that
handle certain special situations.
Arithmetic Operators
The operands of the
arithmetic operators
must be of a numeric
type.
You cannot use
them on boolean types,
but you can use them
on char types, since the
char type in Java is,
essentially, a subset of
int.
//Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
//arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b /4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
//arithmetic using doubles
System.out.println("nFloating Point
Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db /4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
• The Modulus Operator (%)
• Arithmetic Compound Assignment Operators (+=)
• Increment and Decrement (++, --)
public class IncOp
{
public static void main(String args[])
{
int x=1;
int r = --x + x++ + ++x + x--;
System.out.println(x + " " + r);
}
}
//Guess the output
public class Test {
public static void main(String[] args)
{
int a = 10;
int b = ++(++a);
System.out.println(b);
}
}
//final variable
public class Test {
public static void main(String[] args)
{
final int a = 10;
int b = ++a;
System.out.println(b);
}
}
//Can not be applied boolean data type
public class Test {
public static void main(String[] args)
{
boolean b = false;
b++;
System.out.println(b);
}
}
TheBitwise Operators
• Java defines several bitwise operators that can be applied to
the integer types, long, int,short, char,and byte.
• These operators act upon the individual bits of their
operands.
TheBitwise Operators
• The byte value for 42 in binary is 00101010, where
each position represents a power of two, starting with
20 at the rightmostbit.
• All of the integer types (except char) are signed
integers. This means that they can represent negative
values as well as positive ones.
• Javauses an encoding known as two’s complement,
which means that negative numbers are represented
by inverting (changing 1’s to 0’s and vice versa) all of
the bits in a value, then adding 1 to the result.
• Example, –42 is represented by inverting all of the bits
in 42, or 00101010, which yields 11010101, then
adding 1, which results in 11010110, or –42.
Object Oriented concept-JAVA-Module-1-PPT.pptx
Bitwise OR (|) –
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values,
i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise OR Operation of 5 and 7
0101
| 0111
0111 = 7 (In decimal)
Bitwise AND (&) –
This operator is binary operator, denoted by ‘&’.It returns bit by bit AND of input values, i.e,
if both bits are 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise AND Operation of 5 and 7
0101
& 0111
0101 = 5 (In decimal)
Bitwise XOR (^) –
This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input
values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
Bitwise XOR Operation of 5 and 7
0101
^ 0111
0010 = 2 (In decimal)
Bitwise Complement (~) –
This operator is unary operator, denoted by ‘~’. It returns the one’s compliment
representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1,
and every 1 to 0.
For example,
a = 5 = 0101 (In Binary)
Bitwise Compliment Operation of 5
~ 0101
1010 = 10 (In decimal)
public class Bitoperators {
public static void main(String[] args) {
int a = 5;
int b = 7;
//bitwise and
System.out.println("a&b = " + (a & b));
//bitwise or
System.out.println("a|b = " + (a | b));
//bitwise xor
System.out.println("a^b = " + (a ^ b));
//bitwise not ~0101=1010
//will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a);
//assignment a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output :
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Shift Operators
• These operators are used to shift the bits of a
number left or right thereby multiplying or
dividing the number by two respectively.
• They can be used when we have to multiply or
divide a number by two.
• Syntax
number shift_op number_of_shift;
• Signed Right shift operator (>>)
• Unsigned Right shift operator (>>>)
• Left shift operator (<<)
log2base2
• Visit log2base2 site for animations
public class Shiftoperators {
public static void main(String[] args)
{
int a = 5;
int b = -10;
//left shift operator
//0000 0101<<2 =0001 0100
//similar to 5*(2^2)
(20)
System.out.println("a<<2 = " + (a << 2));
//right shift operator
//0000 0101 >> 2 =0000 0001
//similar to 5/(2^2)
(1)
System.out.println("b>>2 = " + (b >> 2));
//unsigned right shift operator
System.out.println("b>>>2 = " + (b >>> 2));
}
}
Output :
a<<2 = 20
b>>2 = -3
b>>>2 = 1073741821
Relational Operators
The outcome of these operations is a boolean value.
Boolean Logical Operators
Short-Circuit Logical Operators
• Java provides two interesting Boolean operators,
These are secondary versions of the Boolean AND and
OR operators, and are known as short-circuitlogical
operators.
• The OR operator results in true when A is true, no
matter what B is. Similarly, the AND operator results
in false when A is false, no matter what B is.
• If you use the || and && forms, rather than the | and
& forms of these operators, Java will not bother to
evaluate the right-hand operand when the outcome
of the expression can be determined by the left
operand alone.
• This is very useful when the right-hand operand
depends on the value of the left one in order to
function properly.
Short-Circuit Logical Operators
• if (denom != 0 && num /denom > 10)
• Since the short-circuit form of AND (&&) is used,
there is no risk of causing a run-time exception
when denom is zero.
• If this line of code were written using the single &
version of AND, both sides would be evaluated,
causing a run-time exception when denom is zero.
import java.io.*;
import java.util.Scanner;
public class AndopEx
{
public static void main(String[] args)
{
int x,y;
int sum=0;
Scanner sobj = new Scanner(System.in);
System.out.println("Enter x & y vals: ")
x = sobj.nextInt();
y = sobj.nextInt();
;
if(x>0 && ++y>0)
sum = x+y;
System.out.println("x=" + x + " and y=" + y + "nx+y=" + sum);
}
}
TheAssignment Operator
var = expression;
int x,y,z;
x = y = z= 100; //set x,y,and zto 100
• This fragment sets the variables x,y,and zto 100
using a single statement.
• This works because the = is an operator that yields
the value of the right-hand expression.
• Thus, the value of z= 100 is 100, which is then
assigned to y,which in turn is assigned to x.
• Using a “chain of assignment” is an easy way to set
a group of variables to a common value.
The? Operator
• Java includes a special ternary (three-way)
operator that can replace certain types of if-then-
else statements. This operator is the ?.
expression1 ? expression2 :expression3
• Here, expression1 can be any expression that
evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise,
expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both
expression2 and expression3 are required to return
the same type, which can’t be void.
k = i < 0 ? -i :i; //get absolute value of i
public class TernaryEx
{
public static void main(String[] args)
{
int A = 10;
int B = 20;
String result = A> B ? "A is greater" : "B is greater";
System.out.println(result);
}
}
For three variables:
String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest“;
Operator Precedence
Object Oriented concept-JAVA-Module-1-PPT.pptx
Object Oriented concept-JAVA-Module-1-PPT.pptx
End of today session:
Student can be able to apply
operators in java programs
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Session Outcome
Java™:
The Complete
Reference
UNIT – 1 & Chapter - 5
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Previous
Class
Today’s Agenda
• Java
conditions
• enum
Java’s Selection
Statements
• if
• if-else
• if-else-if ladder
• nested if
• switch
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
• Java’s program control statements can be put into
the following categories:
– Selection
• Selection statements allow your program to choose
different paths of execution based upon the outcome of an
expression or the state of a variable.
– Iteration
• Iteration statements enable program execution to repeat
one or more statements (that is, iteration statements form
loops).
– jump
• Jump statements allow your program to execute in a
nonlinear fashion.
Control Statements
• The if Statement : The
Java if statement tests the
condition.
• It executes the ifblock if
condition is true.
if(condition) {
//statement;
}
if(num < 100)
//JavaProgram to demonstrate the use of if statement.
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print(“Eligible for voting");
}
}
}
if - else
• The Java if-else statement also tests the condition.
• It executes the ifblock if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
//Itis a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}
else{
System.out.println("odd number");
}
}
}
//A year is leap, if it is divisible by 4 and 400. But, not by 100.
public class LeapYearEx {
public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year %
400==0))
{
System.out.println("LEAPYEAR");
}
else
{
System.out.println("COMMON YEAR");
}
}
}
if-else-if ladder
• The if-else-if ladder statement executes one
condition from multiple statements.
Syntax:
if(condition1){
//codeto be executed if condition1 is true
}else if(condition2){
//codeto be executed if condition2 is true
}
else if(condition3){
//codeto be executed if condition3 is true
}
...
else{
//codeto be executed if all the conditions are false
}
//Itis a program of grading system for fail, D grade, Cgrade, B grade, A grade and A+.
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<35){
System.out.println("fail");
}
else if(marks>=35 &&
marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 &&
marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
//Find out given no is +ve or –ve
or zero
public class PositiveNegativeExample
{
public static void main(String[] args)
{
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
Nested if
• The nested if statement represents
the ifblock within another ifblock.
• Here, the inner if block condition
executes only when outer if block
condition is true.
Syntax:
if(condition)
{
//codeto be executed
if(condition){
//codeto be executed
}
//JavaProgram to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample {
public static void main(String[] args) {
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
else{
System.out.println("You are not eligible to donate blood");
}
}
else{
System.out.println("Age must be greater than 18");
}
}
}
Switch
Statement
• The Java switch statement executes one statement from multiple
conditions.
• It is like if-else-if ladder statement.
• The switch statement works with byte, short, int, long, enum
types, String and some wrapper types like Byte, Short, Int, and
Long.
• There can be one or N number of case values for a switch
expression.
• The case value must be of switch expression type only. The case
value must be literal or constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it
renders compile-time error.
• Each case statement can have a break statement which is
optional. When control reaches to the break statement, it jumps
the control after the switch expression. If a break statement is
not found, it executes the next case.
• The case value can have a default label which is optional.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases
are not matched;
}
public class SwitchExample {
public static void main(String[] args) {
int number=2;
//Switchexpression
switch(number){
//Case statements
case 1: System.out.println(“ONE");
break;
case 2: System.out.println(“TWO");
break;
case 3: System.out.println(“THREE");
break;
//Default case statement
default:System.out.println("Not in 1, 2 or
3");
}
}
//Name of the month
public class SwitchMonthExample {
public static void main(String[]
args) {
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month){
//casestatements within the switch block
case 1: monthString="1 -
January";
break;
case 2: monthString="2 -
February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 -
November";
break;
case 12: monthString="12 -
December";
break;
default:System.out.println("Invalid
Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}
switch w/o break
• It executes all statements after the first match, if a
break statement is not present.
//without break statement
public class SwitchExample2 {
public static void main(String[] args) {
int num=2;
//switch expression with int value
switch(num){
//switch cases without break statements
case 1: System.out.println(“1");
case 2: System.out.println(“2");
case 3: System.out.println(“3");
default:System.out.println("Not in 1, 2 or
3");
}
}
}
Output:
2
3
Not in 1, 2 or 3
//In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12; i++)
switch(i) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
OUTPUT:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
Nested Switch Statement
• We can use switch statement inside other switch
statement in Java.
• It is known as nested switch statement.
switch(expressio
n1){ case
value1:
//code to be
executed; break;
case value2:
switch(expression2){
case value21:
//code to be executed;
break;
//option
al case value22:
break;
//option
al default:
default code to be executed
}
break;
Example: -
You are searching for a department in a university and you’re asked to select a
school from a choice of three schools namely:
1.School of Arts
2.School of Business
3.School of Engineering
Having selected a school you are again provided with a list of departments that fall
under the department namely:
1.School of Arts
A.Department of finearts
B.Department of sketcharts
2.School of Business
A.Department of Commerce
B.Department of purchasing
3.School of Engineering
A.CSE
B.ECE
The initial choices for Computer Science, Business and Engineering schools would
be inside as a set of switch statements. Then various departments would then be
listed within inner switch statements beneath their respective schools.
import java.io.*;
import java.util.Scanner;
class NestedExample
{
public static void main(String args[])
{
int a,b;
System.out.println("1.School of Artsn");
System.out.println("2.School of Businessn");
System.out.println("3.School of Engineeringn");
System.out.println("make your selectionn");
Scanner sobj = new Scanner(System.in);
a=sobj.nextInt();
switch (a)
{
case 1:
System.out.println("You chose Artsn" );
case 2:
break;
System.out.println("You chose Businessn" );
case 3:
//Engineering
break;
System.out.println("You chose Engineeringn" );
System.out.println("1.CSEn" );
System.out.println("2.ECEn" );
System.out.println("make your selectionn");
b=sobj.nextInt();
switch(b)
{
case 1:
System.out.println("You chose CSEn" );
break;
case 2:
System.out.println("You chose ECE" );
break;
}
break;
}
}
}
enum in Switch Statement
• Javaallows us to use enum in switch statement.
• An enum is a special "class" that represents a group
of constants (unchangeable variables, like final
variables).
• Tocreate an enum, use the enum keyword (instead of
class or interface),and separate the constants with a
comma.
• Note that they should be in uppercase letters:
enum Level {
LOW, MEDIUM, HIGH
}
You can access enumconstants with the dot syntax:
Level myVar = Level.MEDIUM;
enum in Switch Statement
public class JavaSwitchEnumExample {
public enum Day { Sun, Mon, Tue,Wed, Thu,Fri,
Sat }
public static void main(String
args[])
{
Day[] DayNow = Day.values();
for (Day Now :DayNow)
{
switch (Now)
{
case Sun:
System.out.println("Sunday");
break;
case Mon:
System.out.println("Monday");
break;
case Tue:
System.out.println("Tuesday");
break;
case Wed:
System.out.println("Wednesday");
break;
case Thu:
System.out.println("Thursday");
break;
case Fri:
System.out.println("Friday");
break;
case Sat:
System.out.println("Saturday");
break;
}
}
}
}
Output:
Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday
End of today session:
Student can be able to
write programs using java
conditions
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Session Outcome
Java™:
TheComplete Reference
UNIT – 1 & Chapter - 5
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Previous Class
Today’s Agenda
• JavaLoops
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Iteration Statements
• Java’s iteration statements are for, while, and
do-while.
• These statements are called loops.
• A loop repeatedly executes the same set of
instructions until a termination condition is
met.
while
• The while loop is Java’s most fundamental loop
statement. It repeats a statement or block while its
controlling expression is true.
while(condition) {
//body of loop
}
• The condition can be any Boolean expression. The
body of the loop will be executed as long as the
conditional expression is true.
• When condition becomes false, control passes to the
next line of code immediately following the loop.
• The curly braces are unnecessary if only a single
statement is being repeated.
//Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println(n);
n--;
}
}
}
//The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j= 200;
//find midpoint between i and j
while(++i < --j);//no body in this loop
System.out.println("Midpoint is " + i);
}
}
do-while
• The do-while loop always executes its body at
least once, because its conditional expression is at
the bottom of the loop. Its general form is
do {
//body of loop
} while (condition);
• 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
terminates.
//Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println(n);
n--;
} while(n > 0);
}
} do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. forn");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.in.read( ) is used to
read characters from standard
input.
for
• There are two forms of the for loop.
• The first is the traditional form of Java.
for(initialization; condition; iteration) {
//body
}
• The second is the new “for-each” form. The for-
each loop is essentially read-only.
for(type itr-var :collection) {
statement-block
}
for Loop Variations
for(int a=1, b=4; a<b; a++, b--)
{
}
for(int i=1; !done; i++)
{
}
//Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ;!done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}
//infinite loop
for( ;;) {
//...
}
//Use a for-each style for loop.
class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 };
int sum = 0;
//use for-each style for to display and sum the values
for(int x:nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
//Use for-each style for on a two-dimensional array.
class ForEach3 {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[3][5];
//give nums some values
for(int i = 0; i < 3;i++)
for(int j=0; j< 5; j++)
nums[i][j] = (i+1)*(j+1);
//use for-each for to display and sum the values
for(int x[] :nums) {
for(int y :x) {
System.out.println("Value is: " + y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
//Search an array using for-each style for.
class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
//use for-each style for to search nums for val
for(int x :nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
Nested Loops
• Java allows loops to be nested. That is, one loop
may be inside another.
//Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
• Try all types of printing pyramid programs.
JumpStatements
• Java supports three jump statements: break,
continue, and return.
• These statements transfer control to another part
of your program.
• Java supports one other way that you can change
your program’s flow of execution: through
exception handling. Exception handling provides a
structured method by which run-time errors can
be trapped and handled by your program. It is
supported by the keywords try, catch, throw,
throws, and finally.
Using break
• In Java,the break statement has three uses.
• First,it terminates a statement sequence in a switch
statement.
• Second, it can be used to exit a loop.
• Third, it can be used as a “civilized” form of goto.
break label;
//Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; //terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
//Using break as a civilized form of goto.
class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t)
break second; //break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
OUTPUT
Before the break.
This is after second block.
//This program contains an error.
class BreakErr {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
}
for(int j=0; j<100; j++) {
if(j== 10) break one; //WRONG
System.out.print(j + " ");
}
}
}
Since the loop labeled one does not enclose the break statement, it
is not possible to transfer control out of that block.
Using continue
• Sometimes it is useful to force an early iteration of a
loop. That is, you might want to continue running the
loop but stop processing the remainder of the code in
its body for this particular iteration.
• In while and do-while loops, a 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 then to the conditional
expression.
• For all three loops, any intermediate code is bypassed.
• As with the break statement, continue may specify a
label to describe which enclosing loop to continue.
//Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j> i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
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.
• The return statement immediately terminates
the method in which it is executed.
//Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t)
return; //return to caller
System.out.println("This won't execute.");
}
}
End of today session:
Student can be able to write
programs using java loops
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Session Outcome
Java™:
The Complete
Reference
UNIT – 1 & Chapter - 6
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Previous Class
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Syllabi
• Introducing Classes: Class Fundamentals,
Declaring Objects, Assuming Object reference
Variables, Introducing Methods, Constructors, The
this Keyword, Garbage Collection, The Finalize()
method, A Stack class.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Class Fundamentals
• A class, defines a new data type.
• Once defined, this new type can be used to
create objects of that type.
• Thus, a class is a template for an object, and an
object is an instance of a class.
• Because an object is an instance of a class, the
two words object and instance used
interchangeably.
The General Form of a
Class
• A class is declared by use of the class keyword.
• Classes may contain only code or only data, most real-world
classes contain both.
class classname {
type instance-variable1;
type instance-variable2;
//...
type instance-variableN;
type methodname1(parameter-list) {
//body of method
}
type methodname2(parameter-list) {
//body of method
}
//...
type methodnameN(parameter-list) {
//body of method
}
}
The General Form of a
Class
• The data, or variables, defined within a class are
called instance variables.
• The code is contained within methods.
• Collectively, the methods and variables defined
within a class are called members of the class.
• Variables defined within a class are called
instance variables because each instance of the
class (that is, each object of the class) contains its
own copy of these variables. Thus, the data for
one object is separate and unique from the data
for another.
A Simple
Class
• a class declaration only creates a template;
class Box {
double width;
double height;
double depth;
}
Box mybox = new Box(); //create a Box object called mybox
mybox will be an instance of Box. Thus, it will have “physical” reality.
Toaccess class variables, use the dot (.) operator.
The dot operator links the name of the object with the name of an instance
variable.
mybox.width = 100;
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
/* 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);
}
}
Declaring
Objects
• Obtaining objects of a class is a two-step process.
• First,you must declare a variable of the class type. This
variable does not define an object. Instead, it is simply a
variable that can refer to an object.
Box mybox; //declare reference to object
• Second, you must acquire an actual, physical copy of the
object and assign it to that variable. You can do this using
the new operator.
mybox = new Box();//allocatea Box object
• The new operator dynamically allocates(that is, allocates at
run time) memory for an object and returns a reference to
it. This reference is, more or less, the address in memory of
the object allocated by new.
• This reference is then stored in the variable.
Object Oriented concept-JAVA-Module-1-PPT.pptx
A Closer Look at
new
• the new operator dynamically allocates memory for
an object.
class-var = new classname( );
• class-var is a variable of the class type being created.
• The classname is the name of the class that is being
instantiated.
• The class name followed by parentheses specifies the
constructor for the class.
• A constructor defines what occurs when an object of
a class is created.
• If no explicit constructor is specified, then Java will
automaticallysupply a default constructor.
• A class is a logical construct. An object has physical
reality.
Assigning Object Reference
Variables
• Object reference variables act differently when an
assignment takes place.
Box b1 = new Box();
Box b2 = b1;
Box b1 = new Box();
Box b2 = b1;
//...
b1 = null;
Here, b1 has been set to null, but b2 still points to the
original object.
When you assign one object referencevariable to another object referencevariable, you are
Introducing
Methods
type name(parameter-list) {
//body of method
return value;
}
• type specifies the type of data returned by the method. This can
be any valid type, including class types that you create. If the
method does not return a value, its return type must be void.
• The name of the method is specified by name. This can be any
legal identifier other than those already used by other items
within the current scope.
• The parameter-list is a sequence of type and identifier pairs
separated by commas. Parameters are essentially variables that
receive the value of the arguments passed to the method when it
is called. If the method has no parameters, then the parameter
list will be empty.
• value is the value returned.
Adding method
• Method With parameters
• Method Without Parameters
• Method Return a value
• The type of data returned by a method must be
compatible with the return type specified by the
method.
• The variable receiving the value returned by a
method must also be compatible with the
return type specified for the method.
Example
Constructors
• Automatic initializationof an object is performed
through the use of a constructor.
• A constructor initializes an object immediately upon
creation.
• It has the same name as the class in which it resides
and is syntactically similar to a method.
• Once defined, the constructor is automatically called
immediatelyafter the object is created, before the
new operator completes.
• Constructors have no return type, not even void.
This is because the implicit return type of a class
constructor is the class type itself.
• The constructor’s job to initializethe internal state of
an object.
Construct
ors
• Constructors are
1. Automatic Constructors
2. Default Constructors
Box mybox1 = new Box();
The default constructor automatically initializes all
instance variables to zero.
3. Parameterized Constructors
Box mybox1 = new Box(10, 20, 15);
4.Copy Constructors
class Box {
double width;
double height;
double depth;
//This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
//compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
//declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
//get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
//get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
OUTPUT:
Volume is 3000.0
Volume is 162.0
1. Default Constructors
class Box {
double width;
double height;
double depth;
//This is the constructor for Box.
Box(double w
, double h, double d) {
width = w;
height = h;
depth = d;
}
//compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
//declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
//get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
//get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
OUTPUT:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Parameterized Constructors
The this Keyword
• Sometimes a method will need to refer to the
object that invoked it.
• Toallow this, Java defines the this keyword.
• this can be used inside any method to refer to the
current object. That is, this is always a reference to
the object on which the method was invoked.
Box(double w
, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
• Usage of java this keyword
1. this can be used to refer current class instance
variable.
2. this can be used to invoke current class method
(implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor
call.
6. this can be used to return the current class instance
from the method.
class Abc {
int val;
Abc() {
System.out.println("Default Constructor Called");
}
Abc(int x)
{
this();
val=x;
System.out.println("Param Constructor " + this.val);
}
}
class ThisEx {
public static void main(String args[]){
Abc obj=new Abc(10);
}
}
Instance Variable Hiding
• It is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.
• Local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables.
• However, when a local variable has the same name as an
instance variable, the local variable hides the instance
variable.
• this, resolve any name space collisions that might occur
between instance variables and local variables.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
• Since objects are dynamically allocated by using the new
operator, how such objects are destroyed and their
memory released for later reallocation?
• In some languages, such as C++, dynamically allocated
objects must be manually released by use of a delete
operator.
• Javatakes a different approach; it handles deallocation
automatically. The technique that accomplishes this is
called garbage collection.
• When no references to an object exist, that object is
assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
Garbage Collection
• There is no explicit need to destroy objects.
• Garbage collection only occurs sporadically (if at all)
during the execution of your program.
• It will not occur simply because one or more objects exist
that are no longer used. Furthermore, different Java run-
time implementations will take varying approaches to
garbage collection.
• Do not to think about it while writing your programs.
System.gc
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
The finalize( )
Method
• Sometimes an object will need to perform some action
when it is destroyed.
• For example, if an object is holding some non-Java
resource such as a file handle or character font, then you
might want to make sure these resources are freed before
an object is destroyed.
• Tohandle such situations, Java provides a mechanism
called finalization.
• By using finalization, you can define specific actions that
will occur when an object is just about to be reclaimed by
the garbage collector.
• Toadd a finalizer to a class, you simply define the
finalize()
protected void finalize( )
{
//finalization code here
}
• The keyword protected is a specifier that prevents access
to finalize( ) by code defined outside its class.
• finalize( ) is only called just prior to garbage collection.
• It is not called when an object goes out-of-scope.
A Stack
Class
• A stack stores data using first-in, last-out ordering.
• That is, a stack is like a stack of plates on a table—
the first plate put down on the table is the last
plate to be used.
• Stacks are controlled through two operations
traditionally called push and pop.
• Toput an item on top of the stack, you willuse
push. Totake an item off the stack, you will use
pop.
• As you will see, it is easy to encapsulate the entire
stack mechanism.
//This class defines an integer stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;
//Initialize top-of-stack
Stack() {
tos = -1;
}
//Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
//Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
//push some numbers onto the stack
for(int i=0; i<10; i++)
mystack1.push(i);
for(int i=10; i<20; i++)
mystack2.push(i);
//pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
OUTPUT
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
Java™:
TheCompleteReference
UNIT – 1 & Chapter - 7
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Previous Class
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Syllabus
• Overloading Methods, Using Object as Parameter,
Argument Passing, Returning Objects, Recursion,
Introducing Access control,
Overloading Methods
• In Javait is possible to define two or more methods within
the same class that share the same name, as long as their
parameter declarations are different.
• When this is the case, the methods are said to be
overloaded, and the process is referred to as method
overloading.
• Method overloading is one of the ways that Javasupports
polymorphism.
• When an overloaded method is invoked, Javauses the type
and/or number of arguments as its guide to determine
which version of the overloaded method to actually call.
• Thus, overloaded methods must differ in the type and/or
number of their parameters.
• While overloaded methods may have different return types,
the return type alone is insufficient to distinguish two
versions of a method.
Method Overloading
• Method Overloading is a feature that allows a class to have more than
one method having the same name, if their argument lists are different.
• It is similar to constructor overloading in Java,that allows a class to have
more than one constructor having different argument lists.
• Threeways to overload a method
1.Number of parameters.
add(int, int)
add(int, int, int)
2.Data type of parameters.
add(int, int)
add(int, float)
3.Sequence of Data type of parameters.
add(int, float)
add(float, int)
• Invalid case of method overloading:
int add(int, int)
float add(int, int)
//Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
//Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
//Overload test for two integer parameters.
void test(int a,int b) {
System.out.println("a and b: " + a + " " + b);
}
//overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
//call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): "
+ result);
}
}
//Automatic type conversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
//Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
//overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); //this will invoke test(double)
ob.test(123.2); //this will invoke test(double)
}
}
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Overloading Constructors
• Also overload constructor methods.
//Constructor Overloading
class Box {
double width;
double height;
double depth;
Box(double w,double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1; //use -1 to indicate
height = -1; //an uninitialized
depth = -1; //box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
//create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
//get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
//get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
//get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
OUTPUT
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
Using Objects as Parameters
//Objects may be passed to methods.
class Test {
int a,b;
Test(int i,int j){
a = i;
b = j;
}
//return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a== a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100,22);
Testob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
OUTPUT
ob1 == ob2: true
ob1 == ob3: false
class Box {
double width;
double height;
double depth;
//Notice this constructor. It takes an object of type Box.
Box(Box ob) { //pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}
//constructor used when all dimensions specified
Box(double w,double h, double d) {
width = w;
height = h;
depth = d;
}
//constructor used when no dimensions specified
Box() {
width = -1; //use -1 to indicate
height = -1; //an uninitialized
depth = -1; //box
}
//constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
//compute and return volume
double volume() {
return width * height * depth;
}
}
class OverloadCons2 {
public static void main(String args[]) {
//create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); //create copy of mybox1
double vol;
//get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
//get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
//get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
//get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
Argument Passing
• there are two ways that a computer language can
pass an argument to a subroutine.
– call-by-value
– call-by-reference
• Java uses both approaches, depending upon what is
passed.
• In Java, when you pass a primitive type to a method,
it is passed by value.
• When you pass an object to a method, it is call-by-
reference.
• When a primitive type is passed to a method, it is
done by use of call-by-value. Objects are implicitly
passed by use of call-by-reference.
//Objects are passed by reference.
class Test{
int a,b;
Test(inti,int j){
a = i;
b = j;
}
//pass an object
void meth(Test o) {
a. *= 2;
b. /=2;
}
}
class CallByRef {
public static void main(String args[]) {
Testob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
OUTPUT
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Returning Objects
• A method can return any type of data,
including class types.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
//Returning an object.
class Test{
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Testtemp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
Testob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}
}
OUTPUT
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Recursion
• Java supports recursion.
• Recursion is the process of defining something in
terms of itself.
• Recursion is the attribute that allows a method to
call itself.
• A method that calls itself is said to be recursive.
//A simple example of recursion.
class Factorial {
//this is a recursive method
int fact(int n) {
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
OUTPUT
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Examples
Given following three values, the task is to find the total number of maximum
chocolates you can eat.
money :Money you have to buy chocolates
price :Price of a chocolate
wrap :Number of wrappers to be returned for getting one extra chocolate.
It may be assumed that all given values are positive integers and greater than 1.
Examples:
Input :money = 16, price = 2, wrap = 2
Output :15
Price of a chocolate is 2.You can buy 8chocolates from amount 16. You can return
8 wrappers back and get 4 more chocolates. Then you can return 4 wrappers
and get 2 more chocolates. Finally you can return 2 wrappers to get 1 more
chocolate. Input :money = 15, price = 1, wrap = 3 Output :22 We buy and eat
15 chocolates We return 15 wrappers and get 5 more chocolates. We return 3
wrappers, get 1 chocolate and eat it (keep 2 wrappers). Now we have 3
wrappers. Return 3 and get 1 more chocolate. So total chocolates = 15 + 5 + 1 +
1
Input :money = 20, price = 3, wrap = 5
Output :7
import java.io.*;
class ChocolateWrapper {
static int countRec(int choc, int wrap)
{
if (choc < wrap)
return 0;
int newChoc = choc /wrap;
return newChoc + countRec(newChoc + choc%wrap, wrap);
}
public static void main (String[] args)
{
int money = 16;
int price = 2;
int wrap = 2;
if(money>=1 && price>=1 && wrap>=1)
{
int totchoc = money/price;
totchoc += countRec(totchoc, wrap);
System.out.println(totchoc);
}
}
}
Access Control
• How a member can be accessed is determined by the
access specifier that modifies its declaration.
• Java supplies a rich set of access specifiers.
• Java’s access specifiers are public, private, and
protected. Java also defines a default access level.
• protected applies only when inheritance is involved.
• public specifier, that member can be accessed by any
other code.
• private, then that member can only be accessed by
other members of its class.
• default, the member of a class is public within its own
package, but cannot be accessed outside of its
package.
class Test {
int a;
public int b;
private int c;
//default access
//public access
//private access
//methods to access c
//set c's value
void setc(int i) {
c= i;
}
int getc() {
return c;
}
}
class AccessTest {
//get c's value
public static void main(String args[]) {
Testob = new Test();
ob.a = 10; //These are OK, a and b may be accessed directly
ob.b = 20;
//This is not OK and will cause an error
//ob.c = 100; //Error!
//You must access c through its methods
ob.setc(100); //OK
System.out.println("a,b, and c: " + ob.a + " " +ob.b + " " + ob.getc());
}
}
//This class defines an integer stack that can hold 10 values.
class Stack {
/* Now, both stck and tos are private. This means that they cannot be accidentallyor maliciously
altered in a way that would be harmful to the stack. */
private int stck[] = new int[10];
private int tos;
//Initialize top-of-stack
Stack() {
tos = -1;
}
//Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
//Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
//push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
//pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
//these statements are not legal
//mystack1.tos = -2;
//mystack2.stck[3] = 100;
}
}
Java™:
TheCompleteReference
UNIT – 1 & Chapter - 7
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Previous Class
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Syllabus
• Understanding static, Introducing Nested and
Inner classes, Exploring the String class, Using
Command line Arguments, Varargs:
variableLength Arguments.
static
• When a member is declared static, it can be accessed
before any objects of its class are created, and without
reference to any object.
• You can declare both methods and variables to be
static.
• Example of a static member is main( ).main( ) is
declared as static because it must be called before any
objects exist.
• Instance variables declared as static are, essentially,
global variables.
• When objects of its class are declared, no copy of a
static variable is made. Instead, all instances of the
class share the same static variable.
• The static keyword in Java is used for memory
management mainly.
• We can apply static keyword with variables,
methods, blocks and nested classes.
• The static keyword belongs to the class than an
instance of the class.
• The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
static variable
• If you declare any variable as static, it is known as a static
variable.
• The static variable can be used to refer to the common property
of all objects, for example, the company name of employees,
college name of students, etc.
• The static variable gets memory only once in the class area at the
time of class loading.
• Advantages of static variable: makes your program memory
efficient .
class Student{
int rollno;
String name;
String college=“RCEW";
}
class Student{
int rollno;
String name;
static String college ="RCEW“;
}
class Student{
int rollno;
String name;
static String college =“RCEW";
//constructor
Student(int r,String n){
rollno = r;
name = n;
}
//method to display the values
void display (){
//instance variable
//static variable
System.out.println(rollno+" "+name+" "+college);
}
}
public class TestStaticVariable1{
public staticvoid main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//wecan change the college of all objects by the single line of code
//Student.college=“GPCET";
s1.display();
s2.display();
}
}
College=RCEW
class Counter2{
staticint count=0; //willget memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[]){
//creating objects
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Output:
1
2
3
Static Method
• A static method belongs to the class rather than the object of a
class.
• A static method can be invoked without the need for creating an
instance of a class.
• A static method can access static data member and can change
the value of it.
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
• The static method cannot use non static data member or call
non-static method directly.
• Outside of the class in which they are defined, static methods
and variables can be used independently of any object. Todo so,
you need only specify the name of their class followed by the dot
operator.
classname.method( )
class Student{
int rollno;
String name;
static String college = "RCEW";
//staticmethod to change the value of static variable
static void change(){
college = “GPCET";
}
//constructor to initialize the variable
Student(int r,String n){
rollno = r;
name = n;
}
//method to display values
void display(){
System.out.println(rollno+" "+name+" "+college);
}
}
publicclass TestStaticMethod{
public static void main(String args[]){
Student.change();
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = newStudent(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111Karan
GPCET
222Aryan
GPCET
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
OUTPUT
a = 42
b = 99
Why is the Java main method static?
• It is because the object is not required to call a
static method.
• If it were a non-static method, JVM creates an
object first then call main() method that will
lead the problem of extra memory allocation.
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Object Oriented concept-JAVA-Module-1-PPT.pptx
static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of
classloading.
class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
//Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
OUTPUT
Static block initialized.
x= 42
a = 3
b = 12
all of the static statements are run. First, a is set to 3, then the static block executes, which
prints a message and then initializes b to a * 4 or 12. Then main( ) is called, which calls
meth(), passing 42 to x.The three println( ) statements refer to the two static variables a and
b, as well as to the local variable x.
Can we execute a program without main()
method?
• No,
• one of the ways was the static block, but it was possible till
JDK 1.6.
• Since JDK 1.7, it is not possible to execute a Javaclass
without the main method.
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:
staticblockisinvoked
Nested Classes
• Java programming language allows us to create a
class within a class.
• The nested class architecture is divided into two:
1. nested classes that are declared static are
called static nested classes
2. nested classes that are non-static are called inner
classes
• The main difference between these two is that the
inner classes have access to all member of the
enclosing class (including private), whereas
the static nested classes only have access to static
members of the outer class.
//Demonstrate an inner class.
class Outer
{
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display();
}
//this is an inner class
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}
OUTPUT
display: outer_x = 100
//Demonstrate nested class.
class TestOuter
{
static int data=30;
static class Inner
{
void msg(){
System.out.println("data is "+data);
}
}
public static void main(String args[]){
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}
OUTPUT
data is 30
final
• The final keyword in javais used to restrict the
user.
• The javafinal keyword can be used in many
context.
1. variable
2. method
3. class
final variable
• A variable can be declared as final.
• Doing so prevents its contents from being modified.
• This means that you must initialize a final variable when it is declared.
• It is a common coding convention to choose all uppercase identifiers for final
variables.
• Variables declared as final do not occupy memory on a per-instance basis.
• Thus, a final variable is essentially a constant.
• A field that is both static and final has only one piece of storage that cannot be
changed.
• The keyword final can also be applied to methods, and classes.
• A final variable that is not initialized at the time of declaration is known as blank
final variable. We can initialize using constructors only.
• A static final variable that is not initialized at the time of declaration is known as
static blank final variable. It can be initialized only in static block.
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
final variable
• If you declare any
parameter as final, you
cannot change the
value of it.
class Bike11{
int cube(final int n){
n=n+2; //can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
Can we declare a constructor final?
No, because constructor is never inherited.
class finalvar{
final int x=90;
void run(){
x=400;
}
//final variable
public static void main(String args[])
{
finalvar obj=newfinalvar();
obj.run();
}
}//end of class
Output: Compile Time Error
final method
• If you make any method as final, you cannot override it.
• Is final method inherited? Yes, final method is inherited but you cannot
override it.
class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
final class
• If you make any class as final, you cannot extend it.
final class Bike{
void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
String Class
• The first thing, strings are actually an object of type String.
• Even string constants are actually String objects. Example
System.out.println("This is a String, too");
• objects of type String are immutable; once a String object is
created, its contents cannot be altered.
– If you need to change a string, you can always create a new one
that contains the modifications.
– Java defines a peer class of String, called StringBuffer, which
allows strings to be altered.
• + is used to concatenate two strings.
• Testtwo strings for equality by using equals( ).
• length of a string by calling the length( ) method.
• character at a specified index within a string by calling
charAt( ).
//Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
} OUTPUT
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
command line arguments
• Sometimes you will want to pass information into a
program when you run it.This is accomplished by
passing command-line arguments to main( ).
• A command-line argument is the information that
directly follows the program’s name on the command
line when it is executed.
• Toaccess the command-line arguments inside a Java
program, they are stored as strings in a String array
passed to the args parameter of main( ).
• The first command-line argument is stored at args[0],
the second at args[1], and so on.
• All command-line arguments are passed as strings.
command line arguments
public class CommandLine
{
public static void main(String args[])
{
for(int i = 0; i<args.length; i++)
{
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
d:/mahesh>javac CommandLine.java
d:/mahesh>javaCommandLine this is a command line 200 -100 Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
Varargs: Variable-Length Arguments
• JDK 5, Java has included a feature that simplifies the creation
of methods that need to take a variable number of
arguments. This feature is called varargs and it is short for
variable-length arguments.
• A method that takes a variable number of arguments is
called a variable-arity method, or simply a varargs method.
example is the printf( )
• Prior to JDK 5, variable-length arguments could be handled
two ways,
– if the maximum number of arguments was small and known,
then you could create overloaded versions of the method, one
for each way the method could be called.
– In cases where the maximum number of potential arguments
was larger, or unknowable, a second approach was used in which
the arguments were put into an array, and then the array was
passed to the method.
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length + " Contents: ");
for(int x :v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
//Notice how an array must be created to hold the arguments.
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { };
vaTest(n1); //1 arg
vaTest(n2); //3 args
vaTest(n3); //no args
}
}
OUTPUT
Number of args: 1 Contents: 10
Number of args: 3 Contents: 1 2 3
Number of args: 0 Contents:
it is tedious to construct an array each
time vaTest( ) is called, it is potentially
error-prone.
varags
• A variable-length argument is specified by three
periods (...).
• For example, here is how vaTest( ) is written using a
vararg:
static void vaTest(int ...v) {
}
• This syntax tells the compiler that vaTest( ) can be
called with zero or more arguments.
• As a result, v is implicitly declared as an array of type
int[ ].Thus, inside vaTest( ),v is accessed using the
normal array syntax.
• The ...syntax simply tells the compiler that a variable
number of arguments will be used.
//Demonstrate variable-length arguments.
class VarArgs {
//vaTest() now uses a vararg.
static void vaTest(int ...v) {
System.out.print("Number of args: " + v.length + " Contents: ");
for(int x :v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
//Notice how vaTest() can be called with a variable number of arguments.
}
vaTest(10);
vaTest(1, 2, 3);
vaTest();
//1 arg
//3 args
//no args
}
• Valid statement
int doIt(int a,int b, double c,int ...vals) {}
• declare a regular parameter after the varargs parameter is invalid.
int doIt(int a, int b, double c,int ...vals, boolean stopFlag) { //Error!
• declare the second varargs parameter is illegal.
int doIt(int a, int b, double c,int ...vals, double ...morevals) { //Error!
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Overloading Vararg Methods
• You can overload a method that takes a variable-
length argument.
//Varargs and overloading.
class VarArgs3 {
static void vaTest(int ...v) {
System.out.print("vaTest(int ...):" +"Number of args: " + v.length +" Contents: ");
for(int x :v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(boolean ...v) {
System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: ");
for(boolean x :v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(String msg, int ...v) {
System.out.print("vaTest(String, int ...): " +msg + v.length +" Contents: ");
for(int x :v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}
OUTPUT
vaTest(int ...):Number of args: 3 Contents: 1 2 3
vaTest(String, int ...):Testing: 2 Contents: 10 20
vaTest(boolean ...)Number of args: 3 Contents: true false false
RCEW, Pasupula (V), Nandikotkur Road,
Near Venkayapalli, KURNOOL
Varargs and Ambiguity
• Somewhat unexpected errors can result when
overloading a method that takes a variable-length
argument.
• These errors involve ambiguity because it is
possible to create an ambiguous call to an
overloaded varargs method.
//Varargs, overloading, and ambiguity.
//This program contains an error and will not compile!
class VarArgs4 {
static void vaTest(int ...v) {
System.out.print("vaTest(int ...):" +"Number of args: " + v.length +" Contents: ");
for(int x :v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(boolean ...v) {
System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: ");
for(boolean x :v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(1, 2, 3); //OK
vaTest(true, false, false); //OK
vaTest(); //Error: Ambiguous!
}
}
static void vaTest(int ...v) { //...
static void vaTest(int n, int ...v) { //...
Although the parameter lists of vaTest( ) differ, there is no way for the
compiler to resolve the following call:
vaTest(1)
Does this translate into a call to vaTest(int ...),with one varargs
argument, or into a call to vaTest(int, int ...)with no varargs
arguments?
There is no way for the compiler to answer this question. Thus, the
situation is ambiguous.
Because of ambiguity errors like those just shown, sometimes you will
need to forego overloading and simply use two different method
names.
Also, in some cases, ambiguity errors expose a conceptual flaw in your
code, which you can remedy by more carefully crafting a solution.

More Related Content

What's hot (20)

PPTX
Linker and Loader
sonalikharade3
 
PDF
CS2303 theory of computation Toc answer key november december 2014
appasami
 
PPTX
History of Linux.pptx
rikritiKoirala1
 
ODP
Description of GRUB 2
iamumr
 
PDF
Chapter 2 - Types of Computer Networks.pdf
ssuser3acfba
 
PPTX
Method overloading
Lovely Professional University
 
PPTX
JAVA FEATURES
shalinikarunakaran1
 
PPTX
Time_Complexity.pptx
vivekcommon
 
PPTX
Chapter 3
Vishnu Palanisamy
 
PDF
System programming note
SANTOSH RATH
 
PDF
Introduction to basics of java
vinay arora
 
PPTX
Multithreading in java
Monika Mishra
 
PPT
Software tools
ravindravekariya
 
PPT
Debugging
Indu Sharma Bhardwaj
 
PPT
Static white box testing lecture 12
Abdul Basit
 
PDF
Java thread life cycle
Archana Gopinath
 
PPT
Core java concepts
Ram132
 
PDF
Programacion en java
Sam Paredes Chaves
 
PPSX
ISOC (internet society)
Himasha Shalini Perera
 
Linker and Loader
sonalikharade3
 
CS2303 theory of computation Toc answer key november december 2014
appasami
 
History of Linux.pptx
rikritiKoirala1
 
Description of GRUB 2
iamumr
 
Chapter 2 - Types of Computer Networks.pdf
ssuser3acfba
 
Method overloading
Lovely Professional University
 
JAVA FEATURES
shalinikarunakaran1
 
Time_Complexity.pptx
vivekcommon
 
Chapter 3
Vishnu Palanisamy
 
System programming note
SANTOSH RATH
 
Introduction to basics of java
vinay arora
 
Multithreading in java
Monika Mishra
 
Software tools
ravindravekariya
 
Static white box testing lecture 12
Abdul Basit
 
Java thread life cycle
Archana Gopinath
 
Core java concepts
Ram132
 
Programacion en java
Sam Paredes Chaves
 
ISOC (internet society)
Himasha Shalini Perera
 

Similar to Object Oriented concept-JAVA-Module-1-PPT.pptx (20)

PPTX
Lec 1-of-oop2
SM Rasel
 
PPTX
1 java introduction
abdullah al mahamud rosi
 
PPTX
1 java intro
abdullah al mahamud rosi
 
PPTX
java basics concepts and the keywords needed
PriyadharshiniG41
 
PPT
Introduction to Core Java feature and its characteristics
rashmishekhar81
 
PPTX
Java Introduction
sunmitraeducation
 
PPTX
Introduction to java
Krunali Gandhi
 
PPTX
1.Intro--Why Java.pptx
YounasKhan542109
 
PPTX
basic core java up to operator
kamal kotecha
 
PPTX
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
PPTX
1. Java Project Guidance for engineering
vyshukodumuri
 
PPSX
Introduction to Java
Hitesh-Java
 
PPT
Java ppt-class_Introduction_class_Objects.ppt
VGaneshKarthikeyan
 
PPTX
Introduction to java
Java Lover
 
PPT
2-Lec - History of OOP and Java (1) .ppt
AqeelAbbas94
 
PPTX
unit1.pptx
PrasadKalal4
 
PDF
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
10322210023
 
PPTX
Introduction to Java Part-2
RatnaJava
 
DOCX
java full 1.docx
SATHYAKALAKSKPRCASBS
 
DOCX
java full.docx
SATHYAKALAKSKPRCASBS
 
Lec 1-of-oop2
SM Rasel
 
1 java introduction
abdullah al mahamud rosi
 
java basics concepts and the keywords needed
PriyadharshiniG41
 
Introduction to Core Java feature and its characteristics
rashmishekhar81
 
Java Introduction
sunmitraeducation
 
Introduction to java
Krunali Gandhi
 
1.Intro--Why Java.pptx
YounasKhan542109
 
basic core java up to operator
kamal kotecha
 
MODULE_1_The History and Evolution of Java.pptx
VeerannaKotagi1
 
1. Java Project Guidance for engineering
vyshukodumuri
 
Introduction to Java
Hitesh-Java
 
Java ppt-class_Introduction_class_Objects.ppt
VGaneshKarthikeyan
 
Introduction to java
Java Lover
 
2-Lec - History of OOP and Java (1) .ppt
AqeelAbbas94
 
unit1.pptx
PrasadKalal4
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
10322210023
 
Introduction to Java Part-2
RatnaJava
 
java full 1.docx
SATHYAKALAKSKPRCASBS
 
java full.docx
SATHYAKALAKSKPRCASBS
 
Ad

Recently uploaded (20)

PDF
community health nursing question paper 2.pdf
Prince kumar
 
PDF
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
PPSX
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
PDF
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PDF
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
community health nursing question paper 2.pdf
Prince kumar
 
People & Earth's Ecosystem -Lesson 2: People & Population
marvinnbustamante1
 
Health Planning in india - Unit 03 - CHN 2 - GNM 3RD YEAR.ppsx
Priyanshu Anand
 
Zoology (Animal Physiology) practical Manual
raviralanaresh2
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Isharyanti-2025-Cross Language Communication in Indonesian Language
Neny Isharyanti
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
CEREBRAL PALSY: NURSING MANAGEMENT .pdf
PRADEEP ABOTHU
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Ad

Object Oriented concept-JAVA-Module-1-PPT.pptx

  • 2. Syllabus • TheHistory and Evolution of Java:Java’s Lineage, The Creation of java, how java changed the internet, Java’s magic: The byte code, Servlets: java on the server side, java Buzzwords, Evolution of java. • An Overview of Java: Object Oriented Programming, Two control statements, Using blocks of codes, Lexical issues, The java class Libraries. • Data Types, Arrays and Variables: Primitive Types, Integers, Floating-point Types, Characters, Booleans, literals, variables, Type conversion and casting, Automatic Type Promotion in Expressions, Arrays, strings, Pointers.
  • 3. Java’sLineage • Java is related to C++, which is a direct descendant of C. • Much of the character of Java is inherited from these two languages. • From C,Java derives its syntax. • Many of Java’s object-oriented features were influenced by C++.
  • 4. The Birth of Modern Programming: C • The C language shook the computer world. • When a computer language is designed, trade-offs are often made, such as the following: – Ease-of-use versus power – Safety versus efficiency – Rigidity versus extensibility • Invented and first implemented by Dennis Ritchie on a DEC PDP- 11 running the UNIX operating system, C was the result of a development process that started with an older language called BCPL, developed by Martin Richards. • BCPL influenced a language called B, invented by Ken Thompson, which led to the development of C in the 1970s. • C was formally standardized in December 1989, when the American National Standards Institute (ANSI) standard for C was adopted. • C is a language designed by and for programmers.
  • 5. C++:TheNext Step • C is a successful and useful language,you might ask why a need for something else existed. The answer is complexity. • Tosolve this problem, a new way to program was invented, called object-oriented programming (OOP). • C++ was invented by Bjarne Stroustrup in 1979, while he was working at Bell Laboratories in Murray Hill, New Jersey. • Stroustrup initiallycalled the new language “Cwith Classes.” • However, in 1983, the name was changed to C++. C++ extends C by adding object-oriented features.
  • 6. TheStage Is Set for Java • By the end of the 1980s and the early 1990s, object-oriented programming using C++ took hold. • Within a few years, the World Wide Web and the Internet would reach critical mass. • This event would precipitate another revolution in programming.
  • 7. TheCreation 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 first working version. This language was initially called “Oak,”but was renamed “Java”in 1995. • Primary motivation was the need for a platform- 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 controls. • The problem is that compilers are expensive and time-consuming to create. • Solution, a portable, platform-independent language
  • 8. TheCreation of Java • The second force was, of course, the World Wide Web. • The emergence of the World Wide Web, Javawas propelled to the forefront of computer language design, because the Web, too, demanded portable programs. • The Internet ultimately led to Java’s large-scale success. • Java is simply the “Internet version of C++.” • Javawas to Internet programming what C was to system programming: a revolutionary force that changed the world.
  • 9. TheC#Connection • C#. Created by Microsoft to support the .NET Framework. • C# is closely related to Java. • For example, both share the same general syntax, support distributed programming, and utilize the same object model.
  • 10. How JavaChanged the Internet • 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 thorniest issues associated with the Internet: portability and security.
  • 11. JavaApplets • An applet is a special kind of Java program that is designed to be transmitted over the Internet and automaticallyexecutedby a Java-compatible web browser. • Applets are intended to be small programs. • They are typically used to display data provided by the server, handle user input, or provide simple functions, such as a loan calculator, that execute locally,rather than on the server. • In essence, the applet allows some functionality to be moved from the server to the client. • The creation of the applet changed Internet programming because it expanded the universe of objects that can move about freely in cyberspace.
  • 12. JavaApplets • Two very broad categories of objects that are transmitted between the server and the client: • passive information and – e-mail, you are viewing passive data. • dynamic, active programs. – the applet is a dynamic, self-executingprogram. • As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. • Obviously, a program that downloads and executes automatically on the client computer must be prevented from doing harm. • It must also be able to run in a variety of different environments and under different operating systems. • As you will see, Java solved these problems in an effective and elegant way.
  • 13. Security • Every time you download a “normal” program, a risk, because the code you are downloading might contain a virus, Trojanhorse, or other harmful code. • For example, a virus program might gather private information, such as credit card numbers, bank account balances, and passwords, by searching the contents of your computer’s local file system. • Java enabled applets, to be downloaded and executed on the client computer safely. • Java achieved this protection by confining an applet to the Java execution environment and not allowing it access to other parts of the computer. • The ability to download applets with confidence that no harm will be done and that no security will be breached is considered by many to be the single most innovative aspect of Java.
  • 14. 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 Javaprogram were to be run on virtually any computer connectedto the Internet, there needed to be some way to enable that program to execute on different systems. • For example, applet must be able to be downloaded and executed by the wide variety of CPUs, operating systems, and browsers connectedto the Internet. • It is not practical to have different versions of the applet for different computers. • The same code must work on all computers. Therefore, some means of generating portable executable code was needed.
  • 15. Java’sMagic: The Bytecode • The key that allows Java to solve both the security and the portability, the output of a Java compiler is not executable code. Rather, it is bytecode. • Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). • In essence, the original JVM was designed as an interpreter for bytecode.
  • 16. Java’sMagic: The Bytecode • Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform. • Once the run-time package exists for a given system, any Javaprogram can run on it. • Remember, although the details of the JVM will differ from platform to platform, all understand the same Java bytecode. • The execution of bytecode by the JVM is the easiest way to create truly portable programs. • The Javaprogram is executed by the JVM helps to make it secure. Because the JVM is in control, it can contain the program and prevent it from generating side effects outside of the system.
  • 17. Java’sMagic: The Bytecode • In general, when a program is compiled to an intermediate form and then interpreted by a virtual machine, it runs slower than it would run if compiled to executable code. • However, with Java,the differential between the two is not so great. • Because bytecode has been highly optimized, the use of bytecode enables the JVM to execute programs much faster than you might expect. • Java was designed as an interpretedlanguage, there is nothing about Java that prevents on-the-fly compilation of bytecode into native code in order to boost performance. • Sun began supplying its HotSpot technology.
  • 18. HotSpot • HotSpot provides a Just-In-Time (JIT)compiler for bytecode. • When a JITcompiler is part of the JVM, selected portions of bytecode are compiled into executable code in real time, on a piece-by-piece, demand basis. • It is important to understand that it is not practical to compile an entire Java program into executable code all at once, because Java performs various run-time checks that can be done only at run time. Instead, a JITcompiler compiles code as it is needed, during execution. • Furthermore, not all sequences of bytecode are compiled—only those that will benefit from compilation. The remaining code is simply interpreted. • However, the just-in-time approach still yields a significant performance boost. • Even when dynamic compilation is applied to bytecode, the portability and safety features still apply, because the JVM is still in charge of the execution environment.
  • 19. Servlets: Javaon the Server Side • As useful as applets can be, they are just one half of the client/server equation. • At Serverside, servlet. • A servlet is a small program that executeson the server.Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the functionality of a web server. • Thus, with the advent of the servlet, Javaspanned both sides of the client/server connection. • Servlets are used to create dynamically generated content that is then served to the client. For example, an online store might use a servlet to look up the price for an item in a database. • Dynamically generated content is availablethrough mechanisms such as CGI (Common Gateway Interface). • Because servlets (like all Javaprograms) are compiled into bytecode and executedby the JVM, they are highly portable.Thus, the same servlet can be used in a variety of different server environments. The only requirementsare that the server support the JVM and a servlet container.
  • 20. JVM • A Virtual Machine is a software implementation of a physical machine. Java was developed with the concept of WORA (WriteOnce Run Anywhere), which runs on a VM. • The compiler compiles the Java file into a Java .class file, then that .class file is input into the JVM, which loads and executes the class file.
  • 21. myprog.c myprog.exe OS/Hardware machine code C source code gcc Platform Dependent JVM myprog.class bytecode Java source code myprog.java javac OS/Hardware Platform Independent
  • 26. TheJavaBuzzwords • The key considerations were summed up by the Java team in the following list of buzzwords: – Simple – Secure – Portable – Object-oriented – Robust – Multithreaded – Architecture-neutral – Interpreted – High performance – Distributed – Dynamic
  • 27. TheJavaBuzzwords :Simple • Based on popular languages called C and C++ • C:old, pretty bare bones language • C++: newer, more complicated language • Start from C and add some of C++’s more useful features “Java omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefits” (Gosling)
  • 30. TheJavaBuzzwords :ObjectOriented • The object-oriented paradigm – problems and their solutions are packaged in terms of classes – the information in a class is the data – the functionality in a class is the method – a class provides the framework for building objects • Object-oriented programming (OOP) allows pieces of programs to be used in other contexts more easily
  • 31. TheJavaBuzzwords :Robust • program must execute reliably in a variety of systems. • Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. • A robust program may not do exactly what it is supposed to do, but it should not bring down other unrelated programs down with it • Reliability – early (compile time) checking – dynamic (runtime) checking – eliminating situations that are error prone. • Example: Two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions (that is, run-time errors).
  • 32. TheJavaBuzzwords:Multithread • Java supports multithreadedprogramming, which allows you to write programs that do many things simultaneously. • A thread is a part of the program that can operate independently of its other parts • Multi-threaded programs can do multiple things at once – example: • download a file from the web while still looking at other web pages • Question: What is the problem with multiple agents working at the same time? – synchronization
  • 33. TheJavaBuzzwords :Architecture- Neutral • Goal was “write once; run anywhere, any time, forever.” • One of the main problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow—even on the same machine. • Operating system upgrades, processor upgrades, and changes in core system resources can all combine to make a program malfunction.
  • 34. TheJavaBuzzwords :Interpreted and High Performance • Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. This code can be executed on any system that implements the Java Virtual Machine. • Most previous attemptsat cross-platform solutions have done so at the expense of performance. • The Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler (JIT). • Java run-time systems that provide this feature lose none of the benefits of the platform-independent code.
  • 35. TheJavaBuzzwords:Distributed • Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. • In fact, accessing a resource using a URL is not much different from accessing a file. • Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.
  • 36. TheJavaBuzzwords: Dynamic • Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time. • This makes it possible to dynamically link code in a safe and expedient manner. • This is crucial to the robustness of the Java environment, in which small fragments of bytecode may be dynamically updated on a running system.
  • 37. TheEvolution of Java • JDK 1.02 (1995) • JDK 1.1 (1996) • Java2 SDK v 1.2 (a.k.aJDK 1.2, 1998) • Java2 SDK v 1.3 (a.k.a JDK 1.3, 2000) • Java2 SDK v 1.4 (a.k.a JDK 1.4, 2002) • Java Standard Edition (J2SE) – J2SE can be used to develop client-side standalone applications or applets. • Java Enterprise Edition (J2EE) – J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages. • Java Micro Edition (J2ME). – J2ME can be used to develop applications for mobile devices such as cell phones.
  • 38. Typesof JavaPrograms • Standalone applications (J2SE) – AWT (Abstract Window Toolkit)and swing are used to create stand alone application. • Web applications (JSP) – Applet, Servlet, jsp, jsf which are used to create web applications. • Enterprise applications (J2EE) – designed for corporate sides such as banking business systems • Mobile applications (J2ME) – Mobile application is developed for run the mobile phones and tablets.
  • 39. JavaIDE Tools • Forte by Sun MicroSystems • Borland JBuilder • Microsoft Visual J++ • WebGain Café • IBM Visual Age for Java • ECLIPSE
  • 41. What you learn in Previous Class
  • 42. Today’s Agenda • OOP Concepts • First Java Program • About main()
  • 43. Object-Oriented Programming • Two Paradigms – All computer programs consist of two elements: code and data. • Furthermore, a program can be conceptually organized around its code or around its data. That is, some programs are written around “what is happening” and others are written around “who is being affected.” • These are the two paradigms that govern how a program is constructed.
  • 44. Object-Oriented Programming • process-oriented model – The process-oriented model can be thought of as code acting on data. – C employ this model. • object-oriented programming – Object-oriented programming organizes a program around its data (that is, objects) and a set of well- defined interfaces to that data. – An object-oriented program can be characterized as data controllingaccess to code.
  • 45. Abstraction • An essential element of object-oriented programming is abstraction. • Humans manage complexity through abstraction. • Example, people do not think of a car as a set of tens of thousands of individual parts. Instead, they are free to utilize the object as a whole. • A powerful way to manage abstraction is through the use of hierarchical classifications. • This allows you to layer the semantics of complex systems, breaking them into more manageable pieces.
  • 46. Abstracti on • Hierarchical abstractions of complex systems can also be applied to computerprograms. • The data from a traditional process-orientedprogram can be transformed by abstraction into its component objects. • A sequence of process steps can become a collection of messages between these objects.Thus, each of these objects describes its own unique behavior. • You can treat these objects as concrete entities that respond to messages telling them to do something. • This is the essence of object-oriented programming. • Object-oriented programming is a powerful and natural paradigm for creating programs that survive the inevitable changes accompanying the life cycle of any major software project, including conception, growth, and aging.
  • 47. The Three OOP Principles 1. Encapsulation 2. Inheritance 3. Polymorphism
  • 48. Encapsulation • Encapsulation is the mechanism that binds together code and the data itmanipulates, and keeps both safe from outside interference and misuse. • One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. • To relate this to the real world, You can’t affect the transmission by using the turn signal or windshield wipers, for example.
  • 49. Encapsulation • In Java, the basis of encapsulation is the class. • A class defines the structure and behavior (data and code) that will be shared by a set of objects. • Each object of a given class contains the structure and behavior defined by the class, as if it were stamped out by a mold in the shape of the class. • For this reason, objects are sometimes referred to as instances of a class. • Thus, a class is a logical construct; an object has physical reality.
  • 50. Encapsulation • When you create a class, you will specify the code and data that constitute that class. Collectively, these elements are called members of the class. • Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods. • Since the purpose of a class is to encapsulate complexity, there are mechanisms for hiding the complexity of the implementation inside the class. • Each method or variable in a class may be marked private or public.
  • 53. class { //memberdata int x; int y; //membermethod public void getxy() { //code } public void putxy() { //code } }
  • 54. FIGURE 2-1 Encapsulation: public methods can be used to protect private data
  • 55. Inheritan ce • Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. • Inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. • Thus, it is the inheritance mechanism that makes it possible for one object to be a specific instance of a more general case. • A deeply inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.
  • 57. FIGURE 2-2 Labrador inherits the encapsulation of all its superclasses
  • 60. Inheritance • Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes, then any subclass will have the same attributes plus any that it adds as part of its specialization. • This is a key concept that lets object-oriented programs grow in complexity linearly rather than geometrically. • A new subclass inherits all of the attributes of all of its ancestors. It does not have unpredictable interactions with the majority of the rest of the code in the system.
  • 61. Polymorphi sm • Polymorphism (from Greek,meaning “many forms”) is a feature that allows one interfaceto be used for a general class of actions. • Ex:- Consider a stack (which is a last-in, first-out list). • The concept of polymorphism is often expressed by the phrase “one interface,multiple methods.” • This means that it is possible to design a generic interface to a group of related activities. • This helps reduce complexity by allowing the same interface to be used to specify a general class of action. • It is the compiler’sjob to select the specific action (that is, method) as it applies to each situation. You,the programmer, do not need to make this selection manually. You need only remember and utilize the general interface. • Example:a dog’s sense of smell is polymorphic.
  • 62. Polymorphism, Encapsulation, and Inheritance Work Together • When properly applied, polymorphism, encapsulation, and inheritance combine to produce a programming environment that supports the development of far more robust and scalable programs than does the process- oriented model. • A well-designed hierarchy of classes is the basis for reusing the code in which you have invested time and effort developing and testing. • Encapsulation allows you to migrate your implementations over time without breaking the code that depends on the public interface of your classes. • Polymorphism allows you to create clean, sensible, readable, and resilient code.
  • 64. A First Simple Program • Enter the program and save as Example.java • Compile the Program c:myjavajavac Example.java • Run the Program c:myjavajavac Example
  • 65. Comments • The contents of a comment are ignored by the compiler. Instead, a comment describes or explains the operation of the program to anyone who is reading its source code. • Java supports three styles of comments. 1. multiline comment (/* 2. single-linecomment (// 3. documentation comment (/** */ ) ) */ ) – This type of comment is used to produce an HTML file that documents your program.
  • 66. public static void main(String args[]) • The public keyword is an access specifier, which allows the programmer to control the visibility of class members. • When a class member is preceded by public, then that member may be accessedby code outside the class in which it is declared. • The keyword static allows main( ) to be called without having to instantiate a particular instance of the class. • This is necessary since main( ) is called by the Java Virtual Machine before any objects are made. • The keyword void simply tells the compiler that main() does not return a value. • In main( ),there is only one parameter,String args[ ] declares a parameter named args, which is an array of instances of the class String.
  • 67. System.out.println(); • println( ) displays the string which is passed to it. • System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. • All statements in Java end with a semicolon. • A variable is a named memory location that may be assigned a value by your program. The value of a variable may be changed during the execution of the program.
  • 68. class Example2 { public static void main(String args[]) { int num; num = 100; //this declares a variable called num //this assigns num the value 100 System.out.println("This is num: " + num); num = num * 2; System.out.print("Thevalue of num * 2 is "); System.out.println(num); } } type var-name; type specifies thetype of variable being declared, and var-name is the name of the variable.
  • 69. Using Blocks of Code • Java allows two or more statements to be grouped into blocks of code, also called code blocks. • This is done by enclosing the statements between opening and closing curly braces. • Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. if(x < y) { x = y; y = 0; } //begin a block //end of block
  • 70. /* Demonstrate a block of code. */ } Output: This is x: 0 This is y: 20 This is x: 1 This is y: 18 This is x: 2 This is y: 16 class BlockTest { public static void main(String args[]) { int x,y; y = 20; //the target of this loop is a block for(x = 0; x<10; x++) { System.out.println("This is x: " + x); System.out.println("This is y: " + y); y = y - 2; } } This is x: 3 This is y: 14 This is x: 4 This is y: 12 This is x: 5 This is y: 10 This is x: 6 This is y: 8 This is x: 7 This is y: 6 This is x: 8 This is y: 4 This is x: 9 This is y: 2
  • 71. Lexical Issues • Java programs are a collection of whitespace, identifiers, literals, comments, operators, separators, and keywords. • Whitespace – Java is a free-form language. This means that you do not need to follow any special indentation rules. – In Java, whitespace is a space, tab,or newline. • Identifiers – Identifiers are used for class names, method names, and variable names. – An identifier may be any descriptivesequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. – They must not begin with a number. – Java is case-sensitive.
  • 72. Lexical Issues • Literals – A constant value in Javais created by using a literal representation of it. • Comments – Three types of comments defined by Java.
  • 73. Lexical Issues • Separators – In Java, there are a few characters that are used as separators. – The most commonly used separator in Javais the semicolon.
  • 74. Lexical Issues • The Java Keywords – There are 50 keywords currently defined in the Java language – These keywords cannot be used as names for a variable, class, or method. – In addition to the keywords, Java reserves the following: true, false, and null. These are values defined by Java.
  • 75. The Java Class Libraries • println( ) and print( ),these methods are members of the System class.
  • 76. End of today session: Student can be able to understand OOP concepts Session Outcome
  • 78. JavaIs a Strongly TypedLanguage • Java is a strongly typed language. • First, every variable has a type, every expression has a type, and every type is strictly defined. • Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. • There are no automatic coercions or conversions of conflicting types as in some languages. • The Java compiler checks all expressions and parameters to ensure that the types are compatible. • Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.
  • 79. Data Typesin Java • Data types specify the different sizes and values that can be stored in the variable. • There are two types of data types in Java: 1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double. 2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays. • Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers. • Floating-point numbers: This group includes float and double, which represent numbers with fractional precision. • Characters :This group includes char,which represents symbols in a characterset, like letters and numbers. • Boolean: This group includes boolean, which is a special type for representing true/false values.
  • 81. Data Type Default Value Default size Example Range boolean false 1 bit Boolean one = false true and false char 'u0000' 2 byte char ch = 'A' 'u0000' (or 0) to 'uffff' (or 65,535) (or) 0 to 65,536 byte 0 1 byte byte a = 10 -128 to 127 Short 0 2 byte short s = 10000 –32,768 to 32,767 int 0 4 byte int a = 100000 –2,147,483,648 to 2,147,483,647 long 0L 8 byte long a = 100000L –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 0.0f 4 byte float f1 = 234.5f 1.4e–045 to 3.4e+038 double 0.0d 8 byte double d1 = 12.3 4.9e–324 to 1.8e+308 char uses 2 byte in javaand u0000, javauses Unicode system not ASCII code system.
  • 82. //Compute the area of a circle. class Area { public static void main(String args[]) { double pi, r,a; r = 10.8; //radius of circle pi = 3.1416; //pi, approximately a = pi * r * r;//compute area System.out.println("Area of circle is " + a); } } //Demonstrate char data type. class CharDemo { public static void main(String args[]) { char ch1, ch2; ch1 = 88; //code for X ch2 = 'Y'; System.out.print("ch1 and ch2: "); System.out.println(ch1 + " " + ch2); } } output: ch1 and ch2: X Y
  • 83. //char variables behave like integers. class CharDemo2 { public static void main(String args[]) { char ch1; ch1 = 'X'; System.out.println("ch1 contains " + ch1); ch1++; //increment ch1 System.out.println("ch1 is now " + ch1); } } Output: ch1 contains X ch1 is now Y
  • 84. Exercises • Addition of two numbers. • Convert Fahrenheit to Celsius. • Area of circle • Simple Interest. int x = 10; int y = 9; System.out.println(x > y); // returns true, because 10 is higher than 9
  • 85. Integer Literals • Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are describing a base 10 number. • There are two other bases which can be used in integer literals, octal (base eight) and hexadecimal (base 16). • Octal values are denoted in Java by a leading zero. Ex:05 • Normal decimal numbers cannot have a leading zero. • Hexadecimal constant with a leading zero-x,(0xor 0X). Ex: 0x5 • The range of a hexadecimal digit is 0to 15,so A through F (or a through f). • For binary, leading 0b or 0B • Ex:0b1000001; (‘A’)
  • 86. public class Test { public static void main(String args[]) { char c = 0b1000001; //Binary System.out.println(c); c=0101; //Octal System.out.println(c); c=0x41; //Hexadecimal System.out.println(c); } }
  • 87. Floating-Point Literals • Floating-point numbers represent decimal values with a fractional component. • They can be expressed in either standard or scientific notation. • Standard notation consists of a whole number component followed by a decimal point followed by a fractional component (ex, 2.0, 3.14159, and 0.6667). • Scientific notation uses a standard-notation, floating- point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. • The exponent is indicatedby an E or e followed by a decimal number,which can be positive or negative. • Examples include 6.022E23, 314159E–05,and 2e+100.
  • 88. Floating-Point Literals • Floating-point literals in Java default to double precision. • Tospecify a float literal, you must append an F or f to the constant. • Ex:3.4f • explicitly specify a double literal by appending a D or d. • Ex:2.5d
  • 89. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Boolean Literals • Boolean literals are simple. • There are only two logical values that a boolean value can have, true and false. • The values of true and false do not convert into any numerical representation. • The true literal in Java does not equal 1, nor does the false literal equal 0.
  • 90. Character Literals • Characters in Java are indices into the Unicode character set. • They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and subtraction operators. • A literal character is represented inside a pair of single quotes. • Ex:‘a’,‘z’ ,and ‘@’. • For characters that are impossible to enter directly, escape sequences, ‘’’ for the single-quote character and ‘n’ for the newline character.
  • 91. Character Literals • There is also a mechanism for directly entering the value of a character in octal or hexadecimal. • For octal notation, use the backslash followed by the three-digit number. • For example, ‘141’ is the letter‘a’. • For hexadecimal, enter a backslash-u (u), then exactly four hexadecimal digits. • For example, ‘u0061’ is the ISO-Latin-1 ‘a’ because the top byte is zero. ‘ua432’ is a Japanese Katakana character.
  • 92. TABLE 3-1 Character Escape Sequences
  • 93. public class EscapeExample { public static void main(String args[]) { String str = new String ("My name is 'abcd'"); System.out.println(str); str = "My Lab is "JAVA LAB""; System.out.println(str); str = "My work files are in D:Work Projectsjava"; System.out.println(str); str = "First Line nSecond Line"; System.out.println(str); str = "Ravindrabb" + "College"; System.out.println(str); str = "Ravindra rCollege"; System.out.println(str); str = "Ravindra fCollege"; System.out.println(str); } }
  • 94. String Literals • String literals in Java are specified by enclosing a sequence of characters between a pair of double quotes. • One important thing to note about Java strings is that they must begin and end on the same line. • There is no line-continuation escape sequence as there is in some other languages. • Ex: “Hello World” “twonlines” “”This is in quotes”“
  • 95. Variables • The variable is the basic unit of storage in a Java program. • A variable is defined by the combination of an identifier, a type, and an optional initializer. • In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring a Variable • In Java,all variables must be declared before they can be used. syntax type identifier [ = value][, identifier [= value] ...]; • The type is one of Java’satomic types,or the name of a class or interface. • The identifier is the name of the variable. • Initialize the variable by specifying an equal sign and a value
  • 96. Variables • Todeclare more than one variable of the specified type, use a comma separated list. int a,b, c; int d = 3, e,f = 5; byte z= 22; //declares three ints, a,b, and c. //declares three more ints, initializing //d and f. //initializes z. double pi = 3.14159; //declares an approximation of pi. char x = 'x'; //the variable x has the value 'x'.
  • 97. Dynamic Initialization • Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. //Demonstrate dynamic initialization. class DynInit { public static void main(String args[]) { double a = 3.0, b = 4.0; //c is dynamically initialized double c = Math.sqrt(a * a + b * b); System.out.println("Hypotenuse is " + c); } }
  • 98. TheScope and Lifetimeof Variables • A block defines a scope. • A scope determines what objects are visible to other parts of your program. • It also determines the lifetime of those objects. • In Java, the two major scopes are – those defined by a class and – those defined by a method. The scope defined by a method begins with its opening curly brace. • As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. • Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. • Scopes can be nested. • Objects declared within the inner scope will not be visible outside it.
  • 99. //Demonstrate block scope. class Scope { public static void main(String args[]) { int x;//known to all code within main x = 10; if(x == 10) { //start new scope int y = 20; //known only to this block //x and y both known here. System.out.println("x and y: " + x + " " + y); x = y * 2; } //y = 100; //Error! y not known here //x is still known here. System.out.println("x is " + x); } }
  • 100. //Demonstrate lifetime of a variable. class LifeTime { public static void main(String args[]) { int x; for(x = 0; x < 3; x++) { int y = -1; //y is initialized each time block is entered System.out.println("y is: " + y); //this always prints -1 y = 100; System.out.println("y is now: " + y); } } } Output: y is: -1 y is now: 100 y is: -1 y is now: 100 y is: -1 y is now: 100 //This program will not compile class ScopeErr { public static void main(String args[]) { int b = 1; { //creates a new scope int b = 2; //Compile-time error – b already defined! } } }
  • 101. TypeConversion and Casting • If the two types are compatible, then Javawill perform the conversion automatically. • Ex:assign an int value to a long variable • no automatic conversion defined from double to byte. • Conversion between incompatible types, use a cast, which performs an explicit conversion between incompatible types.
  • 102. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Java’sAutomatic Conversions • When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met: – The two types are compatible. – The destination type is larger than the source type. • Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short, long, or char.
  • 104. Casting Incompatible Types • Tocreate a conversion between two incompatible types, you must use a cast. • A cast is simply an explicit type conversion. Syntax: (target-type) value • Assign an int value to a byte variable, byte is smaller than an int, This kind of conversion is sometimes called a narrowing conversion • A different type of conversion will occur when a floating- point value is assigned to an integer type: truncation.
  • 106. //Demonstrate casts. class Conversion { public static void main(String args[]) { byte b; int i = 257; double d = 323.142; System.out.println("nConversion of int to byte."); b = (byte) i; System.out.println("i and b " + i + " " + b); System.out.println("nConversion of double to int."); i = (int) d; System.out.println("d and i " + d + " " + i); System.out.println("nConversion of double to byte."); b = (byte) d; System.out.println("d and b " + d + " " + b); } } OUTPUT: Conversion of int to byte. i and b 257 1 Conversion of double to int. d and i 323.142 323 Conversion of double to byte. d and b 323.142 67
  • 107. Automatic TypePromotion in Expressions • In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand. byte a = 40; byte b = 50; byte c = 100; int d = a * b /c; • The result of the intermediateterm a * b easily exceeds the range of either of its byte operands. To handle this kind of problem, Javaautomatically promotes each byte, short, or char operand to int when evaluating an expression.
  • 108. Automatic TypePromotion in Expressions byte b = 50; b = b * 2; //Error! Cannot assign an int to a byte! • The operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int. byte b = 50; b = (byte)(b * 2); • which yields the correct value of 100.
  • 109. TheTypePromotion Rules • Java defines several type promotion rules that apply to expressions. They are as follows: • First, all byte, short, and char values are promoted to int. • Then, if one operand is a long, the whole expression is promoted to long. • If one operand is a float, the entire expression is promoted to float. • If any of the operands is double, the result is double.
  • 110. class Promote { public static void main(String args[]) { byte b = 42; char c = 'a'; short s = 1024; int i = 50000; float f = 5.67f; double d = .1234; double result = (f * b) + (i /c) - (d * s); System.out.println((f * b) + " + " + (i /c) + " - " + (d * s)); System.out.println("result = " + result); } } OUTPUT: 238.14 + 515 - 126.3616 result = 626.7784146484375
  • 111. End of today session: Student can be able to understand Data type concepts along with programs RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome
  • 113. Scanner class • The Scanner class in Javais used for taking input from the user. • The Scanner class can take input of all the data types. • Scanner splits the input after every whitespace. • This class is present in java.util.Scanner package.
  • 114. Scanner class • There are two constructors of the Scanner class that are used. One is the InputStream object and other takes a FileReader object. • Syntax: Scanner in = new Scanner(System.in); //InputStream Scanner inFile = new Scanner(new FileReader(“File_Object”)); • If file is not found “FileNotFoundException” is thrown.
  • 115. Scanner class Methods • public String nextLine() :-Moves the scanner to the next line and returns the skipped input. • public String next() :- Returns the token before delimiter • public byte nextByte() :-Scans next token as byte value • public short nextShort() :-Scans next token as short value • public int nextInt() :- Scans next token as integer value • public long nextLong() :-Scans next token as long value • public float nextFloat():- Scans next token as float value • public double nextDouble() :- Scans next token as double value • void close:- Scanner is closed
  • 116. Arrays • An array is a group of like-typed variables that are referred to by a common name. • Arrays of any type can be created and may have one or more dimensions. • A specific element in an array is accessed by its index. • Arrays offer a convenient means of grouping related information. • If you are familiar with C/C++, be careful.Arrays in Java work differentlythan they do in those languages. • Normally, an array is a collection of similar type of elements which have a contiguous memory location.
  • 117. One-Dimensional Arrays • A one-dimensional array is, essentially, a list of like-typed variables. type var-name[ ]; (or) dataType[] arr; (or) dataType []arr; • Here, type declares the base type of the array int month_days[];
  • 118. myarray = new int[10];
  • 119. One-Dimensional Arrays int month_days[]; • This declaration establishes the fact that month_days is an array variable, no array actually exists. In fact, the value of month_days is set to null, which represents an array with no value. • To link month_days with an actual, physical array of integers, you must allocate one using new and assign it to month_days. • new is a special operator that allocates memory. array-var = new type[size]; month_days = new int[12];
  • 120. int month_days[]; month_days = new int[12]; • After this statement executes, month_days will refer to an array of 12 integers. • Further, all elements in the array will be initialized to zero. • Obtaining an array is a two-step process. – First, you must declare a variable of the desired array type. – Second, you must allocate the memory that will hold the array,using new, and assign it to the array variable. • Thus, in Java all arrays are dynamically allocated.
  • 121. • Once you have allocated an array, you can access a specific element in the array by specifying its index within square brackets. • All array indexes start at zero. month_days[1] = 28;
  • 122. class Testarray{ public static void main(String args[]){ int a[]=new int[5];//declaration and instantiation a[0]=10;//initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //traversing array for(int i=0;i<a.length;i++)//length is the of array System.out.println(a[i]); } }
  • 123. • Arrays can be initialized when they are declared. • The process is much the same as that used to initialize the simple types. • An array initializer is a list of comma-separated expressions surrounded by curly braces. The commas separate the values of the array elements. • The array will automatically be created large enough to hold the number of elements you specify in the array initializer. • There is no need to use new. int a[]={1,2,3,4,5};
  • 124. For-each Loop for Java Array • We can also print the Java array using for-each loop. • The Java for-each loop prints the array elements one by one. • It holds an array element in a variable, then executes the body of the loop. for(data_type variable :array){ //body of the loop
  • 125. public class PrintArray { public static void main(String [] args){ String[] array = { "hi", "hello", "java"}; for(String str :array) { System.out.println(str); } } }
  • 126. //Print month name along with no of days class MonthArray { public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; String month_names[] = {"Jan", "Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; for(int i=0;i<12;i++) { System.out.println(month_names[i] + " is having " + month_days[i] + " days."); } } }
  • 127. Home Task • Print array elements • Print array elements in reverse order • Print odd elements • Merge two arrays into third array • Copy even elements to even array and odd elements to odd array from the original array. • Sort array elements
  • 128. Multidimensional Arrays • In Java, multidimensional arrays are actually arrays of arrays. • Todeclare a multidimensional array variable, specify each additional index using another set of square brackets. int twoD[][] = new int[4][5]; • This allocatesa 4 by 5 array and assigns it to twoD. Syntax: dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[];
  • 129. //Demonstrate a two-dimensional array. class TwoDArray { public static void main(String args[]) { int twoD[][]= new int[4][5]; int i,j,k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } }
  • 131. Jagged Array in Java • Creating odd number of columns in a 2D array, it is known as a jagged array. • In other words, it is an array of arrays with different number of columns.
  • 132. //Manually allocate differing size second dimensions. class TwoDAgain { public static void main(String args[]) { int twoD[][] = new int[4][]; twoD[0] = new int[1]; twoD[1] = new int[2]; twoD[2] = new int[3]; twoD[3] = new int[4]; int i,j,k = 0; for(i=0; i<4; i++) for(j=0; j<i+1; j++) { twoD[i][j] = k; k++; } for(i=0; i<4; i++) { for(j=0; j<i+1; j++) System.out.print(twoD[i][j] + " "); System.out.println(); } } } This program generates the following output: 0 1 2 3 4 5 6 7 8 9
  • 133. • It is possible to initialize multidimensional arrays. Todo so, simply enclose each dimension’s initializer within its own set of curly braces. int arr[][]={ {1,2,3}, {2,4,5}, {4,4,5} };
  • 134. class Testarray3{ 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 2 4 5 4 4 5
  • 135. //Demonstrate a three-dimensional array. class ThreeDMatrix { public static void main(String args[]) { int threeD[][][] = new int[3][4][5]; int i,j,k; for(i=0; i<3; i++) for(j=0; j<4; j++) for(k=0; k<5; k++) threeD[i][j][k] = i * j* k; for(i=0; i<3; i++) { for(j=0; j<4; j++) { for(k=0; k<5; k++) System.out.print(threeD[i][j][k] + " "); System.out.println(); } System.out.println(); } } } output: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 0 2 4 6 8 0 3 6 9 12 0 0 0 0 0 0 2 4 6 8 0 4 8 12 16 0 6 12 18 24
  • 136. Alternative Array Declaration Syntax • There is a second form used to declare an array: type[ ] var-name; int a1[] = new int[3]; int[] a2 = new int[3]; char twod1[][] = new char[3][4]; char[][] twod2 = new char[3][4]; int[] nums, nums2, nums3; //create three arrays
  • 137. String • Java’s string type, called String, is not a simple type. Nor is it simply an array of characters. Rather, String defines an object. • The String type is used to declare string variables. • Also declare arrays of strings. • A quoted string constant can be assigned to a String variable. • A variable of type String can be assigned to another variable of type String. String str = "this is a test"; System.out.println(str);
  • 138. class StrDemo { public static void main(String args[]) { String str1 = new String(); str1 = "Hello World"; System.out.println(str1); String str2 = "Bye Bye"; System.out.println(str1+str2); } }
  • 139. Pointers • Javadoes not support or allow pointers. • Java cannot allow pointers, because doing so would allow Java programs to breach the firewall between the Java execution environment and the host computer. • (Remember, a pointer can be given any address in memory—even addresses that might be outside the Javarun-time system.) • Javais designed in such a way that as long as you stay within the confines of the execution environment, you will never need to use a pointer, nor would there be any benefit in using one.
  • 140. End of today session: Students can be able to implement programs. Session Outcome
  • 142. What you learn in Previous Class
  • 143. Today’s Agenda • Operators: Arithmetic Operators, The Bitwise Operators, Relational Operators, Boolean Logic operators, The assignment operator, The ? Operator, Operator Precedence, Using Parentheses.
  • 144. Operators • Java provides a rich operator environment. Most of its operators can be divided into the following four groups: – arithmetic, – bitwise, – relational, and – logical. • Java also defines some additional operators that handle certain special situations.
  • 145. Arithmetic Operators The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is, essentially, a subset of int.
  • 146. //Demonstrate the basic arithmetic operators. class BasicMath { public static void main(String args[]) { //arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b /4; int d = c - a; int e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); //arithmetic using doubles System.out.println("nFloating Point Arithmetic"); double da = 1 + 1; double db = da * 3; double dc = db /4; double dd = dc - a; double de = -dd; System.out.println("da = " + da); System.out.println("db = " + db); System.out.println("dc = " + dc); System.out.println("dd = " + dd); System.out.println("de = " + de); } }
  • 147. • The Modulus Operator (%) • Arithmetic Compound Assignment Operators (+=) • Increment and Decrement (++, --) public class IncOp { public static void main(String args[]) { int x=1; int r = --x + x++ + ++x + x--; System.out.println(x + " " + r); } }
  • 148. //Guess the output public class Test { public static void main(String[] args) { int a = 10; int b = ++(++a); System.out.println(b); } } //final variable public class Test { public static void main(String[] args) { final int a = 10; int b = ++a; System.out.println(b); } }
  • 149. //Can not be applied boolean data type public class Test { public static void main(String[] args) { boolean b = false; b++; System.out.println(b); } }
  • 150. TheBitwise Operators • Java defines several bitwise operators that can be applied to the integer types, long, int,short, char,and byte. • These operators act upon the individual bits of their operands.
  • 151. TheBitwise Operators • The byte value for 42 in binary is 00101010, where each position represents a power of two, starting with 20 at the rightmostbit. • All of the integer types (except char) are signed integers. This means that they can represent negative values as well as positive ones. • Javauses an encoding known as two’s complement, which means that negative numbers are represented by inverting (changing 1’s to 0’s and vice versa) all of the bits in a value, then adding 1 to the result. • Example, –42 is represented by inverting all of the bits in 42, or 00101010, which yields 11010101, then adding 1, which results in 11010110, or –42.
  • 153. Bitwise OR (|) – This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 0111 = 7 (In decimal) Bitwise AND (&) – This operator is binary operator, denoted by ‘&’.It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise AND Operation of 5 and 7 0101 & 0111 0101 = 5 (In decimal)
  • 154. Bitwise XOR (^) – This operator is binary operator, denoted by ‘^’. It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0. For example, a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise XOR Operation of 5 and 7 0101 ^ 0111 0010 = 2 (In decimal) Bitwise Complement (~) – This operator is unary operator, denoted by ‘~’. It returns the one’s compliment representation of the input value, i.e, with all bits inversed, means it makes every 0 to 1, and every 1 to 0. For example, a = 5 = 0101 (In Binary) Bitwise Compliment Operation of 5 ~ 0101 1010 = 10 (In decimal)
  • 155. public class Bitoperators { public static void main(String[] args) { int a = 5; int b = 7; //bitwise and System.out.println("a&b = " + (a & b)); //bitwise or System.out.println("a|b = " + (a | b)); //bitwise xor System.out.println("a^b = " + (a ^ b)); //bitwise not ~0101=1010 //will give 2's complement of 1010 = -6 System.out.println("~a = " + ~a); //assignment a=a&b a &= b; System.out.println("a= " + a); } } Output : a&b = 5 a|b = 7 a^b = 2 ~a = -6 a= 5
  • 156. Shift Operators • These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. • They can be used when we have to multiply or divide a number by two. • Syntax number shift_op number_of_shift; • Signed Right shift operator (>>) • Unsigned Right shift operator (>>>) • Left shift operator (<<)
  • 157. log2base2 • Visit log2base2 site for animations
  • 158. public class Shiftoperators { public static void main(String[] args) { int a = 5; int b = -10; //left shift operator //0000 0101<<2 =0001 0100 //similar to 5*(2^2) (20) System.out.println("a<<2 = " + (a << 2)); //right shift operator //0000 0101 >> 2 =0000 0001 //similar to 5/(2^2) (1) System.out.println("b>>2 = " + (b >> 2)); //unsigned right shift operator System.out.println("b>>>2 = " + (b >>> 2)); } } Output : a<<2 = 20 b>>2 = -3 b>>>2 = 1073741821
  • 159. Relational Operators The outcome of these operations is a boolean value.
  • 161. Short-Circuit Logical Operators • Java provides two interesting Boolean operators, These are secondary versions of the Boolean AND and OR operators, and are known as short-circuitlogical operators. • The OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is. • If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone. • This is very useful when the right-hand operand depends on the value of the left one in order to function properly.
  • 162. Short-Circuit Logical Operators • if (denom != 0 && num /denom > 10) • Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception when denom is zero. • If this line of code were written using the single & version of AND, both sides would be evaluated, causing a run-time exception when denom is zero.
  • 163. import java.io.*; import java.util.Scanner; public class AndopEx { public static void main(String[] args) { int x,y; int sum=0; Scanner sobj = new Scanner(System.in); System.out.println("Enter x & y vals: ") x = sobj.nextInt(); y = sobj.nextInt(); ; if(x>0 && ++y>0) sum = x+y; System.out.println("x=" + x + " and y=" + y + "nx+y=" + sum); } }
  • 164. TheAssignment Operator var = expression; int x,y,z; x = y = z= 100; //set x,y,and zto 100 • This fragment sets the variables x,y,and zto 100 using a single statement. • This works because the = is an operator that yields the value of the right-hand expression. • Thus, the value of z= 100 is 100, which is then assigned to y,which in turn is assigned to x. • Using a “chain of assignment” is an easy way to set a group of variables to a common value.
  • 165. The? Operator • Java includes a special ternary (three-way) operator that can replace certain types of if-then- else statements. This operator is the ?. expression1 ? expression2 :expression3 • Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same type, which can’t be void. k = i < 0 ? -i :i; //get absolute value of i
  • 166. public class TernaryEx { public static void main(String[] args) { int A = 10; int B = 20; String result = A> B ? "A is greater" : "B is greater"; System.out.println(result); } } For three variables: String result = a > b ? a > c ? "a is greatest" : "c is greatest" : b > c ? "b is greatest" : "c is greatest“;
  • 170. End of today session: Student can be able to apply operators in java programs RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome
  • 171. Java™: The Complete Reference UNIT – 1 & Chapter - 5 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 174. Java’s Selection Statements • if • if-else • if-else-if ladder • nested if • switch RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 175. • Java’s program control statements can be put into the following categories: – Selection • Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. – Iteration • Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). – jump • Jump statements allow your program to execute in a nonlinear fashion.
  • 176. Control Statements • The if Statement : The Java if statement tests the condition. • It executes the ifblock if condition is true. if(condition) { //statement; } if(num < 100)
  • 177. //JavaProgram to demonstrate the use of if statement. public class IfExample { public static void main(String[] args) { //defining an 'age' variable int age=20; //checking the age if(age>18){ System.out.print(“Eligible for voting"); } } }
  • 178. if - else • The Java if-else statement also tests the condition. • It executes the ifblock if condition is true otherwise else block is executed. Syntax: if(condition){ //code if condition is true } else{ //code if condition is false }
  • 179. //Itis a program of odd and even number. public class IfElseExample { public static void main(String[] args) { int number=13; //Check if the number is divisible by 2 or not if(number%2==0){ System.out.println("even number"); } else{ System.out.println("odd number"); } } }
  • 180. //A year is leap, if it is divisible by 4 and 400. But, not by 100. public class LeapYearEx { public static void main(String[] args) { int year=2020; if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)) { System.out.println("LEAPYEAR"); } else { System.out.println("COMMON YEAR"); } } }
  • 181. if-else-if ladder • The if-else-if ladder statement executes one condition from multiple statements. Syntax: if(condition1){ //codeto be executed if condition1 is true }else if(condition2){ //codeto be executed if condition2 is true } else if(condition3){ //codeto be executed if condition3 is true } ... else{ //codeto be executed if all the conditions are false }
  • 182. //Itis a program of grading system for fail, D grade, Cgrade, B grade, A grade and A+. public class IfElseIfExample { public static void main(String[] args) { int marks=65; if(marks<35){ System.out.println("fail"); } else if(marks>=35 && marks<60){ System.out.println("D grade"); } else if(marks>=60 && marks<70){ System.out.println("C grade"); } else if(marks>=70 && marks<80){ System.out.println("B grade"); } else if(marks>=80 && marks<90){ System.out.println("A grade"); }else if(marks>=90 && marks<100){ System.out.println("A+ grade"); }else{ System.out.println("Invalid!"); }
  • 183. //Find out given no is +ve or –ve or zero public class PositiveNegativeExample { public static void main(String[] args) { int number=-13; if(number>0){ System.out.println("POSITIVE"); }else if(number<0){ System.out.println("NEGATIVE"); }else{ System.out.println("ZERO"); } }
  • 184. Nested if • The nested if statement represents the ifblock within another ifblock. • Here, the inner if block condition executes only when outer if block condition is true. Syntax: if(condition) { //codeto be executed if(condition){ //codeto be executed }
  • 185. //JavaProgram to demonstrate the use of Nested If Statement. public class JavaNestedIfExample { public static void main(String[] args) { int age=20; int weight=80; //applying condition on age and weight if(age>=18){ if(weight>50){ System.out.println("You are eligible to donate blood"); } else{ System.out.println("You are not eligible to donate blood"); } } else{ System.out.println("Age must be greater than 18"); } } }
  • 186. Switch Statement • The Java switch statement executes one statement from multiple conditions. • It is like if-else-if ladder statement. • The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. • There can be one or N number of case values for a switch expression. • The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables. • The case values must be unique. In case of duplicate value, it renders compile-time error. • Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case. • The case value can have a default label which is optional.
  • 187. switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }
  • 188. public class SwitchExample { public static void main(String[] args) { int number=2; //Switchexpression switch(number){ //Case statements case 1: System.out.println(“ONE"); break; case 2: System.out.println(“TWO"); break; case 3: System.out.println(“THREE"); break; //Default case statement default:System.out.println("Not in 1, 2 or 3"); } }
  • 189. //Name of the month public class SwitchMonthExample { public static void main(String[] args) { //Specifying month number int month=7; String monthString=""; //Switch statement switch(month){ //casestatements within the switch block case 1: monthString="1 - January"; break; case 2: monthString="2 - February"; break; case 3: monthString="3 - March"; break; case 4: monthString="4 - April"; break; case 5: monthString="5 - May"; break; case 6: monthString="6 - June"; break; case 7: monthString="7 - July"; break; case 8: monthString="8 - August"; break; case 9: monthString="9 - September"; break; case 10: monthString="10 - October"; break; case 11: monthString="11 - November"; break; case 12: monthString="12 - December"; break; default:System.out.println("Invalid Month!"); } //Printing month of the given number System.out.println(monthString); } }
  • 190. switch w/o break • It executes all statements after the first match, if a break statement is not present. //without break statement public class SwitchExample2 { public static void main(String[] args) { int num=2; //switch expression with int value switch(num){ //switch cases without break statements case 1: System.out.println(“1"); case 2: System.out.println(“2"); case 3: System.out.println(“3"); default:System.out.println("Not in 1, 2 or 3"); } } } Output: 2 3 Not in 1, 2 or 3
  • 191. //In a switch, break statements are optional. class MissingBreak { public static void main(String args[]) { for(int i=0; i<12; i++) switch(i) { case 0: case 1: case 2: case 3: case 4: System.out.println("i is less than 5"); break; case 5: case 6: case 7: case 8: case 9: System.out.println("i is less than 10"); break; default: System.out.println("i is 10 or more"); } } } OUTPUT: i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 5 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is less than 10 i is 10 or more i is 10 or more
  • 192. Nested Switch Statement • We can use switch statement inside other switch statement in Java. • It is known as nested switch statement.
  • 193. switch(expressio n1){ case value1: //code to be executed; break; case value2: switch(expression2){ case value21: //code to be executed; break; //option al case value22: break; //option al default: default code to be executed } break;
  • 194. Example: - You are searching for a department in a university and you’re asked to select a school from a choice of three schools namely: 1.School of Arts 2.School of Business 3.School of Engineering Having selected a school you are again provided with a list of departments that fall under the department namely: 1.School of Arts A.Department of finearts B.Department of sketcharts 2.School of Business A.Department of Commerce B.Department of purchasing 3.School of Engineering A.CSE B.ECE The initial choices for Computer Science, Business and Engineering schools would be inside as a set of switch statements. Then various departments would then be listed within inner switch statements beneath their respective schools.
  • 195. import java.io.*; import java.util.Scanner; class NestedExample { public static void main(String args[]) { int a,b; System.out.println("1.School of Artsn"); System.out.println("2.School of Businessn"); System.out.println("3.School of Engineeringn"); System.out.println("make your selectionn"); Scanner sobj = new Scanner(System.in); a=sobj.nextInt();
  • 196. switch (a) { case 1: System.out.println("You chose Artsn" ); case 2: break; System.out.println("You chose Businessn" ); case 3: //Engineering break; System.out.println("You chose Engineeringn" ); System.out.println("1.CSEn" ); System.out.println("2.ECEn" ); System.out.println("make your selectionn"); b=sobj.nextInt(); switch(b) { case 1: System.out.println("You chose CSEn" ); break; case 2: System.out.println("You chose ECE" ); break; } break; } } }
  • 197. enum in Switch Statement • Javaallows us to use enum in switch statement. • An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). • Tocreate an enum, use the enum keyword (instead of class or interface),and separate the constants with a comma. • Note that they should be in uppercase letters: enum Level { LOW, MEDIUM, HIGH } You can access enumconstants with the dot syntax: Level myVar = Level.MEDIUM;
  • 198. enum in Switch Statement public class JavaSwitchEnumExample { public enum Day { Sun, Mon, Tue,Wed, Thu,Fri, Sat } public static void main(String args[]) { Day[] DayNow = Day.values(); for (Day Now :DayNow) { switch (Now) { case Sun: System.out.println("Sunday"); break; case Mon: System.out.println("Monday"); break; case Tue: System.out.println("Tuesday"); break; case Wed: System.out.println("Wednesday"); break; case Thu: System.out.println("Thursday"); break; case Fri: System.out.println("Friday"); break; case Sat: System.out.println("Saturday"); break; } } } } Output: Sunday Monday Twesday Wednesday Thursday Friday Saturday
  • 199. End of today session: Student can be able to write programs using java conditions RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome
  • 200. Java™: TheComplete Reference UNIT – 1 & Chapter - 5 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 203. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Iteration Statements • Java’s iteration statements are for, while, and do-while. • These statements are called loops. • A loop repeatedly executes the same set of instructions until a termination condition is met.
  • 204. while • The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. while(condition) { //body of loop } • The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. • When condition becomes false, control passes to the next line of code immediately following the loop. • The curly braces are unnecessary if only a single statement is being repeated.
  • 205. //Demonstrate the while loop. class While { public static void main(String args[]) { int n = 10; while(n > 0) { System.out.println(n); n--; } } } //The target of a loop can be empty. class NoBody { public static void main(String args[]) { int i, j; i = 100; j= 200; //find midpoint between i and j while(++i < --j);//no body in this loop System.out.println("Midpoint is " + i); } }
  • 206. do-while • The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is do { //body of loop } while (condition); • 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 terminates.
  • 207. //Demonstrate the do-while loop. class DoWhile { public static void main(String args[]) { int n = 10; do { System.out.println(n); n--; } while(n > 0); } } do { System.out.println("Help on:"); System.out.println(" 1. if"); System.out.println(" 2. switch"); System.out.println(" 3. while"); System.out.println(" 4. do-while"); System.out.println(" 5. forn"); System.out.println("Choose one:"); choice = (char) System.in.read(); } while( choice < '1' || choice > '5'); System.in.read( ) is used to read characters from standard input.
  • 208. for • There are two forms of the for loop. • The first is the traditional form of Java. for(initialization; condition; iteration) { //body } • The second is the new “for-each” form. The for- each loop is essentially read-only. for(type itr-var :collection) { statement-block }
  • 209. for Loop Variations for(int a=1, b=4; a<b; a++, b--) { } for(int i=1; !done; i++) { } //Parts of the for loop can be empty. class ForVar { public static void main(String args[]) { int i; boolean done = false; i = 0; for( ;!done; ) { System.out.println("i is " + i); if(i == 10) done = true; i++; } } } //infinite loop for( ;;) { //... }
  • 210. //Use a for-each style for loop. class ForEach { public static void main(String args[]) { int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 }; int sum = 0; //use for-each style for to display and sum the values for(int x:nums) { System.out.println("Value is: " + x); sum += x; } System.out.println("Summation: " + sum); } }
  • 211. //Use for-each style for on a two-dimensional array. class ForEach3 { public static void main(String args[]) { int sum = 0; int nums[][] = new int[3][5]; //give nums some values for(int i = 0; i < 3;i++) for(int j=0; j< 5; j++) nums[i][j] = (i+1)*(j+1); //use for-each for to display and sum the values for(int x[] :nums) { for(int y :x) { System.out.println("Value is: " + y); sum += y; } } System.out.println("Summation: " + sum); } }
  • 212. //Search an array using for-each style for. class Search { public static void main(String args[]) { int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 }; int val = 5; boolean found = false; //use for-each style for to search nums for val for(int x :nums) { if(x == val) { found = true; break; } } if(found) System.out.println("Value found!"); } }
  • 213. Nested Loops • Java allows loops to be nested. That is, one loop may be inside another. //Loops may be nested. class Nested { public static void main(String args[]) { int i, j; for(i=0; i<10; i++) { for(j=i; j<10; j++) System.out.print("."); System.out.println(); } } }
  • 214. • Try all types of printing pyramid programs.
  • 215. JumpStatements • Java supports three jump statements: break, continue, and return. • These statements transfer control to another part of your program. • Java supports one other way that you can change your program’s flow of execution: through exception handling. Exception handling provides a structured method by which run-time errors can be trapped and handled by your program. It is supported by the keywords try, catch, throw, throws, and finally.
  • 216. Using break • In Java,the break statement has three uses. • First,it terminates a statement sequence in a switch statement. • Second, it can be used to exit a loop. • Third, it can be used as a “civilized” form of goto. break label; //Using break to exit a loop. class BreakLoop { public static void main(String args[]) { for(int i=0; i<100; i++) { if(i == 10) break; //terminate loop if i is 10 System.out.println("i: " + i); } System.out.println("Loop complete."); } }
  • 217. //Using break as a civilized form of goto. class Break { public static void main(String args[]) { boolean t = true; first: { second: { third: { System.out.println("Before the break."); if(t) break second; //break out of second block System.out.println("This won't execute"); } System.out.println("This won't execute"); } System.out.println("This is after second block."); } } } OUTPUT Before the break. This is after second block.
  • 218. //This program contains an error. class BreakErr { public static void main(String args[]) { one: for(int i=0; i<3; i++) { System.out.print("Pass " + i + ": "); } for(int j=0; j<100; j++) { if(j== 10) break one; //WRONG System.out.print(j + " "); } } } Since the loop labeled one does not enclose the break statement, it is not possible to transfer control out of that block.
  • 219. Using continue • Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. • In while and do-while loops, a 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 then to the conditional expression. • For all three loops, any intermediate code is bypassed. • As with the break statement, continue may specify a label to describe which enclosing loop to continue.
  • 220. //Using continue with a label. class ContinueLabel { public static void main(String args[]) { outer: for (int i=0; i<10; i++) { for(int j=0; j<10; j++) { if(j> i) { System.out.println(); continue outer; } System.out.print(" " + (i * j)); } } System.out.println(); } }
  • 221. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL 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. • The return statement immediately terminates the method in which it is executed.
  • 222. //Demonstrate return. class Return { public static void main(String args[]) { boolean t = true; System.out.println("Before the return."); if(t) return; //return to caller System.out.println("This won't execute."); } }
  • 223. End of today session: Student can be able to write programs using java loops RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Session Outcome
  • 224. Java™: The Complete Reference UNIT – 1 & Chapter - 6 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 226. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabi • Introducing Classes: Class Fundamentals, Declaring Objects, Assuming Object reference Variables, Introducing Methods, Constructors, The this Keyword, Garbage Collection, The Finalize() method, A Stack class.
  • 227. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Class Fundamentals • A class, defines a new data type. • Once defined, this new type can be used to create objects of that type. • Thus, a class is a template for an object, and an object is an instance of a class. • Because an object is an instance of a class, the two words object and instance used interchangeably.
  • 228. The General Form of a Class • A class is declared by use of the class keyword. • Classes may contain only code or only data, most real-world classes contain both. class classname { type instance-variable1; type instance-variable2; //... type instance-variableN; type methodname1(parameter-list) { //body of method } type methodname2(parameter-list) { //body of method } //... type methodnameN(parameter-list) { //body of method } }
  • 229. The General Form of a Class • The data, or variables, defined within a class are called instance variables. • The code is contained within methods. • Collectively, the methods and variables defined within a class are called members of the class. • Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another.
  • 230. A Simple Class • a class declaration only creates a template; class Box { double width; double height; double depth; } Box mybox = new Box(); //create a Box object called mybox mybox will be an instance of Box. Thus, it will have “physical” reality. Toaccess class variables, use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. mybox.width = 100; RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 231. /* 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); } }
  • 232. Declaring Objects • Obtaining objects of a class is a two-step process. • First,you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Box mybox; //declare reference to object • Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. mybox = new Box();//allocatea Box object • The new operator dynamically allocates(that is, allocates at run time) memory for an object and returns a reference to it. This reference is, more or less, the address in memory of the object allocated by new. • This reference is then stored in the variable.
  • 234. A Closer Look at new • the new operator dynamically allocates memory for an object. class-var = new classname( ); • class-var is a variable of the class type being created. • The classname is the name of the class that is being instantiated. • The class name followed by parentheses specifies the constructor for the class. • A constructor defines what occurs when an object of a class is created. • If no explicit constructor is specified, then Java will automaticallysupply a default constructor. • A class is a logical construct. An object has physical reality.
  • 235. Assigning Object Reference Variables • Object reference variables act differently when an assignment takes place. Box b1 = new Box(); Box b2 = b1; Box b1 = new Box(); Box b2 = b1; //... b1 = null; Here, b1 has been set to null, but b2 still points to the original object. When you assign one object referencevariable to another object referencevariable, you are
  • 236. Introducing Methods type name(parameter-list) { //body of method return value; } • type specifies the type of data returned by the method. This can be any valid type, including class types that you create. If the method does not return a value, its return type must be void. • The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. • The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. • value is the value returned.
  • 237. Adding method • Method With parameters • Method Without Parameters • Method Return a value • The type of data returned by a method must be compatible with the return type specified by the method. • The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
  • 239. Constructors • Automatic initializationof an object is performed through the use of a constructor. • A constructor initializes an object immediately upon creation. • It has the same name as the class in which it resides and is syntactically similar to a method. • Once defined, the constructor is automatically called immediatelyafter the object is created, before the new operator completes. • Constructors have no return type, not even void. This is because the implicit return type of a class constructor is the class type itself. • The constructor’s job to initializethe internal state of an object.
  • 240. Construct ors • Constructors are 1. Automatic Constructors 2. Default Constructors Box mybox1 = new Box(); The default constructor automatically initializes all instance variables to zero. 3. Parameterized Constructors Box mybox1 = new Box(10, 20, 15); 4.Copy Constructors
  • 241. class Box { double width; double height; double depth; //This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } //compute and return volume double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String args[]) { //declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; //get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); //get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } OUTPUT: Volume is 3000.0 Volume is 162.0 1. Default Constructors
  • 242. class Box { double width; double height; double depth; //This is the constructor for Box. Box(double w , double h, double d) { width = w; height = h; depth = d; } //compute and return volume double volume() { return width * height * depth; } } class BoxDemo7 { public static void main(String args[]) { //declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; //get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); //get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } OUTPUT: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0 Parameterized Constructors
  • 243. The this Keyword • Sometimes a method will need to refer to the object that invoked it. • Toallow this, Java defines the this keyword. • this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. Box(double w , double h, double d) { this.width = w; this.height = h; this.depth = d; }
  • 244. • Usage of java this keyword 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method.
  • 245. class Abc { int val; Abc() { System.out.println("Default Constructor Called"); } Abc(int x) { this(); val=x; System.out.println("Param Constructor " + this.val); } } class ThisEx { public static void main(String args[]){ Abc obj=new Abc(10); } }
  • 246. Instance Variable Hiding • It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. • Local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. • However, when a local variable has the same name as an instance variable, the local variable hides the instance variable. • this, resolve any name space collisions that might occur between instance variables and local variables. Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; }
  • 247. Garbage Collection • Since objects are dynamically allocated by using the new operator, how such objects are destroyed and their memory released for later reallocation? • In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. • Javatakes a different approach; it handles deallocation automatically. The technique that accomplishes this is called garbage collection. • When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
  • 248. Garbage Collection • There is no explicit need to destroy objects. • Garbage collection only occurs sporadically (if at all) during the execution of your program. • It will not occur simply because one or more objects exist that are no longer used. Furthermore, different Java run- time implementations will take varying approaches to garbage collection. • Do not to think about it while writing your programs.
  • 250. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL The finalize( ) Method • Sometimes an object will need to perform some action when it is destroyed. • For example, if an object is holding some non-Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. • Tohandle such situations, Java provides a mechanism called finalization. • By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. • Toadd a finalizer to a class, you simply define the finalize()
  • 251. protected void finalize( ) { //finalization code here } • The keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. • finalize( ) is only called just prior to garbage collection. • It is not called when an object goes out-of-scope.
  • 252. A Stack Class • A stack stores data using first-in, last-out ordering. • That is, a stack is like a stack of plates on a table— the first plate put down on the table is the last plate to be used. • Stacks are controlled through two operations traditionally called push and pop. • Toput an item on top of the stack, you willuse push. Totake an item off the stack, you will use pop. • As you will see, it is easy to encapsulate the entire stack mechanism.
  • 253. //This class defines an integer stack that can hold 10 values. class Stack { int stck[] = new int[10]; int tos; //Initialize top-of-stack Stack() { tos = -1; } //Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } //Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } }
  • 254. class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); //push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); //pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); } } OUTPUT Stack in mystack1: 9 8 7 6 5 4 3 2 1 0 Stack in mystack2: 19 18 17 16 15 14 13 12 11 10
  • 255. Java™: TheCompleteReference UNIT – 1 & Chapter - 7 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 256. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Previous Class
  • 257. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabus • Overloading Methods, Using Object as Parameter, Argument Passing, Returning Objects, Recursion, Introducing Access control,
  • 258. Overloading Methods • In Javait is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. • When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. • Method overloading is one of the ways that Javasupports polymorphism. • When an overloaded method is invoked, Javauses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. • Thus, overloaded methods must differ in the type and/or number of their parameters. • While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method.
  • 259. Method Overloading • Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different. • It is similar to constructor overloading in Java,that allows a class to have more than one constructor having different argument lists. • Threeways to overload a method 1.Number of parameters. add(int, int) add(int, int, int) 2.Data type of parameters. add(int, int) add(int, float) 3.Sequence of Data type of parameters. add(int, float) add(float, int) • Invalid case of method overloading: int add(int, int) float add(int, int)
  • 260. //Demonstrate method overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } //Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } //Overload test for two integer parameters. void test(int a,int b) { System.out.println("a and b: " + a + " " + b); } //overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; //call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }
  • 261. //Automatic type conversions apply to overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } //Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } //overload test for a double parameter void test(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); //this will invoke test(double) ob.test(123.2); //this will invoke test(double) } }
  • 262. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Overloading Constructors • Also overload constructor methods.
  • 263. //Constructor Overloading class Box { double width; double height; double depth; Box(double w,double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; //use -1 to indicate height = -1; //an uninitialized depth = -1; //box } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { //create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; //get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); //get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); //get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } } OUTPUT Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0
  • 264. Using Objects as Parameters //Objects may be passed to methods. class Test { int a,b; Test(int i,int j){ a = i; b = j; } //return true if o is equal to the invoking object boolean equals(Test o) { if(o.a== a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100,22); Testob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } } OUTPUT ob1 == ob2: true ob1 == ob3: false
  • 265. class Box { double width; double height; double depth; //Notice this constructor. It takes an object of type Box. Box(Box ob) { //pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } //constructor used when all dimensions specified Box(double w,double h, double d) { width = w; height = h; depth = d; } //constructor used when no dimensions specified Box() { width = -1; //use -1 to indicate height = -1; //an uninitialized depth = -1; //box } //constructor used when cube is created Box(double len) { width = height = depth = len; } //compute and return volume double volume() { return width * height * depth; } }
  • 266. class OverloadCons2 { public static void main(String args[]) { //create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); //create copy of mybox1 double vol; //get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); //get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); //get volume of cube vol = mycube.volume(); System.out.println("Volume of cube is " + vol); //get volume of clone vol = myclone.volume(); System.out.println("Volume of clone is " + vol); } }
  • 267. Argument Passing • there are two ways that a computer language can pass an argument to a subroutine. – call-by-value – call-by-reference • Java uses both approaches, depending upon what is passed. • In Java, when you pass a primitive type to a method, it is passed by value. • When you pass an object to a method, it is call-by- reference. • When a primitive type is passed to a method, it is done by use of call-by-value. Objects are implicitly passed by use of call-by-reference.
  • 268. //Objects are passed by reference. class Test{ int a,b; Test(inti,int j){ a = i; b = j; } //pass an object void meth(Test o) { a. *= 2; b. /=2; } } class CallByRef { public static void main(String args[]) { Testob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } OUTPUT ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10
  • 269. Returning Objects • A method can return any type of data, including class types. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 270. //Returning an object. class Test{ int a; Test(int i) { a = i; } Test incrByTen() { Testtemp = new Test(a+10); return temp; } } class RetOb { public static void main(String args[]) { Testob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: "+ ob2.a); } } OUTPUT ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
  • 271. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Recursion • Java supports recursion. • Recursion is the process of defining something in terms of itself. • Recursion is the attribute that allows a method to call itself. • A method that calls itself is said to be recursive.
  • 272. //A simple example of recursion. class Factorial { //this is a recursive method int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } } OUTPUT Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120
  • 273. Examples Given following three values, the task is to find the total number of maximum chocolates you can eat. money :Money you have to buy chocolates price :Price of a chocolate wrap :Number of wrappers to be returned for getting one extra chocolate. It may be assumed that all given values are positive integers and greater than 1. Examples: Input :money = 16, price = 2, wrap = 2 Output :15 Price of a chocolate is 2.You can buy 8chocolates from amount 16. You can return 8 wrappers back and get 4 more chocolates. Then you can return 4 wrappers and get 2 more chocolates. Finally you can return 2 wrappers to get 1 more chocolate. Input :money = 15, price = 1, wrap = 3 Output :22 We buy and eat 15 chocolates We return 15 wrappers and get 5 more chocolates. We return 3 wrappers, get 1 chocolate and eat it (keep 2 wrappers). Now we have 3 wrappers. Return 3 and get 1 more chocolate. So total chocolates = 15 + 5 + 1 + 1 Input :money = 20, price = 3, wrap = 5 Output :7
  • 274. import java.io.*; class ChocolateWrapper { static int countRec(int choc, int wrap) { if (choc < wrap) return 0; int newChoc = choc /wrap; return newChoc + countRec(newChoc + choc%wrap, wrap); } public static void main (String[] args) { int money = 16; int price = 2; int wrap = 2; if(money>=1 && price>=1 && wrap>=1) { int totchoc = money/price; totchoc += countRec(totchoc, wrap); System.out.println(totchoc); } } }
  • 275. Access Control • How a member can be accessed is determined by the access specifier that modifies its declaration. • Java supplies a rich set of access specifiers. • Java’s access specifiers are public, private, and protected. Java also defines a default access level. • protected applies only when inheritance is involved. • public specifier, that member can be accessed by any other code. • private, then that member can only be accessed by other members of its class. • default, the member of a class is public within its own package, but cannot be accessed outside of its package.
  • 276. class Test { int a; public int b; private int c; //default access //public access //private access //methods to access c //set c's value void setc(int i) { c= i; } int getc() { return c; } } class AccessTest { //get c's value public static void main(String args[]) { Testob = new Test(); ob.a = 10; //These are OK, a and b may be accessed directly ob.b = 20; //This is not OK and will cause an error //ob.c = 100; //Error! //You must access c through its methods ob.setc(100); //OK System.out.println("a,b, and c: " + ob.a + " " +ob.b + " " + ob.getc()); } }
  • 277. //This class defines an integer stack that can hold 10 values. class Stack { /* Now, both stck and tos are private. This means that they cannot be accidentallyor maliciously altered in a way that would be harmful to the stack. */ private int stck[] = new int[10]; private int tos; //Initialize top-of-stack Stack() { tos = -1; } //Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } //Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; }} class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); //push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); //pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); //these statements are not legal //mystack1.tos = -2; //mystack2.stck[3] = 100; } }
  • 278. Java™: TheCompleteReference UNIT – 1 & Chapter - 7 RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 279. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Previous Class
  • 280. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Syllabus • Understanding static, Introducing Nested and Inner classes, Exploring the String class, Using Command line Arguments, Varargs: variableLength Arguments.
  • 281. static • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. • You can declare both methods and variables to be static. • Example of a static member is main( ).main( ) is declared as static because it must be called before any objects exist. • Instance variables declared as static are, essentially, global variables. • When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable.
  • 282. • The static keyword in Java is used for memory management mainly. • We can apply static keyword with variables, methods, blocks and nested classes. • The static keyword belongs to the class than an instance of the class. • The static can be: 1. Variable (also known as a class variable) 2. Method (also known as a class method) 3. Block 4. Nested class
  • 283. static variable • If you declare any variable as static, it is known as a static variable. • The static variable can be used to refer to the common property of all objects, for example, the company name of employees, college name of students, etc. • The static variable gets memory only once in the class area at the time of class loading. • Advantages of static variable: makes your program memory efficient . class Student{ int rollno; String name; String college=“RCEW"; } class Student{ int rollno; String name; static String college ="RCEW“; }
  • 284. class Student{ int rollno; String name; static String college =“RCEW"; //constructor Student(int r,String n){ rollno = r; name = n; } //method to display the values void display (){ //instance variable //static variable System.out.println(rollno+" "+name+" "+college); } } public class TestStaticVariable1{ public staticvoid main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //wecan change the college of all objects by the single line of code //Student.college=“GPCET"; s1.display(); s2.display(); } }
  • 286. class Counter2{ staticint count=0; //willget memory only once and retain its value Counter2(){ count++;//incrementing the value of static variable System.out.println(count); } public static void main(String args[]){ //creating objects Counter2 c1=new Counter2(); Counter2 c2=new Counter2(); Counter2 c3=new Counter2(); } } Output: 1 2 3
  • 287. Static Method • A static method belongs to the class rather than the object of a class. • A static method can be invoked without the need for creating an instance of a class. • A static method can access static data member and can change the value of it. • They can only call other static methods. • They must only access static data. • They cannot refer to this or super in any way. • The static method cannot use non static data member or call non-static method directly. • Outside of the class in which they are defined, static methods and variables can be used independently of any object. Todo so, you need only specify the name of their class followed by the dot operator. classname.method( )
  • 288. class Student{ int rollno; String name; static String college = "RCEW"; //staticmethod to change the value of static variable static void change(){ college = “GPCET"; } //constructor to initialize the variable Student(int r,String n){ rollno = r; name = n; } //method to display values void display(){ System.out.println(rollno+" "+name+" "+college); } } publicclass TestStaticMethod{ public static void main(String args[]){ Student.change(); Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = newStudent(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } } Output: 111Karan GPCET 222Aryan GPCET
  • 289. class Calculate{ static int cube(int x){ return x*x*x; } public static void main(String args[]){ int result=Calculate.cube(5); System.out.println(result); } }
  • 290. class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } } OUTPUT a = 42 b = 99
  • 291. Why is the Java main method static? • It is because the object is not required to call a static method. • If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL
  • 293. static block • Is used to initialize the static data member. • It is executed before the main method at the time of classloading. class A2{ static{ System.out.println("static block is invoked"); } public static void main(String args[]){ System.out.println("Hello main"); } } Output: static block is invoked Hello main
  • 294. //Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } OUTPUT Static block initialized. x= 42 a = 3 b = 12 all of the static statements are run. First, a is set to 3, then the static block executes, which prints a message and then initializes b to a * 4 or 12. Then main( ) is called, which calls meth(), passing 42 to x.The three println( ) statements refer to the two static variables a and b, as well as to the local variable x.
  • 295. Can we execute a program without main() method? • No, • one of the ways was the static block, but it was possible till JDK 1.6. • Since JDK 1.7, it is not possible to execute a Javaclass without the main method. class A3{ static{ System.out.println("static block is invoked"); System.exit(0); } } Output: staticblockisinvoked
  • 296. Nested Classes • Java programming language allows us to create a class within a class. • The nested class architecture is divided into two: 1. nested classes that are declared static are called static nested classes 2. nested classes that are non-static are called inner classes • The main difference between these two is that the inner classes have access to all member of the enclosing class (including private), whereas the static nested classes only have access to static members of the outer class.
  • 297. //Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } //this is an inner class class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } } OUTPUT display: outer_x = 100
  • 298. //Demonstrate nested class. class TestOuter { static int data=30; static class Inner { void msg(){ System.out.println("data is "+data); } } public static void main(String args[]){ TestOuter.Inner obj=new TestOuter.Inner(); obj.msg(); } } OUTPUT data is 30
  • 299. final • The final keyword in javais used to restrict the user. • The javafinal keyword can be used in many context. 1. variable 2. method 3. class
  • 300. final variable • A variable can be declared as final. • Doing so prevents its contents from being modified. • This means that you must initialize a final variable when it is declared. • It is a common coding convention to choose all uppercase identifiers for final variables. • Variables declared as final do not occupy memory on a per-instance basis. • Thus, a final variable is essentially a constant. • A field that is both static and final has only one piece of storage that cannot be changed. • The keyword final can also be applied to methods, and classes. • A final variable that is not initialized at the time of declaration is known as blank final variable. We can initialize using constructors only. • A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5; class A{ static final int data;//static blank final variable static{ data=50;} public static void main(String args[]){ System.out.println(A.data); } }
  • 301. final variable • If you declare any parameter as final, you cannot change the value of it. class Bike11{ int cube(final int n){ n=n+2; //can't be changed as n is final n*n*n; } public static void main(String args[]){ Bike11 b=new Bike11(); b.cube(5); } } Can we declare a constructor final? No, because constructor is never inherited.
  • 302. class finalvar{ final int x=90; void run(){ x=400; } //final variable public static void main(String args[]) { finalvar obj=newfinalvar(); obj.run(); } }//end of class Output: Compile Time Error
  • 303. final method • If you make any method as final, you cannot override it. • Is final method inherited? Yes, final method is inherited but you cannot override it. class Bike{ final void run(){ System.out.println("running"); } } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error
  • 304. final class • If you make any class as final, you cannot extend it. final class Bike{ void run(){ System.out.println("running"); } } class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } Output:Compile Time Error
  • 305. String Class • The first thing, strings are actually an object of type String. • Even string constants are actually String objects. Example System.out.println("This is a String, too"); • objects of type String are immutable; once a String object is created, its contents cannot be altered. – If you need to change a string, you can always create a new one that contains the modifications. – Java defines a peer class of String, called StringBuffer, which allows strings to be altered. • + is used to concatenate two strings. • Testtwo strings for equality by using equals( ). • length of a string by calling the length( ) method. • character at a specified index within a string by calling charAt( ).
  • 306. //Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length()); System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } } OUTPUT Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3
  • 307. command line arguments • Sometimes you will want to pass information into a program when you run it.This is accomplished by passing command-line arguments to main( ). • A command-line argument is the information that directly follows the program’s name on the command line when it is executed. • Toaccess the command-line arguments inside a Java program, they are stored as strings in a String array passed to the args parameter of main( ). • The first command-line argument is stored at args[0], the second at args[1], and so on. • All command-line arguments are passed as strings.
  • 308. command line arguments public class CommandLine { public static void main(String args[]) { for(int i = 0; i<args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } } d:/mahesh>javac CommandLine.java d:/mahesh>javaCommandLine this is a command line 200 -100 Output args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100
  • 309. Varargs: Variable-Length Arguments • JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of arguments. This feature is called varargs and it is short for variable-length arguments. • A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method. example is the printf( ) • Prior to JDK 5, variable-length arguments could be handled two ways, – if the maximum number of arguments was small and known, then you could create overloaded versions of the method, one for each way the method could be called. – In cases where the maximum number of potential arguments was larger, or unknowable, a second approach was used in which the arguments were put into an array, and then the array was passed to the method.
  • 310. class PassArray { static void vaTest(int v[]) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x :v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { //Notice how an array must be created to hold the arguments. int n1[] = { 10 }; int n2[] = { 1, 2, 3 }; int n3[] = { }; vaTest(n1); //1 arg vaTest(n2); //3 args vaTest(n3); //no args } } OUTPUT Number of args: 1 Contents: 10 Number of args: 3 Contents: 1 2 3 Number of args: 0 Contents: it is tedious to construct an array each time vaTest( ) is called, it is potentially error-prone.
  • 311. varags • A variable-length argument is specified by three periods (...). • For example, here is how vaTest( ) is written using a vararg: static void vaTest(int ...v) { } • This syntax tells the compiler that vaTest( ) can be called with zero or more arguments. • As a result, v is implicitly declared as an array of type int[ ].Thus, inside vaTest( ),v is accessed using the normal array syntax. • The ...syntax simply tells the compiler that a variable number of arguments will be used.
  • 312. //Demonstrate variable-length arguments. class VarArgs { //vaTest() now uses a vararg. static void vaTest(int ...v) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x :v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { //Notice how vaTest() can be called with a variable number of arguments. } vaTest(10); vaTest(1, 2, 3); vaTest(); //1 arg //3 args //no args }
  • 313. • Valid statement int doIt(int a,int b, double c,int ...vals) {} • declare a regular parameter after the varargs parameter is invalid. int doIt(int a, int b, double c,int ...vals, boolean stopFlag) { //Error! • declare the second varargs parameter is illegal. int doIt(int a, int b, double c,int ...vals, double ...morevals) { //Error!
  • 314. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Overloading Vararg Methods • You can overload a method that takes a variable- length argument.
  • 315. //Varargs and overloading. class VarArgs3 { static void vaTest(int ...v) { System.out.print("vaTest(int ...):" +"Number of args: " + v.length +" Contents: "); for(int x :v) System.out.print(x + " "); System.out.println(); } static void vaTest(boolean ...v) { System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: "); for(boolean x :v) System.out.print(x + " "); System.out.println(); } static void vaTest(String msg, int ...v) { System.out.print("vaTest(String, int ...): " +msg + v.length +" Contents: "); for(int x :v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest(1, 2, 3); vaTest("Testing: ", 10, 20); vaTest(true, false, false); } } OUTPUT vaTest(int ...):Number of args: 3 Contents: 1 2 3 vaTest(String, int ...):Testing: 2 Contents: 10 20 vaTest(boolean ...)Number of args: 3 Contents: true false false
  • 316. RCEW, Pasupula (V), Nandikotkur Road, Near Venkayapalli, KURNOOL Varargs and Ambiguity • Somewhat unexpected errors can result when overloading a method that takes a variable-length argument. • These errors involve ambiguity because it is possible to create an ambiguous call to an overloaded varargs method.
  • 317. //Varargs, overloading, and ambiguity. //This program contains an error and will not compile! class VarArgs4 { static void vaTest(int ...v) { System.out.print("vaTest(int ...):" +"Number of args: " + v.length +" Contents: "); for(int x :v) System.out.print(x + " "); System.out.println(); } static void vaTest(boolean ...v) { System.out.print("vaTest(boolean ...) " +"Number of args: " + v.length +" Contents: "); for(boolean x :v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) { vaTest(1, 2, 3); //OK vaTest(true, false, false); //OK vaTest(); //Error: Ambiguous! } }
  • 318. static void vaTest(int ...v) { //... static void vaTest(int n, int ...v) { //... Although the parameter lists of vaTest( ) differ, there is no way for the compiler to resolve the following call: vaTest(1) Does this translate into a call to vaTest(int ...),with one varargs argument, or into a call to vaTest(int, int ...)with no varargs arguments? There is no way for the compiler to answer this question. Thus, the situation is ambiguous. Because of ambiguity errors like those just shown, sometimes you will need to forego overloading and simply use two different method names. Also, in some cases, ambiguity errors expose a conceptual flaw in your code, which you can remedy by more carefully crafting a solution.