U21CSG04- JAVA PROGRAMMING
UNIT I
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 1
TOPIC 1
The Genesis of JAVA
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 2
The Genesis of JAVA -The Creation of Java
➢ Java team members (also known as green team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc.
➢ Specially Designed for interactive television – highly qualified to time
➢ However, it was suited for internet programming. Later, Java technology was incorporated by Netscape.
➢ James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
➢ Initially designed for small, embedded systems in electronic appliances like set-top boxes.
➢ Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
➢ After that, it was called Oak and was developed as a part of the Green project.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 3
Why Java named "Oak"?
➢ Why Oak?
Oak is a symbol of strength and chosen as a national tree of many countries like the U.S.A., France, Germany,
Romania, etc.
➢ In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Why had they chosen java name for Java language ?
➢ Java is an island of Indonesia where the first coffee was produced (called java coffee).
➢ It is a kind of espresso bean. Java name was chosen by James Gosling while having coffee near his office.
➢ Notice that Java is just a name, not an acronym.
➢ Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle Corporation) and
released in 1995.
➢ JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been many additional features added
to the language.
➢ Now Java is being used in Windows applications, Web applications, enterprise applications, mobile applications, cards,
etc. Each new version adds the new features
12-10-2023
in Java.
Prepared By [Link] AP(SrG)/CSE(AIML) 4
Java Versions –(Evolutions of Java)
➢ JDK Alpha and Beta (1995)
➢ JDK 1.0 (23rd Jan 1996)
➢ JDK 1.1 (19th Feb 1997) ---Added New Library Elemenets
➢ J2SE 1.2 (8th Dec 1998) ---Second Generation- Java 2 Platform Standard Editions—Included
Swing,Collections,Thread,RMI,etc
➢ J2SE 1.3 (8th May 2000) --- released with tiny Improvements– Nevertheless important
➢ J2SE 1.4 (6th Feb 2002) --- included Keyword assert chained exceptions ,Updated the changes in collections
and networking Framework
➢ J2SE 5.0 (30th Sep 2004) ---Included the annotations and Auto Boxing and auto Unboxings
➢ Java SE 6 (11th Dec 2006) ---included the support to Scripting languages
➢ Java SE 7 (28th July 2011) – Supports Dynamic Language and improved Interfaces and try catch..
➢ Java SE 8 (18th Mar 2014) ---Allowed to embed JS Script Code in Java applications
➢ Java SE 9 (21st Sep 2017) ---Reactive stream implementation
➢ Java SE 10 (20th Mar 2018) --Application Class-Data Sharing, Additional Unicode Language-Tag Extensions
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 5
INTRODUCTION– “ THE JAVA MAGIC (ByteCode)”
➢ Java technology is both a
Programming Language And a Platform
Java – The Platform
➢ What is Platform? ---A platform is the hardware or software environment in which a program runs
➢ Well Known Samples---- Windows OS, Linux OS, Unix OS, Solaris OS, Kernals..etc
Java is a
➢ Software-only platform that runs on top of other hardware-based platforms
The Java platform have two components:
➢ The Java Virtual Machine
➢ The Java Application Programming Interface (API)
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 6
INTRODUCTION– “THE JAVA MAGIC (ByteCode)” (Cont…)
The Java Virtual Machine (JVM)
➢ Java Virtual Machine is an “ABSTRACT COMPUTING MACHINE”
JVM interprets --- JAVA Binary Code (a) JAVA Byte Codes – Into machine code for Processor
The Java API
➢ The API is a large collection of ready-made software components
➢ These are grouped into libraries of related classes and interfaces; these libraries are known as packages
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 7
INTRODUCTION– “THE JAVA MAGIC (ByteCode)” (Cont…)
The Java Programming Language
➢ The Java programming language is a high-level language
➢ Programming Language---- Set of Instructions Which make the machine to act based on our Needs
Characters of Java ---(BUZZ WORDS)
➢ Simple ➢ Architecture neutral
➢ Object oriented ➢ Portable
➢ Distributed ➢ High performance
➢ Multithreaded ➢ Robust
➢ Dynamic ➢ Secure
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 8
INTRODUCTION– “THE JAVA MAGIC (ByteCode)” (Cont…)
The Java –Software Development Process Steps
➢ Source code Written in text files with .Java Extension
➢ Compiling the text files in .class file using javac Compiler.
➢ The class File does not contain ---Machine code to processor , Instead
➢ It Contains “BYTE CODES” –
➢ Byte Code is Machine Language for JVM ( Java Virtual Machine)
➢ Running the application with an instance of the Java Virtual Machine
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 9
INTRODUCTION– “THE JAVA MAGIC (ByteCode)” (Cont…)
The Java program Execution Process:
Write code in Notepad
Java –Compiler– Covert Java code to Byte code
JVM – Covert Byte code to Machine code
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 10
INTRODUCTION– “THE JAVA MAGIC (ByteCode)” (Cont…)
The Java program Execution Process: //Java code
Public static void main(String []args)
{
int a=10,b=20, c;
c=a*b;
Javac-- Compiler [Link](c);
}
// Bytecode stream: 03 3b 84 00 01 1a 05 68 3b a7 ff f9
// Disassembly:
iconst_0 // 03
istore_0 // 3b //Machine
iinc 0, 1 // 84 00 01 code
JVM
iload_0 // 1a 01…
iconst_2 // 05 10..
imul // 68 11…
istore_0 // 3b
goto -7 // a7 ff f9
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 11
Let’s Go for The Demo
Thank you
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 12
TOPIC 2
The Overview of JAVA
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 13
Object-Oriented Programming
➢ Object-oriented programming (OOP) is at the core of Java.
➢ All Java programs are to at least some extent object-oriented.
Two Paradigms
All computer programs consist of two elements: code and data.
The Program can be organized [Link] Code (What is happening) (or)
2. Around Data (Who is going to be Affetcted)
➢ Process-oriented model → code acting on data. (Ie) Procedural Languages Like C ---These are complex
➢ object-oriented programming → data controlling access to code.
Abstraction
➢ Abstraction is a process of hiding the implementation details and showing only functionality to the user.
(Ex) – No Need to know how internal parts of an car is working– Just need to know to drive
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 14
The Three OOP Principles
Encapsulation
➢ Encapsulation in Java is a process of wrapping code and data together into a single unit
➢ Restrict Access to data out side of the wrapper class.
➢ Access to the code and data inside the wrapper is tightly controlled through a
well-defined interface.
➢ A class defines the structure and behaviour (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,
➢ objects are sometimes referred to as instances of a class.
➢ 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.
➢ Each method or variable in a class may be marked private or public.
➢ The private Interface refers the data can only be accessed by code that is a member of the class.
➢ The public Interface refers the data can be accessed by code that is not even a member of the class.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 15
Inheritance
➢ Inheritance is the process by which one object acquires the properties of another object.
➢ Inheritance is important because it supports the concept of hierarchical classification.
Class:
A class is a group of objects which have common properties.
Sub Class/Child Class:
Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
Super Class/Parent Class:
Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
Reusability:
Reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you
create a new class.
You can use the same fields and methods already defined in the previous class.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 16
Polymorphism
➢ Polymorphism is a feature that allows one interface to be used for a general class of actions.
➢ Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms
Polymorphism, Encapsulation, and Inheritance Work Together
➢ 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.
➢ Example: Object : Bajaj Pulsar
➢ Bajaj CT100→Bajaj Discover→Pulsar ------Inheritance
➢ Bajaj Pulsar -→ Pulsar 150, Pulsar 125, Pulsar 200, Pulsar 220 ---Same Bike Diff functions – Polymorphism
➢ Bajaj Pulsar→ DTS-I Engine( Digital Twin Spark ignition) --- Technical we don't know– But working-- Encaptulation
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 17
A First Simple Program
Entering the Program
/*
This is a simple Java program. Class Name and File name should be equal
Call this file "[Link]". File name extension should be .java
*/ Case sensitive – Be precise while naming the file.
class Example {
// Your program begins with a call to main(). Compiling the Program
public static void main(String args[]) {
[Link]("This is a simple Java program."); execute the compiler--- javac,
} specifying the name of the source file
}
C:\>javac [Link]
➢ The javac compiler creates a file called [Link] that contains the bytecode version of the program.
➢ As discussed earlier, the Java bytecode is the intermediate representation of your program that contains instructions
the Java Virtual Machine will execute. Thus, the output of javac is not code that can be directly executed.
➢ To actually run the program, you must use the Java application launcher, called java.
To do so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
➢ When the program is run, the following output is displayed:
This is a simple Java program
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 18
Note:
Why it is instructed to Name the program as same as class name ?
When Java source code is compiled, each individual class is put into its own output file named after the class
and using the .class extension.
This is why it is a good idea to give your Java source files the same name as the class they
contain—the name of the source file will match the name of the .class file.
When you execute java as just shown,
you are actually specifying the name of the class that you want to execute. It will automatically
search for a file by that name that has the .class extension. If it finds the file, it will execute the code
contained in the specified class.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 19
S Notations Definition
no
1 /*This is a simple Java This is a comment. Multiline commend Line. This type of comment must begin with /* and
[Link] this file end with */. Anything
"[Link]".*/ between these two comment symbols is ignored by the compiler. As the name suggests, a
multiline comment may be several lines long.
2 class Example { Class is a keyword and Example is An Identifier (Name of the Class)
The entire class definition, including all of its members,
will be between the opening curly brace ({) and the closing curly brace (})
3 public static void This line begins the main( ) method.
main(String args[]) { The public keyword is an access specifier --- control the
visibility of class members.
Public--- Allow Class members Accessed by code outside of the class
Private – Prevent Class members Accessed by code outside of the class
NOTE: Why Main() Needed to be Public?
since it must be called by code outside of its class when the program is started
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
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 20
S Notations Definition
no
1 public static void The variable Specified with in parenthesis followed by name of method called
main(String args[]) Parameters.
A Method Not Necessarily to have Parameter. Even it must have empty Parenthesis.
Here the main –Have only one Parameter “args” –It is the type of array of instances (ie:
Class String)
In this case, args receives any command-line arguments present when the program is
executed.
2 [Link]("This println( ) is a method – It displays the string which (whatever) is passed to it
is a simple Java
program."); System is a predefined class that provides access to the
system, and out is the output stream that is connected to the console.
NOTE:
Java is case-sensitive. Thus, Main is different from main.
if you had typed Main instead of main, java would report an error because it would be unable
to find the main( ) method.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 21
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) { // begin a block for(x = 0; x<10; x++) {
x = y; [Link]("This is x: " + x);
y = 0; [Link]("This is y: " + y);
} // end of block y = y - 2;
}
Lexical Issues
Whitespace
Java is a free-form language.
NOTE: Do not need to follow any special indentation rules.
Literals
A constant value in Java is created by using a literal representation
Examples: 100 ,98.6 , 'X’ ,"This is a test"
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 22
Identifiers
Identifiers are used for class names, method names, and variable names.
➢ An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
➢ They must not begin with a number, lest they be confused with a numeric literal.
Avg a4 Temp count $test this_is_ok
Separators
There are a few characters that are used as separators.
The most commonly used separator in Java is the semicolon
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 23
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
The keywords const and goto are reserved but not used
Java reserves the following also : true, false, and null
NOTE: We may not use these words for the names of variables, classes,and so on.
The Java Class Libraries
println( ) and print( ) - methods are members of the System class - class predefined by Java that is automatically
included in your programs.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 24
TOPIC 3
Data Types, Variables,
and Arrays
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 25
NOTE : Why java called as Strongly Typed language?
1.
Every variable has a type,
Every expression has a type, and
Every type is strictly defined
2.
All assignments, (whether explicit or via parameter passing in method calls) , are checked for
type compatibility
3.
There are no automatic conversions of conflicting types as in some languages.
4.
The Java compiler checks all expressions and parameters to ensure that the types are compatible.
5.
Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 26
Data Types
Data types specify the different sizes and values that can be stored in the variable
Primarily classified into two…
[Link] data types:
[Link] primitive data types include boolean, char, byte, short, int, long, float and double.
[Link]-primitive data types:
[Link] non-primitive data types include Classes, Interfaces, and Arrays.
The Primitive Types
primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean
Integers Floating-point numbers
This group includes byte, short, int, and long,
which are for whole-valued This group includes float and double,
signed numbers. represent numbers with fractional precision
Characters Boolean
This group includes char, which represents This group includes boolean, which is a special
symbols in a character set,like letters and numbers type for representingtrue/false values.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 27
Integers
1. Byte Data Type
➢ It is an 8-bit signed two's complement integer
➢ Smallest Integer type- Variables of type byte are especially useful when you’re working with a stream of data
from a network or file.
➢ Its value-range lies between -128 to 127 (inclusive)
➢ Its minimum value is -128 and
➢ maximum value is 127.
➢ Its default value is 0.
➢ Byte variables are declared by use of the byte keyword
➢ Example : byte b, c; byte a = 10, byte b = -20
2. Short Data Type
➢ The short data type is a 16-bit signed two's complement integer.
➢ Smallest Integer type- Variables of type byte are especially useful when you’re working with a stream of data
from a network or file.
➢ Its value-range lies between -32,768 to 32,767
➢ Its minimum value is -32,768 and
➢ maximum value is 32,767.
➢ Its default value is 0.
➢ Short variables are declared by use of the short keyword
➢ Example : short b, c; short a = 10, byte b = -20
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 28
Integers(cont…)
3. Int Data Type
➢ It is an 32-bit signed two's complement integer
➢ In addition to other uses, variables of type int are commonly employed to control loops and to index arrays.
➢ Its value-range lies between (-2^31) to (2^31 -1)
➢ Its minimum value is -2,147,483,648 and
➢ maximum value is 2,147,483,647.
➢ Its default value is 0.
➢ int variables are declared by use of the int keyword
➢ Example : int b, c; int a = 10, byte b = -20
4. Long Data Type
➢ The long data type is a 64-bit two's complement integer
➢ This makes it useful when big, whole numbers are needed. For example, here is a program that computes
the number of miles that light will travel in a specified number of days.
➢ Its value-range lies between (-2^63)to (2^63 -1)
➢ Its minimum value is -9,223,372,036,854,775,808 and
➢ maximum value is 9,223,372,036,854,775,807.
➢ Its default value is 0.
➢ long variables are declared by use of the long keyword
➢ Example : long b, c; long a = 10, byte b = -20
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 29
NOTE:
Why Java not support unsigned types ?
➢ Java does not support unsigned, positive-only integers.
➢ Java designers felt that the concept of unsigned was used mostly to specify the behavior of the high-
order bit which defines the sign of an integer value.
➢ Java manages the meaning of the high-order bit differently, by adding a special “unsigned right shift”
operator.
➢ Thus, the need for an unsigned integer type was eliminated.
// Compute distance light travels using long variables. seconds = days * 24 * 60 * 60; // convert to seconds
class Light { distance = lightspeed * seconds; // compute distance
public static void main(String args[]) { [Link]("In " + days);
int lightspeed; [Link](" days light will travel about ");
long days; [Link](distance + " miles.");
long seconds; }
long distance; }
// approximate speed of light in miles per second This program generates the following output:
lightspeed = 186000; In 1000 days light will travel about 16070400000000 miles.
days = 1000; // specify number of days here Clearly, the result could not have been held in an int variable.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 30
Floating-Point Types
➢ Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional
precision.
For example,
Calculations such as square root, or transcendentals such as sine and cosine, result in a value whose
precision requires a floating-point type
➢ Java implements the standard (IEEE–754) set of floating-point types and operators.
➢ There are two kinds of floating-point types, float and double,
which represent single- and double-precisionnumbers, respectively
Float Data Type
➢ The float data type is a single-precision 32-bit IEEE 754 floating point.
➢ Pros: Single precision is faster on some processors and takes half as much space as double precision
➢ Cons: but will become imprecise when the values are either very large or very small
➢ Variables of type float are useful when you need a fractional component, but don’t require a large degree of precision
(i.e) float can be useful when representing dollars and cents.
Example:float hightemp, lowtemp;
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 31
Double Data Type
➢ The double data type is a double-precision 64-bit IEEE 754 floating point.
Pros:
➢ Double precision is actually faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations.
➢ All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
➢ When you need to maintain accuracy over many iterative calculations, or are manipulating large-valued .
Example:double hightemp, lowtemp;
Character Data Type
➢ The char data type is a single 16-bit Unicode character.
➢ Its value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
➢ The char data type is used to store characters.
➢ Example: char letterA = 'A'
Boolean Data Type
➢ The Boolean data type is used to store only two possible values: true and false.
➢ This data type is used for simple flags that track true/false conditions.
➢ The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
➢ Example: Boolean > 12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 32
NOTE:
Why Java Char datatype differs form C,C++?
➢ Java uses Unicode to represent characters
Unicode defines a fully international character set that can represent all of the characters found in all human
languages(Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.)
➢ For this purpose, Java requires 16 bits to represent Char datatype.
➢ Java char is a 16-bit type.
➢ The range of a char is 0 to 65,536.
➢ There are no negative chars.
Note:
The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the
extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
C and C++ :
Uses ASCII Standard – 8 bits only-Singned (Negative) char is also available
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 33
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
NOTE: All variables must be declared before they can be used
Syntax
type identifier [ = value][, identifier [= value] ...] ;
Type -- represent data type
identifier --is the name of the variable
To initialize value can use Equal to Symbol
More then one variable can be declared using comma separation
Example
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing // d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x’; // the variable x has the value 'x'.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 34
Variables (Cont..)
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is
declared
//Demonstrate dynamic initialization. (This is Command Line)
class DynInit { // Class Name
public static void main(String args[]) { // Main function
double a = 3.0, b = 4.0; // Two Local var declared and Initialized with const value
double c = [Link](a * a + b * b); // c is declared and Dynamically Initialized by Expression
[Link]("Hypotenuse is " + c); // Display OP variable
}
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 35
Variables (Cont..)
The Scope and Lifetime of Variables
➢ Java allows variables to be declared within any block
➢ Block is begun with an opening curly brace and ended by a closing curly brace
➢ Each time you start a new block, you are creating a new scope.
➢ A scope determines what objects are visible to other parts of your program.
➢ It also determines the lifetime of those objects.
NOTE: 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.
// Demonstrate block scope. // x and y both known here.
class Scope { [Link]("x and y: " + x + " " + y);
public static void main(String args[]) { x = y * 2;
int x; // known to all code within main }
x = 10; // y = 100; // Error! y not known here
if(x == 10) { // start new scope // x is still known here.
int y = 20; // known only to this block [Link]("x is " + x);
}}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 36
Variables (Cont..)
The Scope and Lifetime of Variables (Cont…)
NOTE:
variables are created when their scope is entered, and destroyed when their scope is left.
This means that a variable will not hold its value once it has gone out of scope.
// Demonstrate lifetime of a variable.
class LifeTime { The output generated by this program is
public static void main(String args[]) { shown here:
int x; y is: -1
for(x = 0; x < 3; x++) { y is now: 100
int y = -1; // y is initialized each time block is entered y is: -1
[Link]("y is: " + y); // this always prints -1 y is now: 100
y = 100; y is: -1
[Link]("y is now: " + y); y is now: 100
}}}
NOTE:
// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared!
int count;
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 37
Variables (Cont..)
Type Conversion and Casting
➢ Assign a value to the variable of one type to a variable of another type
➢ If the two types are compatible,
Then “Automatic Type Conversion” will takes place.
Example:
➢ It is always possible to assign an int value to a long variable.
➢ If the two types are compatible,
Then “ Explict Conversion(i.e) Cast ” will takes place.
Example:
No automatic conversion defined from double to byte.
NOTE:
Java’s Automatic Conversions—
The two types are compatible.
The destination type is larger than the source type.
Casting Incompatible Types
The two types are incompatible.
The destination type is Smaller than the source type.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 38
Variables (Cont…)
Type Conversion and Casting (cont…)
Casting :
➢ To create a conversion between two incompatible types, you must use a cast.
➢ A cast is simply an explicit type conversion. It has this general form
Syntax:
(target-type) value
// Demonstrate casts. [Link]("d and i " + d + " " + i);
class Conversion { [Link]("\nConversion of double to byte.");
public static void main(String args[]) { b = (byte) d;
byte b; [Link]("d and b " + d + " " + b);
int i = 257; }}
double d = 323.142;
[Link]("\nConversion of int to byte."); This program generates the following output:
b = (byte) i; Conversion of int to byte.
[Link]("i and b " + i + " " + b); i and b 257 1
[Link]("\nConversion of double to int."); Conversion of double to int.
i = (int) d; d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 39
Variables (Cont…) Type Conversion and Casting (cont…)
Automatic Type Promotion in Expressions
NOTE:
Java automatically promotes each byte, short, or char operand to int when evaluating an expression
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c; // Here a*b is performed using integers—not bytes.
The Type Promotion Rules class Promote {
public static void main(String args[]) {
Java defines several type promotion rules that byte b = 42;
apply to expressions char c = 'a';
short s = 1024;
➢ All byte, short, and char values are promoted to int,
int i = 50000;
➢ If one operand is a long, the whole expression is
float f = 5.67f;
promoted to long
double d = .1234;
➢ If one operand is a float, the entire expression is promoted
double result = (f * b) + (i / c) - (d * s);
to float
[Link]((f * b) + " + " + (i / c) + " - " + (d * s));
➢ If any of the operands is double, the result is double.
[Link]("result = " + result);
}
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 40
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.
One-Dimensional Arrays
➢ A one-dimensional array is, essentially, a list of like-typed variables.
➢ To create an array, you first must create an array variable of the desired type.
Declaration Syntax is
type var-name[ ];
➢ Type is Base type of array.. That determines the data type of each element .
➢ Example: int month_days[];
➢ month_days is an array variable (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.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 41
Syntax:
array-var = new type[size];
Example:
month_days = new int[12];
Note:
Array variable- Name of the array.
New-Keyword—Allocate memory to array.
Size specifies the number of elements in the array.
Values of Each element automatically initialized as zero by new keyword
// Demonstrate a one-dimensional array. month_days[7] = 31;
class Array { month_days[8] = 30;
public static void main(String args[]) { month_days[9] = 31;
int month_days[]; month_days[10] = 30;
month_days = new int[12]; month_days[11] = 31;
month_days[0] = 31; [Link]("April has " + month_days[3] + " days.");
month_days[1] = 28; }
month_days[2] = 31; }
month_days[3] = 30;
month_days[4] = 31; Output:
month_days[5] = 30; April has 30 days
month_days[6] = 31;
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 42
Syntax: Can be used as Optimized : Reduced no of line
int Arr_Var[] = new int[size];
Example:
int month_days[] = new int[12];
Array Initializer
➢ Arrays can be initialized when they are declared
➢ An array initializer is a list of comma-separated expressions surrounded by curly braces
// An improved version of the previous program.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
[Link]("April has " + month_days[3] + " days.");
}
}
Output:
April has 30 days
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 43
Multidimensional Arrays
➢ Multidimensional arrays are actually arrays of arrays.
➢ To declare a multidimensional array variable, specify each additional index using another set of square brackets.
Two dimensional Arrays
Syntax
int twoD[][] = new int[4][5];
Note: This allocates a 4 by 5 array and assigns it to twoD.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 44
NOTE:
// Demonstrate a two-dimensional array.
class TwoDArray {
➢ To allocate memory for a multidimensional array need only specify
public static void main(String args[]) {
the memory for the first (leftmost) dimension.
int twoD[][]= new int[4][5];
➢ Can allocate the remaining dimensions separately.
int i, j, k = 0;
➢ Example:
for(i=0; i<4; i++)
int twoD[][] = new int[4][];
for(j=0; j<5; j++) {
twoD[0] = new int[5];
twoD[i][j] = k;
twoD[1] = new int[5];
k++;
twoD[2] = new int[5];
}
twoD[3] = new int[5];
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
// Manually allocate differing size second
[Link](twoD[i][j] + " ");
dimensions.
[Link]();
} int twoD[][] = new
} int[4][];
} twoD[0] = new int[1];
output: 01234 twoD[1] = new int[2];
56789 twoD[2] = new int[3];
10 11 12 13 14 twoD[3] = new int[4];
15 16 17 18 19
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 45
NOTE:
Alternative Array Declaration Syntax
second form that may be used to declare an array:
Syntax:
type[ ] var-name;
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the same time. For example,
int[] nums, nums2, nums3; // create three arrays
creates three array variables of type int. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 46
TOPIC 4
Operator Types - Control Statements
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 47
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 48
Arithmetic Operators( Cont..)
// Demonstrate the basic arithmetic operators. [Link]("\nFloating Point Arithmetic");
class BasicMath { double da = 1 + 1;
public static void main(String args[]) { double db = da * 3;
// arithmetic using integers double dc = db / 4;
[Link]("Integer Arithmetic"); double dd = dc - a;
int a = 1 + 1; double de = -dd;
int b = a * 3; [Link]("da = " + da);
int c = b / 4; [Link]("db = " + db);
int d = c - a; [Link]("dc = " + dc);
int e = -d; [Link]("dd = " + dd);
[Link]("a = " + a); [Link]("de = " + de);
[Link]("b = " + b); }
[Link]("c = " + c); }
[Link]("d = " + d);
[Link]("e = " + e); output: Integer Arithmetic Floating Point Arithmetic
// arithmetic using doubles a = 2 da = 2.0
b = 6 db = 6.0
c = 1 dc = 1.5
d = -1 dd = -0.5
e = 1 de = 0.5
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 49
Arithmetic Operators( Cont..)
The Modulus Operator Arithmetic Compound Assignment Operators
Java provides special operators that can be used to
➢ The modulus operator, %, returns the remainder of
combine an arithmetic operation with
a division operation.
an assignment
➢ It can be applied to floating-point types as well as
integer types. a = a + 4;
In Java, you can rewrite this statement as shown here:
// Demonstrate the % operator. a += 4;
class Modulus { // Demonstrate several assignment operators.
public static void main(String args[]) { class OpEquals {
int x = 42; public static void main(String args[]) {
double y = 42.25; int a = 1; int b = 2; int c = 3;
[Link]("x mod 10 = " + x % 10); a += 5; output
[Link]("y mod 10 = " + y % 10); b *= 4; a=6
} c += a * b; b=8
} c %= 6; c=3
Output: [Link]("a = " + a);
x mod 10 = 2 [Link]("b = " + b);
y mod 10 = 2.25 [Link]("c = " + c);
}}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 50
Increment and Decrement (Arithmetic Operators( Cont..))
The ++ and the – – are Java’s increment and decrement operators
The increment operator increases its operand by one. The decrement operator decreases
its operand by one.
x = x + 1; can be rewritten as x++;
x = x - 1; can be rewritten as x--;
NOTE:
// Demonstrate ++.
Equivalent representations
class IncDec {
y = ++x; ➔ x=x+1 ; y=x;
public static void main(String args[]) {
int a = 1; int b = 2;
y = x++; ➔ y=x ; x=x+1 ;
int c;
Example:
int d;
x = 42;
c = ++b;
y = ++x; → O/P Y=43
d = a++;
c++;
x = 42;
[Link]("a = " + a); Output
y = x++; → O/P Y=42
[Link]("b = " + b); a = 2
[Link]("c = " + c); b = 3
[Link]("d = " + d); c = 4
}} d = 1
Prepared By [Link]
12-10-2023 51
AP(SrG)/CSE(AIML)
The Bitwise 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
NOTE:
Receiving input Operant is Byte or Integer…etc
All of the integer types are represented by binary numbers of varying bit widths
Example: byte value for 42 in binary is 00101010,
Since numeric type are signed…. The –ve numbers converted as 2’s Complement
Example: byte value for -42 in binary is 11010110,,
Prepared By [Link]
12-10-2023 52
AP(SrG)/CSE(AIML)
The Bitwise Operators (Cont…)
The Bitwise Logical Operators The Bitwise AND
The bitwise logical operators are &, |, ^, and ~. The AND operator, &, produces a 1 bit if both
The bitwise operators are applied to each individual bit within operands are also 1. A zero is produced in all
each operand. other cases.
Example:
00101010 42
& 00001111 15
00001010 10
The Bitwise OR
The Bitwise NOT The OR operator, |, combines bits such that if
either of the bits in the operands is a 1, then
Also called the bitwise complement, the unary NOT
the resultant bit is a 1,
operator, ~, inverts all of the bits of its operand.
Example, Example:
The number : 42
Bit pattern : 00101010 00101010 42
After NOT OP is applied : 11010101 | 00001111 15
00101111 47
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 53
The Bitwise Operators (Cont…) // Demonstrate the bitwise logical operators.
class BitLogic {
The Bitwise XOR public static void main(String args[]) {
String binary[] = { "0000", "0001", "0010", "0011", "0100",
The XOR operator, ^, combines bits such that "0101", "0110", "0111", "1000", "1001", "1010", "1011",
if exactly one operand is 1, then the result is 1. "1100", "1101", "1110", "1111"
Otherwise, the result is zero. };
int a = 3; // 0 + 2 + 1 or 0011 in binary
Example:
int b = 6; // 4 + 2 + 0 or 0110 in binary
00101010 42
int c = a | b;
^ 00001111 15
int d = a & b;
00100101 37
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
[Link](" a = " + binary[a]);
Output: [Link](" b = " + binary[b]);
a = 0011 [Link](" a|b = " + binary[c]);
b = 0110 [Link](" a&b = " + binary[d]);
a|b = 0111 [Link](" a^b = " + binary[e]);
a&b = 0010 [Link]("~a&b|a&~b = " + binary[f]);
a^b = 0101 [Link](" ~a = " + binary[g]);
~a&b|a&~b = 0101 }}
12-10-2023
~a = 1100
Prepared By [Link] AP(SrG)/CSE(AIML) 54
The Bitwise Operators (Cont…)
The Left Shift The Right Shift
The left shift operator, <<, shifts all of the bits in a The right shift operator, >>, shifts all of the bits in a value to the
value to the left a specified number of times. right a specified number of times.
It has this general form: Its general form is shown here:
value << num value >> num
// Left shifting a byte value.
int a = 32;
class ByteShift {
a = a >> 2; // a now contains 8
public static void main(String args[]) {
byte a = 64, b;
int a = 35;
int i;
i = a << 2;
a = a >> 2; // a still contains 8
b = (byte) (a << 2);
[Link]("Original value of a: " + a);
Looking at the same operation in binary shows more
[Link]("i and b: " + i + " " + b);
clearly how this happens:
}
}
00100011 35
The output : >> 2
Original value of a: 64 00001000 8
i and b: 256 0
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 55
Relational Operators
The relational operators determine the relationship that one operand has to the other
The outcome of these operations is a boolean value.
Majorly used in Conditional and Looping Statements
NOTE:
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.
In Java, these statements must be written like this:
if(done == 0) ... // This is Java-style.
if(done != 0) ...
In Java, true and false are nonnumeric values that do not relate to zero or nonzero.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 56
Relational Operators (Cont…)
Boolean Logical Operators
The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators
combine two boolean values to form a resultant boolean value.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 57
Relational Operators (Cont…)
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
Output:
boolean d = a & b;
a = true
boolean e = a ^ b;
b = false
boolean f = (!a & b) | (a & !b);
a|b = true
boolean g = !a;
a&b = false
[Link](" a = " + a);
a^b = true
[Link](" b = " + b);
a&b|a&!b = true
[Link](" a|b = " + c);
!a = false
[Link](" a&b = " + d);
[Link](" a^b = " + e);
[Link]("!a&b|a&!b = " + f);
[Link](" !a = " + g);
}
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 58
The Assignment Operator
// Demonstrate ?.
The assignment operator is the single equal sign, =.
class Ternary {
Syntax:
public static void main(String args[]) {
var = expression; int i, k;
Example: i = 10;
int x, y, z; k = i < 0 ? -i : i; // get absolute value of i
x = y = z = 100; // set x, y, and z to 100 [Link]("Absolute value of ");
The ? Operator [Link](i + " is " + k);
i = -10;
Java includes a special ternary (three-way) operator k = i < 0 ? -i : i; // get absolute value of i
that can replace certain types of if-then-else [Link]("Absolute value of ");
statements. [Link](i + " is " + k);
Syntax: }
}
expression1 ? expression2 : expression3 output :
Absolute value of 10 is 10
Absolute value of -10 is 10
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 59
Control Statements
Java supports two selection statements: if and switch. These statements allow you to control the
flow of your program’s execution based upon conditions known only during run time
If and if else Statement
The if statement is Java’s conditional branch statement. It can be used to route program execution
through two different paths.
Syntax:
if (condition)
statement1;
else
statement2;
Nested ifs
The nested if statement represents the if block within another if block. Here, the inner if block condition executes only
when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
} }
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 60
Control Statements (cont…) // Demonstrate if-else-if statements.
class IfElse {
public static void main(String args[]) {
The if-else-if Ladder int month = 4; // April
String season;
A common programming construct that is based upon a
if(month == 12 || month == 1 || month == 2)
sequence of nested ifs is the if-else-if ladder.
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
Syntax: else if(month == 6 || month == 7 || month == 8)
if(condition) season = "Summer";
statement; else if(month == 9 || month == 10 || month == 11)
else if(condition) season = "Autumn";
statement; else
else if(condition) season = "Bogus Month";
statement; [Link]("April is in the " + season + ".");
... }
else }
statement;
output :
April is in the Spring.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 61
Control Statements (cont…) // A simple example of the switch.
class SampleSwitch {
Switch Statement public static void main(String args[]) {
for(int i=0; i<6; i++)
The switch statement is Java’s multiway branch
switch(i) {
statement.
case 0:
It often provides a better alternative than a large series
[Link]("i is zero.");
of if-else-if statements
Syntax: break;
switch (expression) { case 1:
case value1: [Link]("i is one."); i is zero.
// statement sequence break; i is one.
break; case 2: i is two.
case value2: [Link]("i is two."); i is three.
// statement sequence break; i is greater than 3.
break; case 3: i is greater than 3.
... [Link]("i is three.");
case valueN: break;
// statement sequence default:
break; [Link]("i is greater than 3.");
default: }}}
// default statement sequence
Note : default statement is optional
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 62
Iteration Statements
Java’s iteration statements are for, while, and do-while
It is also called as Loop
loop repeatedly executes the same set of instructions until a termination condition is met.
// Demonstrate the while loop.
While Loop class While {
public static void main(String args[]) {
The while loop is Java’s most fundamental loop int n = 10;
statement. It repeats a statement or block while(n > 0) {
while its controlling expression is true. [Link]("tick " + n); Output:
n--; tick 10
} tick 9
Syntax: } tick 8
while(condition) } tick 7
{ tick 6
// body of loop tick 5
} tick 4
tick 3
tick 2
tick 1
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 63
Iteration Statements (Cont..) // Demonstrate the do-while loop.
class DoWhile {
do-while Loop public static void main(String args[]) {
The do-while loop always executes its body at least int n = 10;
once, because its conditional expression is at the do {
bottom of the loop [Link]("tick " + n);
n--; Output:
Syntax: } while(n > 0); tick 10
do { } tick 9
// body of loop } tick 8
} while (condition); tick 7
tick 6
tick 5
tick 4
Each iteration of the do-while loop first executes the body of tick 3
the loop and then evaluates the conditional expression. tick 2
tick 1
If this expression is true, the loop will repeat. Otherwise, the
loop terminates.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 64
Iteration Statements (Cont..) Demonstrate the for loop.
class ForTick {
for Loop public static void main(String
args[]) {
The for loop operates as follows, int n;
➢ initialization portion of the loop is executed first for(n=10; n>0; n--)
➢ Next, condition is evaluated. This must be a Boolean expression [Link]("tick " + n);
➢ If this expression is true, then the body of the loop is executed. If }
it is false, the loop terminates. Output:
}
➢ Next, the iteration portion of the loop is executed- it increments tick 10
➢ or decrements the loop control variable. tick 9
tick 8
tick 7
Syntax: tick 6
tick 5
for(initialization; condition; iteration) { tick 4
// body tick 3
} tick 2
tick 1
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 65
Jump Statements // Using break to exit a loop.
class BreakLoop {
Java supports three jump statements: break, public static void main(String args[]) {
continue, and return. for(int i=0; i<100; i++) {
These statements transfer control to another if(i == 10) break; // terminate loop if i is 10
part of your program [Link]("i: " + i);
}
[Link]("Loop complete.");
Using break }
}
In Java, the break statement has three uses. Output:
i: 0
➢ it terminates a statement sequence in a switch statement
i: 1
➢ it can be used to exit a loop.
i: 2
➢ it can be used as a “civilized” form of goto.
i: 3
i: 4
i: 5
NOTE: i: 6
By using break, you can force immediate termination i: 7
of a loop, bypassing the conditional expression and any i: 8
remaining code in the body of the loop i: 9
Loop complete.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 66
Jump Statements (Cont…)
// Using break as a civilized form of goto.
Using break as a Form of Goto class Break {
public static void main(String args[]) {
Java does not have a goto statement boolean t = true;
break gives you the benefits of a goto first: {
second: {
Syntax: third: {
break label; [Link]("Before the break.");
if(t) break second; // break out of second block
[Link]("This won't execute");
}
[Link]("This won't execute");
}
[Link]("This is after second block.");
}
}
}
output:
Before the break.
This is after second block.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 67
Jump Statements (Cont…)
// Demonstrate continue.
Using continue class Continue {
public static void main(String args[]) {
Sometimes it is useful to force an early iteration of a for(int i=0; i<10; i++) {
loop. That is, you might want to continue [Link](i + " ");
running the loop but stop processing the remainder of if (i%2 == 0) continue;
the code in its body for this particular iteration [Link]("");
}
}
In while and do-while loops, a continue statement }
causes control to be transferred directly to the conditional Output :
expression that controls the loop. 01
23
45
In a for loop, control goes first to the iteration portion of the 67
for statement and then to the 89
conditional expression.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 68
Jump Statements (Cont…)
Using return
The return statement is used to explicitly return from
a method.
It causes program control to transfer back to the caller of the
method.
return statement immediately terminates the
method in which it is executed
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true; output
[Link]("Before the return."); Before the return
if(t) return; // return to caller
[Link]("This won't execute.");
}
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 69
TOPIC 5
Introducing Classes - Methods and Classes
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 70
Introducing Classes
class forms the basis for object-oriented programming in Java.
Any concept you wish to implement in a Java program must be encapsulated within a class.
The General Form of a Class
A class is declared by use of the class keyword The data, or variables, defined within a class are called instance
class classname variables
{
type instance-variable1; The code is contained within methods
type instance-variable2;
type instance-variableN; the methods and variables defined within a class are
type methodname1(parameter-list) { called members of the class
// body of method
} NOTE:
type methodname2(parameter-list) { ➢ Class is that it defines a new data Type
// body of method ➢ Once defined, this new type can be used to create objects of
} that type
type methodnameN(parameter-list) { ➢ A class is a template for an object, and an object is an instance
// body of method} of a class.
} ➢ The general form of a class does not specify a main( )
method.
➢ All Java classes do not need to have a main( ) method.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 71
Introducing Classes (Cont..) A Simple Class Example
/* A program that uses the Box class. Call this file
NOTE:
[Link]*/
➢ You should call the file that contains this program
class Box {
[Link], because the main( ) method is in the
double width;
class called BoxDemo, not the class called Box.
double height;
double depth;
➢ When you compile this program, you will find that two
}
.class files have been created, one for Box and one for
// This class declares an object of type Box.
BoxDemo.
class BoxDemo {
public static void main(String args[]) {
➢ To run this program, you must execute [Link].
Box mybox = new Box();
double vol;
➢ It is important to understand that changes to the instance
// assign values to mybox's instance variables
variables of one object have no effect on the instance
[Link] = 10;
variables of another.
[Link] = 20;
[Link] = 15;
// compute volume of box
vol = [Link] * [Link] * [Link]; output:
[Link]("Volume is " + vol); Volume is 3000.0
}}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 72
Introducing Classes (Cont..)
Declaring Objects
when you create a class, you are creating a new data type , You can use this type to declare objects of that type
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
➢ Second, you must acquire an actual, physical copy of the object and assign it to that variable
using the new operator.
Example:
Box mybox = new Box();
It can be rewritten as follows
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 73
Introducing Classes (Cont..)
A Closer Look at new
new operator dynamically allocates memory for an object
Syntax:
class-var = new classname( );
NOTE:
➢ 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
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 74
Introducing Classes (Cont..)
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an assignment takes place.
Example:
Box b1 = new Box();
Box b2 = b1;
after this fragment executes,
➢ b1 and b2 will both refer to the same object.
➢ The assignment of b1 to b2 did not allocate any memory or copy any part of the original object.
➢ It simply makes b2 refer to the same object as does b1.
➢ Thus, any changes made to the object through b2 will affect the object to which b1 is referring, since they are
the same object
NOTE:
Although b1 and b2 both refer to the same object, they are not linked in any other way.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 75
Introducing Methods
Classes usually consist of two things: instance variables and methods.
to add methods to your classes.
Syntax:
type name(parameter-list)
{
// body of method
}
➢ type specifies the type of data returned by the method
➢ The name of the method is specified by name (within the current scope)
➢ Parameters are essentially variables that receive the value of the arguments passed to the method
when it is called.
Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:
Syntax:
return value;
➢ Here, value is the value returned
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 76
Introducing Methods(Cont..)
class BoxDemo3 {
Adding a Method to the Box Class -Example public static void main(String args[]) {
Box mybox1 = new Box();
// This program includes a method inside the box class. Box mybox2 = new Box();
class Box { // assign values to mybox1's instance variables
double width; [Link] = 10;
double height; [Link] = 20;
double depth; [Link] = 15;
// display volume of a box /* assign different values to mybox2's
void volume() { instance variables */
[Link]("Volume is "); [Link] = 3;
[Link](width * height * depth); [Link] = 6;
} [Link] = 9;
} // display volume of first box
[Link]();
// display volume of second box
Output: [Link]();
Volume is 3000.0 }
Volume is 162.0 }
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 77
Introducing Methods(Cont..)
class BoxDemo4 {
Return a Method to the Box Class -Example public static void main(String args[]) {
Box mybox1 = new Box();
A better way to implement volume( ) is to have it Box mybox2 = new Box();
compute the volume of the box and return the result double vol;
to the caller. // assign values to mybox1's instance variables
class Box { [Link] = 10;
double width; [Link] = 20;
double height; [Link] = 15;
double depth; /* assign different values to mybox2's
// compute and return volume instance variables */
double volume() { [Link] = 3;
return width * height * depth; [Link] = 6;
} [Link] = 9;
} // get volume of first box
vol = [Link]();
[Link]("Volume is " + vol);
// get volume of second box
Output: vol = [Link]();
Volume is 3000.0 [Link]("Volume is " + vol);
Volume is 162.0 }
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 78
Introducing Methods(Cont..) class BoxDemo5 {
public static void main(String args[]) {
Adding a Method That Takes Parameters Box mybox1 = new Box();
Box mybox2 = new Box();
➢ Parameters allow a method to be generalized. double vol;
➢ a parameterized method can operate on a variety of data // initialize each box
and/or be used in a number of slightly different situations [Link](10, 20, 15);
[Link](3, 6, 9);
// This program uses a parameterized method.
// get volume of first box
class Box {
vol = [Link]();
double width;
[Link]("Volume is " + vol);
double height;
// get volume of second box
double depth;
vol = [Link]();
// compute and return volume
[Link]("Volume is " + vol);
double volume() {
}
return width * height * depth;
}
}
// sets dimensions of box
void setDim(double w, double h, double d) { Output:
width = w; Volume is 3000.0
height = h; Volume is 162.0
depth = d;
}}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 79
Introducing Methods(Cont..)
Constructors
➢ Java allows objects to initialize themselves when they are created.
➢ This automatic initialization 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 immediately after the object is created, before the new
operator completes.
/* Here, Box uses a constructor to initialize the dimensions of a box.*/ class BoxDemo6 {
class Box { public static void main(String args[]) {
double width;
// declare, allocate, and initialize Box objects
double height;
double depth; Box mybox1 = new Box();
// This is the constructor for Box. Box mybox2 = new Box();
Box() { double vol; Constructing Box
[Link]("Constructing Box"); // get volume of first box Constructing Box
width = 10; vol = [Link]();
height = 10;
Volume is 1000.0
[Link]("Volume is " + vol); Volume is 1000.0
depth = 10;
// get volume of second box
}
// compute and return volume vol = [Link]();
double volume() { [Link]("Volume is " + vol);
return width * height * depth; }
} }
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 80
Introducing Methods(Cont..)
Parameterized Constructors
each object is initialized as specified in the parameters to its constructor.
/* Here, Box uses a parameterized constructor to class BoxDemo7 {
initialize the dimensions of a box. public static void main(String args[]) {
*/ // declare, allocate, and initialize Box objects
class Box { Box mybox1 = new Box(10, 20, 15);
double width; Box mybox2 = new Box(3, 6, 9);
double height; double vol;
double depth; // get volume of first box
// This is the constructor for Box. vol = [Link]();
Box(double w, double h, double d) { [Link]("Volume is " + vol);
width = w; // get volume of second box
height = h; vol = [Link]();
depth = d; [Link]("Volume is " + vol);
} }
// compute and return volume }
double volume() {
Output:
return width * height * depth;
Volume is 3000.0
}
Volume is 162.0
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 81
Introducing Methods(Cont..)
The this Keyword
➢ Sometimes a method will need to refer to the object that invoked it.
➢ To allow this, Java defines the this keyword.
➢ this can be used inside any method to refer to the current object.
➢ That is, this is always a reference to the object on which the method was invoked.
Instance Variable Hiding
➢ It is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes.
➢ you can have local variables, including formal parameters to methods, which overlap with the names of the class’
instance variables.
➢ when a local variable has the same name as an instance variable, the local variable hides the instance variable.
Example
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
12-10-2023 Prepared By [Link] AP(SrG)/CSE(AIML) 82