FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
1
Unit : 1 : Object Oriented Programming And Introduction To Java, Data Types,
Operators, Statements And Defining Classes In Java Sr. No Topic Page No. 1.1 Java Introduction & Installation 1 to 12
1.2 Why Java is So Popular ? OR Features of Java 12 to 15
1.3 Features of Object – Oriented Programming 15 to 17
1.4 Creating an Application in Java 17
1.5 Compiling and Executing Applications in Java 18 to 19
1.6 Lexical Issues 19 to 20
1.7 Using Command Line Arguments 20 to 21
1.8 Program comments in Java 21
1.9 Primitive Data Types 21 to 27
• Numeric Data Types byte short int long
• Floating Point Data Types float double
• char
• boolean
1.10 Conversion of Numeric Types 27 to 29
Widening Conversion Narrowing Conversion Mixed Conversion
1.11 Infinities and NaNs for floating point types 29 to 32
1.12 What is Unicode in Java? 32
1.13 Specifying Constants / Literals for different data types in Java 32
1.14 Unicode Escapes in Java Source Code 32
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
2
1.15 Reference Data Types 33 to 37
• Arrays
• Classes
• Interfaces
• Enum
• Annotation
1.16 Arrays 37 to 41
• One Dimensional Array
• Multi‐Dimensional Array
1.17 Understanding Super – Types and Sub ‐ Types in Java 42
OR Super‐type and sub‐type relations in primitive data types
1.18 Operators 43 to 55
• Arithmetic Operators
• String Concatenation
• Relational Operators
• Logical Operators
• Bitwise Operators
• Increment ‐ Decrement Operators
• Conditional Operator
• Assignment Cast operators
• instanceof operator
• Other Operators ( new , [ ] , . (dot) )
1.19 Statements 55 to 62
• Condition Statements if if‐else switch‐case
• Loop Statements for while do‐while
• break simple break labelled break
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
3
• continue simple continue labelled continue
• return
1.20 Various Members within a class 63 to 94
• Instance Variables
• Methods Overloading Methods Using Objects as Parameters A Closer Look at Argument Passing
Pass‐by‐reference Pass‐by‐value
Returning Objects Recursion
• Constructors Overloading Constructors
• Uses of this keyword Accessing current instance using this keyword Invoking a constructor of the same class using this keyword
• Garbage collector and finalize() method
• static variables
• static methods
• static block / Class Initializer Block
• Initializer Block
1.21 Read value from keyboard 93
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
4
1.1 Java Introduction & Installation:
History of Sun Microsystem History of Java How Will Java Technology Change My Life? The Java Programming Language / Java Buzzwords Setup Development Environment Download JDK Install JDK Set Environment Variable Directory Structure
History of Java
1982: Getting Started
Incorporated in February 1982, with four employees: Scott McNealy, Vinod Khosla, Bill Joy, and Andy Bechtolsheim. All four the original founders of SUN. The name SUN is an acronym for the Stanford University Network
First workstation introduced. It includes TCP/IP, now known as the Internet protocol suite.
1993: One Million and Counting
In just over 10 years, Sun reaches an incredible milestone‐‐one million systems shipped.
Sun makes its debut on the Fortune 500.
Years of leadership pay off: Sun, IBM, HP, and others unify UNIX system software.
1995: The Java Technology Revolution Begins
Sun introduces the first universal software platform, designed from the ground up for the Internet and corporate intranets. Java technology enables developers to write applications once to run on any computer.
According to James Gosling, "the goal was to build a system that would let us do a large, distributed, heterogeneous network of consumer electronic devices all talking to each other." With this goal in mind, the stealth group began work.
"It's difficult to find a good name for a programming language, as the team discovered after many hours of brainstorming. Finally, inspiration struck one day during a trip to the local coffee shop" Gosling recalls. Others have speculated that the name Java came from several individuals involved in the project: James gosling, Arthur Van hoff, Andy bechtolsheim.
Releases Event Month Year Java 1.5.0_09 October 2006
Java 1.5.0_08 August 2006
Java 1.5.0_06 December 2005
Java 1.5.0_05 October 2005
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
5
Java 1_5_0_04 July 2005
Java 1_5_0_01 February 2005
Java 2 Platform, Standard Edition 1.4 (J2SE 1.4) February 2002
Java 2 Platform, Standard Edition 1.3 (J2SE 1.3) May 2000
Java 2 Platform, Enterprise Edition (J2EE) December 1999
Java 2 Platform, Standard Edition (J2SE) August 1999
Java Development Kit 1.2 (JDK 1.2) December 1998
Java Development Kit 1.1 (JDK 1.1) February 1997
Java Development Kit 1.0 (JDK 1.0) January 1996
How Will Java Technology Change My Life?
We can't promise you fame, fortune, or even a job if you learn the Java programming language. Still, it is likely to make your programs better and requires less effort than other languages. We believe that Java technology will help you do the following:
• Get started quickly: Although the Java programming language is a powerful object‐oriented language, it's easy to learn, especially for programmers already familiar with C or C++.
• Write less code: Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in the Java programming language can be four times smaller than the same program written in C++.
• Write better code: The Java programming language encourages good coding practices, and automatic garbage collection helps you avoid memory leaks. Its object orientation,
• Develop programs more quickly: The Java programming language is simpler than C++, and as such, your development time could be up to twice as fast when writing in it. Your programs will also require fewer lines of code.
• Avoid platform dependencies: You can keep your program portable by avoiding the use of libraries written in other languages.
• Write once, run anywhere: Because applications written in the Java programming language are compiled into machine‐independent bytecodes, they run consistently on any Java platform.
• Distribute software more easily: With Java Web Start software, users will be able to launch your applications with a single click of the mouse. An automatic version check at startup ensures that users are always up to date with the latest version of your software. If an update is available, the Java Web Start software will automatically update their installation.
The Java Programming Language
The Java programming language is a high‐level language that can be characterized by all of the following buzzwords:
• Simple • Architecture neutral
• Object oriented • Portable
• Distributed • High performance
• Multithreaded • Robust
• Dynamic • Secure
Each of the preceding buzzwords is explained in The Java Language Environment , a white paper written by James Gosling and Henry McGilton.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
6
In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes — the machine language of the Java Virtual Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.
An overview of the software development process.
Because the Java VM is available on many different operating systems, the same .class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.
Through the Java VM, the same application is capable of running on multiple platforms.
The Java Platform
A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software‐only platform that runs on top of other hardware‐based platforms.
The Java platform has two components:
• The Java Virtual Machine
• The Java Application Programming Interface (API)
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
7
You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware‐based platforms.
The API is a large collection of ready‐made software components that provide many useful capabilities. It is grouped into
libraries of related classes and interfaces; these libraries are known as packages.
The API and Java Virtual Machine insulate the program from the underlying hardware.
As a platform‐independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.
Setup Development Environment
1. Download JDK Open URL http://java.sun.com/javase/downloads/widget/jdk6.jsp
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
8
2. Install JDK
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
9
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
10
e
3. Set Environment Variable in Windows
Right Click on My Computer ‐ > Properties
Click on Environment Variable
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
11
Now, Select “Path” Variable in System Variable list and click “Edit”
Add C:\Program Files\Java\jdk1.6.0_11\bin; at last of path value (Path for JDK installation)
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
12
Click “OK”.. Click “Ok”.. Click “OK”…
4. Let’s Test Environment Variable Goto Start‐>Run>Cmd and Type Javac
Directory Structure
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
13
Jre directory: When you run any java program then you have to compile it by the help of Java interpreter or Java Runtime Environment (JRE). The SDK uses the internal adaptation of JRE, which containing in the jre root directory
Lib directory: This is a most important directory for development tools that contains libraries and it's supported files.
Docs directory: It is the last directory of Software Development Kit that assists you to store the Java documents. The docs directory is an optional directory.
scr.zip: The zip file is a collection of one of more files that has been compressed or stored to '.zip' extension. Similarly, the scr.sip file contains the source code of SDK. It becomes necessary to extract the file that contains the source code from the ZIP file.
1.2 Why Java is So Popular ? OR Features of Java • Platform Independent
• Simple
• Object ‐ Oriented
• Robust
• Distributed
• Portable
• Dynamic
• Secure
• Performance
• Multithreaded
• Interpreted
• Architecture Neutral
• Exception handling support
• Provides applets and servlets for use on the Web
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
14
Platform Independent
• The concept of Write‐once‐run‐anywhere is known as the Platform independent. • Platform independent is one of the important key feature of java language that makes java as the most
powerful language. • Not even a single language is idle to this feature but java is more closer to this feature. • The programs written on one platform can run on any platform provided the platform must have the JVM. • Platform independent means the execution of the program is not restricted by the type of os environment
provided...thereby, make it possible to process the program at any type of environement available. • Java is a platform independent language becoz of the bytecode magic of java. • In java, when we execute the source code...it generates the .class file comprising the bytecodes. Bytecodes
are easily interpreted by JVM which is available with every type of OS we install. • Whereas C and C++ are complied languages which makes them platform dependent. The source code
written in C / C++ gets transformed into an object code which is machine and OS dependent. That's the reason why C and C++ languages are termed as Platform Dependent.
Compilation and Execution for Java
Simple • There are various features that makes the java as a simple language. • Programs are easy to write and debug because java does not use the pointers explicitly. • It is much harder to write the java programs that can crash the system but we can not say about the other
programming languages. • Java provides the bug free system due to the strong memory management. It also has the automatic
memory allocation and deallocation system. Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.
run
interpret
Compile
Java Code
Java Bytecode
JVM
Platform
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
15
• Inheritance :
It is the process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding the additional features as needed.
• Encapsulation: : It is the mechanism of combining the information and methods and providing the abstraction.
• Polymorphism: : As the name suggest one name multiple form, Polymorphism is the way of providing the different
functionality by the functions having the same name based on the signatures of the methods.
• Dynamic binding : Sometimes we don't have the knowledge of objects about their specific types while writing our
code. It is the way of providing the maximum functionality to a program about the specific type at runtime.
NOTE : As the languages like Objective C, C++ fulfills the above four characteristics yet they are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java, it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.
Robust • Java has the strong memory allocation and automatic garbage collection mechanism. • It provides the powerful exception handling and type checking mechanism as compare to other
programming languages. • Compiler checks the program whether there is any error and interpreter checks any run time error and
makes the system secure from crash. • All of the above features makes the java language robust.
Distributed
• The widely used protocols like HTTP and FTP are developed in java. • Internet programmers can call functions on these protocols and can get access the files from any remote
machine on the internet rather than writing codes on their local system.
Portable • The feature Write‐once‐run‐anywhere makes the java language portable provided that the system must
have interpreter for the JVM. • Java also have the standard data size irrespective of operating system or the processor. These features
makes the java as a portable language.
Dynamic • While executing the java program the user can get the required files dynamically from a local drive or from
a computer thousands of miles away from the user just by connecting with the Internet. Secure
• Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box.
• Security manager determines the accessibility options of a class like reading and writing a file to the local disk.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
16
• Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form.
• The bytecode Verifier checks the classes after loading.
Performance • Java uses native code usage, and lightweight process called threads. • In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM
uses the adaptive and just in time compilation technique that improves the performance.
Multithreaded
• As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded.
• Java is also a Multithreaded programming language. • Multithreading means a single program having different threads executing independently at the same
time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer.
• Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs.
Interpreted • We all know that Java is an interpreted language as well. With an interpreted language such as Java,
programs run directly from the source code. • The interpreter program reads the source code and translates it on the fly into computations. • Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. • The source code to be written and distributed is platform independent. • Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error
occurring in the program gets traced. This is how it is different to work with Java.
Architecture Neutral • The term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. • The growing popularity of networks makes developers think distributed. In the world of network it is
essential that the applications must be able to migrate easily to different computer systems. • Not only to computer systems but to a wide variety of hardware architecture and Operating system
architectures as well. • The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine
and to be easily translated into native machine code on the fly. • The compiler generates an architecture‐neutral object file format to enable a Java application to execute
anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system.
• Hence Java was designed to support applications on network. This feature of Java has thrived the programming language.
1.3 Features of Object – Oriented Programming
• Object‐oriented programming is at the core of Java. In fact, all Java programs are object‐oriented ‐ this isn’t an option the way that it is in C++, for example.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
17
• OOP is so integral to Java that you must understand its basic principles before you can write even simple Java programs.
• 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 controlling access to code.
Class • A class defines the structure and behavior (data and code) that will be shared by a set of objects. • In object‐oriented programming , a class is a template definition of the method s and variable s in a
particular kind of object . Thus, an object is a specific instance of a class; it contains real values instead of variables.
• The class is one of the defining ideas of object‐oriented programming.
Object • 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. • A class is not an object. (but it’s used to construct them)
Inheritance • Inheritance in OOP allows to define a general class and later to organize some other classes simply adding
some details with the old class definition. • This saves work as the special class inherits all the properties of the old general class and as a programmer
you only require the new features. • This helps in a better data analysis, accurate coding and reduces development time. • This is the mechanism of organizing and structuring software program. • Though objects are distinguished from each other by some additional features but there are objects that
share certain things common. • In object oriented programming classes can inherit some common behavior and state from others.
Abstraction • Abstraction refers to the act of representing essential features without including the background details or
explanations. • The process of abstraction in Java is used to hide certain details and only show the essential features of the
object. • In other words, it deals with the outside view of an object (interface).
Encapsulation
• The wrapping of data and methods into a single unit (a class) is known as encapsulations. • This is an important programming concept that assists in separating an object's state from its behavior.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
18
• This helps in hiding an object's data describing its state from any further modification by external component.
• In Java there are three different terms used for hiding data constructs and these are public, private and protected.
• It can also be termed as information hiding that prohibits outsiders in seeing the inside of an object in which abstraction is implemented.
Polymorphism • Polymorphism means the ability to take more than one form. • It describes the ability of the object in belonging to different types with specific behavior of each type. • So by using this, one object can be treated like another and in this way it can create and define multiple
level of interface. • Here the programmers need not have to know the exact type of object in advance and this is being
implemented at runtime.
1.4 Creating an Application in Java /* This is a simple Java program. Call this file "MyFirstApp.java". */ class MyFirstApp {
// Your program begins with a call to main(). public static void main(String args[]) {
System.out.println("This is a simple Java program."); }
} • In Java, methods are defined inside some class. Therefore, we need to define a class, which will contain the
method main(). • The classes in Java are always defined in a file with extension “.java”. • So above file will be named as MyFirstApp.java • public static void main(String args[]) {
This line begins the main( ) method. As the comment preceding it suggests, this is the line at which the program will begin executing. All Java applications begin execution by calling main( ).
• The public keyword is an access specifier, which allows the programmer to control the visibility of class members.
• In this case, main( ) must be declared as 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 interpreter before any objects are made.
• The keyword void simply tells the compiler that main( ) does not return a value. As you will see, methods may also return values. If all this seems a bit confusing, don’t worry.
• main( ) is simply a starting place for your program. A complex program will have dozens of classes, only one of which will need to have a main( ) method to get things started.
• Keep in mind that Java is case‐sensitive. Thus, Main is different from main. • String args[ ] declares a parameter named args, which is an array of instances of the class String. This will be
referred as the command line arguments. • System.out.println("This is a simple Java program.");
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
19
This line outputs the string “This is a simple Java program.” followed by a new line on the screen. Output is actually accomplished by the built‐in println( ) method. In this case, 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.
• Notice that the println( ) statement ends with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in the program do not end in a semicolon is that they are not, technically, statements.
1.5 Compiling and Executing Applications in Java
1. Go to Start‐>Run‐>cmd‐>edit
2. Type Simple program
3. Save and Close Editor
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
20
4. Compile and Run
Javac (Java Compiler)
• The javac compiler creates a file called MyFirstApp.class that contains bytecode version of the program.
• Java Bytecode is the intermediate representation of your program that contains instructions the Java Interpreter will execute.
• Thus, the output of Javac is not code that can be directly executed.
Java (Java Interpreter)
• When you execute java interpreter, you are actually specifying name of that class that you want interpreter to execute.
• It automatically searches for a file by that name that has the .class extension eg. Java MyFirstApp will search MyFirstApp.class file.
• If it finds the file, it will execute code contained in specified class.
1.6 Lexical Issues • Java programs are a collection of whitespace, identifiers, comments, literals, operators, separators, and
keywords. Whitespace
• In Java, you do not need to follow any special indentation rules. For example, the java program could have been written all on one line or in any other strange way you felt like typing it, as long as there was at least
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
21
one whitespace character between each token that was not already delineated by an operator or separator.
• 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 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.
• Again, Java is case‐sensitive, so VALUE is a different identifier than Value. Some examples of valid identifiers are: Valid : I, hello, $num , I_am_Variable Invalid: 10i ,hello‐java, And/Or
Separators In Java, there are a few characters that are used as separators.
Symbol Name Purpose ( ) Parentheses Used to contain lists of parameters in method definition and invocation.
Also used for defining precedence in expressions, containing expressions in control statements, and surrounding cast types.
{ } Braces Used to contain the values of automatically Initialized arrays. Also used to define a block of code, for classes, methods, and local scopes.
[] Brackets Used to declare array types. Also used when dereferencing array values. ; Semicolon Terminates statements. , Comma Separates consecutive identifiers in a variable
. Period Used to separate package names from subpackages and classes. Also used to separate a variable or method from a reference variable.
The Java Keywords There are 49 reserved keywords currently defined in the Java language. These keywords cannot be used as names for a variable, class, or method. Data Type: boolean, byte, char, double, float, int, long, short Control: break, case, continue, default, do, else, for, goto, if, return, switch, while. Exception: catch, throw, throws, try, finally. Class: abstract, class, extends, implements, import, interface, native, strictfp, super, this, new, package Access Control: public, private, protected, Others : assert, const, final, instanceof, static, synchronized, transient, void, volatile
The keywords const and goto are reserved but not used. Java reserves the following: true, false, and null
1.7 Using Command Line Arguments
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
22
• 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. • To access the command‐line arguments inside a Java program is quite easy—they are stored as strings in
the String array passed to main( ). • For example, the following program displays all of the command‐line arguments that it is called with:
// Display all command‐line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]);
} } Try executing this program, as shown here:
1.8 Program comments in Java
• There are three types of comments defined by Java. 1. Single‐line: / / I am single line comment 2. Multiline: /* I am multiple line comment */ 3. Documentation comment: This type of comment is used to produce an HTML file that
documents your program. The documentation comment begins with a /** and ends with a */.
1.9 Primitive Data Types
• Numeric Data Types byte short int long
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
23
• Floating Point Data Types float double
• char
• boolean Java defines eight simple (or elemental) types of data: byte, short, int, long, float, double, char and boolean. These can be put in four groups:
• Numeric Data Types: This group includes byte, short, int, and long, which are for whole‐valued signed numbers.
• Floating‐point: This group includes float and double, which represent numbers with fractional precision. • Characters: This group includes char, which represents symbols in a character set, like letters and numbers. • Boolean: This group includes boolean, which is a special type for representing true/false values.
Numeric Data Types • Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative
values. Name Width Range long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 –2,147,483,648 to 2,147,483,647 short 16 –32,768 to 32,767 byte 8 –128 to 127
Example public class test{ public static void main(String args[]){
int i = 50; long l = 123456; short s = 500; byte b = 128; System.out.println(“int:”+I +”\nlong:”+l+”\nshort:”+s+”\nbyte:”+b);
} }
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
24
WHY?
public class test{ public static void main(String args[]){
int i = 50; long l = 123456; short s = 500; byte b = 127; System.out.println(“int:”+I +”\nlong:”+l+”\nshort:”+s+”\nbyte:”+b);
} }
Floating‐Point Types
• Floating‐point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision
• Java implements the standard (IEEE–754) set of floating‐point types and operators Name Width Approximate Range double 64 4.9e–324 to 1.8e+308 float 32 1.4e−045 to 3.4e+038
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
25
Example
// Compute the area of a circle. class Area {
public static void main(String args[]) { float pi, r double 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);
} }
Why? // Compute the area of a circle.
class Area { public static void main(String args[]) {
float pi, r double a;
r = 10.8f; // radius of circle
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
26
pi = 3.1416f; // pi, approximately a = pi * r * r; // compute area System.out.println("Area of circle is " + a);
} }
Characters
• In Java, the data type used to store characters is char • char is an integer type that is 8 bits wide. This is not the case in Java. Instead, 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.
• The range of a char is 0 to 65,536. • There are no negative chars. • The standard set of characters known as ASCII still ranges from 0 to 127 as always • The extended 8‐bit character set, ISO‐Latin‐1, ranges from 0 to 255. Since Java is designed to allow
applets to be written for worldwide use
Example
// Demonstrate char data type. class CharDemo {
public static void main(String args[]) { char ch1, ch2, ch3; ch1 = 88; ch2 = 'Y';
ch3 = ‘\u00F6’; //value of 00F6 = ÷ System.out.print("ch1:" + ch1); System.out.print("ch2:" + ch2); System.out.print("ch3:" + ch3);
ch2 ++; System.out.print("ch2:" + ch2);
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
27
} }
Booleans
• Java has a simple type, called boolean, for logical values. It can have only one of two possible values, true or false.
Example
class BoolTest { public static void main(String args[]) {
boolean b; b = false; System.out.println("b is " + b); b = true; System.out.println("b is " + b); // a boolean value can control the if statement if(b) System.out.println("This is executed."); b = false; if(b) System.out.println("This is not executed."); // outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9));
} }
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
28
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 initialize. Declaring a Variable type identifier [ = value][, identifier [= value] ...] ; 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'.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
29
The Scope and Lifetime of Variables
• Most other computer languages define two general categories of scopes: global and local.
• However, these traditional scopes do not fit well with Java’s strict, object oriented model.
• In Java, the two major scopes are those defined by a class and those defined by a method
• Scopes can be nested.
1.10 Conversion of Numeric Types
• There are various types of conversions for numeric types, like Widening Conversion Narrowing Conversion Mixed Conversion
Widening Primitive Conversion
• The widening conversion is the conversion of a sub‐type to one of its super‐types. • The following are specific conversions on primitive types & are called the widening primitive conversions:
byte to short, int, long, float, or double short to int, long, float, or double char to int, long, float, or double int to long, float, or double long to float or double float to double
• Widening primitive conversions do not lose information about the overall magnitude of a numeric value. • Indeed, conversions widening from an integral type to another integral type and from float to double do
not lose any information at all; the numeric value is preserved exactly. • Here is an example of a widening conversion that loses precision:
class Test { public static void main(String[] args) { int big = 1234567890; float approx = big; System.out.println(big ‐ (int)approx); } } output
‐46
Narrowing Conversion
The narrowing conversion occurs from a type to a different type that has a smaller size, such as from a long (64 bits) to an int (32 bits).
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
30
In general, the narrowing primitive conversion can occur in these cases:
1. short to byte or char 2. char to byte or short 3. int to byte, short, or char 4. long to byte, short, or char 5. float to byte, short, char, int, or long 6. double to byte, short, char, int, long, or float
• The narrowing primitive conversion must be explicit. • You need to specify the target type in parentheses.
public class MainClass { public static void main(String[] args) { long a = 10; int b = (int) a; // narrowing conversion System.out.println(a); System.out.println(b); } } Mixed Conversion
• A mixed conversion is the conversion that involves first a widening conversion followed by a narrowing conversion.
• For numeric types, the following are the cases for mixed conversions: o char to byte or short o short to char o byte to char
• The mixed conversion involve the conversion of char with the other two sub‐types of int. • In these conversion, first a widening conversion is done to the int type and then the narrowing conversion
is done to the target type.
1.11 Infinities and NaNs for floating point types OR
What Are Floating Point Numbers? • There are several ways to represent real numbers on computers. Fixed point places a radix point
somewhere in the middle of the digits, and is equivalent to using integers that represent portions of some unit. For example, one might represent 1/100ths of a unit; if you have four decimal digits, you could represent 10.82, or 00.01. Another approach is to use rationals, and represent every number as the ratio of two integers.
• Floating‐point representation ‐ the most common solution ‐ basically represents reals in scientific notation. Scientific notation represents numbers as a base number and an exponent. For example, 123.456 could be represented as 1.23456 × 102. In hexadecimal, the number 123.abc might be represented as 1.23abc × 162.
• Floating‐point solves a number of representation problems. Fixed‐point has a fixed window of representation, which limits it from representing very large or very small numbers. Also, fixed‐point is prone to a loss of precision when two large numbers are divided.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
31
• Floating‐point, on the other hand, employs a sort of "sliding window" of precision appropriate to the scale of the number. This allows it to represent numbers from 1,000,000,000,000 to 0.0000000000000001 with ease.
Storage Layout • IEEE floating point numbers have three basic components: the sign, the exponent, and the mantissa. The
mantissa is composed of the fraction and an implicit leading digit (explained below). The exponent base (2) is implicit and need not be stored.
• The following figure shows the layout for single (32‐bit) and double (64‐bit) precision floating‐point values. The number of bits for each field are shown (bit ranges are in square brackets):
Sign Exponent Fraction Bias
Single Precision 1 [31] 8 [30‐23] 23 [22‐00] 127
Double Precision 1 [63] 11 [62‐52] 52 [51‐00] 1023
The Sign Bit • The sign bit is as simple as it gets. 0 denotes a positive number; 1 denotes a negative number. Flipping the
value of this bit flips the sign of the number. The Exponent
• The exponent field needs to represent both positive and negative exponents. To do this, a bias is added to the actual exponent in order to get the stored exponent. For IEEE single‐precision floats, this value is 127. Thus, an exponent of zero means that 127 is stored in the exponent field. A stored value of 200 indicates an exponent of (200‐127), or 73. For reasons discussed later, exponents of ‐127 (all 0s) and +128 (all 1s) are reserved for special numbers.
• For double precision, the exponent field is 11 bits, and has a bias of 1023. The Mantissa
• The mantissa, also known as the significand, represents the precision bits of the number. It is composed of an implicit leading bit and the fraction bits.
• To find out the value of the implicit leading bit, consider that any number can be expressed in scientific notation in many different ways. For example, the number five can be represented as any of these:
5.00 × 100 , 0.05 × 102 , 5000 × 10‐3
• In order to maximize the quantity of representable numbers, floating‐point numbers are typically stored in normalized form. This basically puts the radix point after the first non‐zero digit. In normalized form, five is represented as 5.0 × 100.
• A nice little optimization is available to us in base two, since the only possible non‐zero digit is 1. Thus, we can just assume a leading digit of 1, and don't need to represent it explicitly. As a result, the mantissa has effectively 24 bits of resolution, by way of 23 fraction bits.
Putting it All Together So, to sum up:
1. The sign bit is 0 for positive, 1 for negative. 2. The exponent's base is two. 3. The exponent field contains 127 plus the true exponent for single‐precision, or 1023 plus the true exponent
for double precision. 4. The first bit of the mantissa is typically assumed to be 1.f, where f is the field of fraction bits.
Ranges of Floating‐Point Numbers • Let's consider single‐precision floats for a second. Note that we're taking essentially a 32‐bit number and re‐jiggering
the fields to cover a much broader range. Something has to give, and it's precision. For example, regular 32‐bit integers, with all precision centered around zero, can precisely store integers with 32‐bits of resolution. Single‐
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
32
precision floating‐point, on the other hand, is unable to match this resolution with its 24 bits. It does, however, approximate this value by effectively truncating from the lower end. For example:
11110000 11001100 10101010 00001111 // 32‐bit integer = +1.1110000 11001100 10101010 x 231 // Single‐Precision Float = 11110000 11001100 10101010 00000000 // Corresponding Value
• This approximates the 32‐bit value, but doesn't yield an exact representation. On the other hand, besides the ability to represent fractional components (which integers lack completely), the floating‐point value can represent numbers around 2127, compared to 32‐bit integers maximum value around 232.
• The range of positive floating point numbers can be split into normalized numbers (which preserve the full precision of the mantissa), and denormalized numbers (discussed later) which use only a portion of the fractions's precision.
Denormalized Normalized Approximate Decimal
Single Precision ± 2‐149 to (1‐2‐23)×2‐126 ± 2‐126 to (2‐2‐23)×2127 ± ~10‐44.85 to ~1038.53
Double Precision ± 2‐1074 to (1‐2‐52)×2‐1022 ± 2‐1022 to (2‐2‐52)×21023 ± ~10‐323.3 to ~10308.3
• Since the sign of floating point numbers is given by a special leading bit, the range for negative numbers is given by the negation of the above values.
• There are five distinct numerical ranges that single‐precision floating‐point numbers are not able to represent:
1. Negative numbers less than ‐(2‐2‐23) × 2127 (negative overflow) 2. Negative numbers greater than ‐2‐149 (negative underflow) 3. Zero 4. Positive numbers less than 2‐149 (positive underflow) 5. Positive numbers greater than (2‐2‐23) × 2127 (positive overflow) • Overflow means that values have grown too large for the representation, much in the same way that you
can overflow integers. Underflow is a less serious problem because is just denotes a loss of precision, which is guaranteed to be closely approximated by zero.
• Here's a table of the effective range (excluding infinite values) of IEEE floating‐point numbers:
Binary Decimal
Single ± (2‐2‐23) × 2127 ~ ± 1038.53
Double ± (2‐2‐52) × 21023 ~ ± 10308.25
Note that the extreme values occur (regardless of sign) when the exponent is at the maximum value for finite numbers (2127 for single‐precision, 21023 for double), and the mantissa is filled with 1s (including the normalizing 1 bit).
Special Values • IEEE reserves exponent field values of all 0s and all 1s to denote special values in the floating‐point scheme.
Zero • As mentioned above, zero is not directly representable in the straight format, due to the assumption of a
leading 1 (we'd need to specify a true zero mantissa to yield a value of zero). Zero is a special value denoted with an exponent field of zero and a fraction field of zero. Note that ‐0 and +0 are distinct values, though they both compare as equal.
Denormalized • If the exponent is all 0s, but the fraction is non‐zero (else it would be interpreted as zero), then the value is
a denormalized number, which does not have an assumed leading 1 before the binary point. Thus, this
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
33
represents a number (‐1)s × 0.f × 2‐126, where s is the sign bit and f is the fraction. For double precision, denormalized numbers are of the form (‐1)s × 0.f × 2‐1022. From this you can interpret zero as a special type of denormalized number.
Infinity • The values +infinity and ‐infinity are denoted with an exponent of all 1s and a fraction of all 0s. The sign bit
distinguishes between negative infinity and positive infinity. Being able to denote infinity as a specific value is useful because it allows operations to continue past overflow situations. Operations with infinite values are well defined in IEEE floating point.
Not A Number • The value NaN (Not a Number) is used to represent a value that does not represent a real number. NaN's
are represented by a bit pattern with an exponent of all 1s and a non‐zero fraction. There are two categories of NaN: QNaN (Quiet NaN) and SNaN (Signalling NaN).
• A QNaN is a NaN with the most significant fraction bit set. QNaN's propagate freely through most arithmetic operations. These values pop out of an operation when the result is not mathematically defined.
• An SNaN is a NaN with the most significant fraction bit clear. It is used to signal an exception when used in operations. SNaN's can be handy to assign to uninitialized variables to trap premature usage.
Semantically, QNaN's denote indeterminate operations, while SNaN's denote invalid operations.
Special Operations • Operations on special numbers are well‐defined by IEEE. In the simplest case, any operation with a NaN
yields a NaN result. Other operations are as follows:
Operation Result
n ÷ ±Infinity 0
±Infinity × ±Infinity ±Infinity
±nonzero ÷ 0 ±Infinity
Infinity + Infinity Infinity
±0 ÷ ±0 NaN
Infinity ‐ Infinity NaN
±Infinity ÷ ±Infinity NaN
±Infinity × 0 NaN
1.12 What is Unicode in Java?
• Unicode is a character set that has characters from all the languages of the world. • There are various versions of the unicode character set. • It has several character encoding forms, UTF standing for Unicode Transformation Unit:
o UTF‐8: only uses one byte (8 bits) to encode English characters. It can use a sequence of bytes to encode the other characters. UTF‐8 is widely used in email systems and on the Internet.
o UTF‐16: uses two bytes (16 bits) to encode the most commonly used characters. If needed, the additional characters can be represented by a pair of 16‐bit numbers.
o UTF‐32: uses four bytes (32 bits) to encode the characters. It became apparent that as the Unicode standard grew a 16‐bit number is too small to represent all the characters. UTF‐32 is capable of representing every Unicode character as one number.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
34
How Does Java Use Unicode? • Java was created around the time when the Unicode standard had values defined for a much smaller set of
characters. Back then it was felt that 16‐bits would be more than enough to encode all the characters that would ever be needed. With that in mind Java was designed to use UTF‐16. In fact, the char data type was originally used to be able to represent a 16‐bit Unicode code point.
• Since Java SE v5.0, the char now represents a code unit. It makes little difference for representing characters that are in the basic multilingual plane because the value of the code unit is the same as the code point. It does mean that for the characters on the other planes two chars are needed. The important thing to remember is a single char data type can no longer represent all the Unicode characters.
1.13 Specifying Constants / Literals for different data types in Java • A constant value in Java is created by using a literal representation of it. For example,
100 : Integer literal 12.25f : float literal 100.12 : double literal ‘J’ : character literal true : boolean literal “Hello Java” : String literal 0x10 : hex literal 010 : Octal literal
1.14 Unicode Escapes in Java Source Code / Character Literals
1.15 Reference Data Types What is reference data type ?
• In Java, a reference data type is a variable that can contain the reference or an address of dynamically created object.
• These type of data types are not predefined like primitive data type. • The reference data types are :
Classes Arrays Interfaces
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
35
Enum Annotation
• These are made and handle according to a programmer in a java program which can hold the values like:
array type // Points to an array instance
class type // Points to an object or a class instance
interface type // Points to an object and a method, which is implemented to the corresponding interface etc..
• Because objects are passed by reference, two different variables may refer to the same object:
Button p, q; p = new Button(); // p refers to a Button object. q = p; // q refers to the same Button. p.setLabel("Ok"); // A change to the object through p... String s = q.getLabel(); // ...is also visible through q. // s now contains "Ok."
This is not true of primitive types, however:
int i = 3; // i contains the value 3. int j = i; // j contains a copy of the value in i. i = 2; // Changing i doesn't change j. // Now, i == 2 and j == 3.
class Type:
• Java is an object‐oriented programming language where an object is a variable, associated with methods that is described by a class.
• The name of a class is treated as a type in a java program, so that you can declare a variable of an object‐type, and a method which can be called using that object‐ type variable.
• Whenever a variable is created, a reference to an object is also created using the name of a class for its type i.e. that variable can contain either null or a reference to an object of that class.
• It is not allowed to contain any other kinds of values. Such type is called reference types in Java. • The object becomes an instance when the memory is allocated to that object using new keyword. • In addition, array types are reference types because these are treated as objects in Java. • For example:
class Fruit { fColor() { //................. }
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
36
fSize() { //................. } } class Demo { public static void main(String args[]) {
Fruit mango; Fruit banana; ...
} }
In the given example the Fruit is a class that has the reference variables as mango & banana through which we can call the behaviors associated with that class as mango.fColor(); within the main method of the Demo class.
Array Type: • An array is a special kind of object that contains values called elements. • The java array enables the user to store the values of the same type in contiguous memory allocations. • The elements in an array are identified by an integer index which initially starts from 0 and ends with one
less than number of elements available in the array. • All elements of an array must contain the same type of value i.e. if an array is a type of integer then all the
elements must be of integer type. • It is a reference data type because the class named as Array implicitly extends java.lang.Object. • The syntax of declaring the array is shown as:
DataType [ ] variable1, variable2, .......variableN; DataType [ ] variable = new DataType [ArraySize]; DataType [ ] variable = {item 1, item 2,...item n};
For example: int [] a = new int [10]; String [] b = {"reference","data", "type"};
• In the first statement, an array variable "a" is declared of integer data type that holds the memory spaces according to the size of int. The index of the array starts from a[0] and ends with a[9]. Thus, the integer value can be assigned for each or a particular index position of the array.
• In the second statement, the array "b" is declared of string data type that has the enough memory spaces to directly holds the three string values. Thus each value is assigned for each index position of the array.
interface Type:
• Java provides an another kind of reference data type or a mechanism to support multiple inheritance feature called an interface.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
37
• The name of an interface can be used to specify the type of a reference. • A value is not allowed to be assign to a variable declared using an interface type until the object
implements the specified interface. • When a class declaration implements an interface, that class inherits all of the variables and methods
declared in that interface. • So the implementations for all of the methods declared in the interface must be provided by that class. • For example, Java provides a class called Thread that implements Runnable interface.
Thus the following assignment can be allowed:
Runnable r; r = new Thread();
enum Type:
• The enum types were introduced in Java programming from Java Version 5.0. • These are special classes that have a fixed number of instances. • All these instances are known at the compile time. • The name of an interface can be used to specify the type of a reference. • An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass
directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. • Because they are constants, the names of an enum type's fields are in uppercase letters. • In the Java programming language, you define an enum type by using the enum keyword. For example, you
would specify a days‐of‐the‐week enum type as:
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
public class EnumTest { Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break;
case FRIDAY: System.out.println("Fridays are better.");
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
38
break;
case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break;
default: System.out.println("Midweek days are so‐so."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } } The output is: Mondays are bad. Midweek days are so‐so. Fridays are better. Weekends are best. Weekends are best.
annotation Type:
• Annotations were introduced in Java programming from Java Version 5.0. • These are special kinds of interfaces that are used to annotate programming elements in the source code. • These could then be used by annotation processing tools.
Reference Type Summary The distinction between primitive types passed by value, and objects and arrays passed by reference is a crucial one in Java. Be sure you understand the following:
• All objects and arrays are handled by reference in Java. (Those object references are passed‐by‐value to methods, however.)
• The = and == operators assign and test references to objects. Use clone() and equals() to actually copy or test the objects themselves.
• The necessary referencing and dereferencing of objects and arrays is handled automatically by Java. • A reference type can never be cast to a primitive type. • A primitive type can never be cast to a reference type. • There is no pointer arithmetic in Java.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
39
• There is no sizeof operator in Java. • null is a special value that means "no object" or indicates an absence of reference.
1.16 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.
o One‐Dimensional Arrays o Multidimensional Arrays
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.
• The general form of a one dimensional array declaration is type var‐name[ ]; type ‐ declares the base type of the array Example : Array declaration int month_days[];
• 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];
Example : Array allocation month_days = new int[12]; int month_days[] = new int[12];
• That is, to use new to allocate an array, you must specify the type and number of elements to allocate. • The elements in the array allocated by new will automatically be initialized to zero.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
40
Example : 1 : // Demonstrate a one‐dimensional array. class Array {
public static void main(String args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); }
}
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
41
Example : 2 : An array initializer is a list of comma‐separated expressions surrounded by curly braces. // Example for array initializer. class AutoArray {
public static void main(String args[]) { int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; System.out.println("January has " + month_days[0] + " days.");
} }
length variable for an array
• Specifically, the size of an array—that is, the number of elements that an array can hold—is found in its length instance variable.
• All arrays have this variable, and it will always hold the size of the array. Here is a program that demonstrates this property:
// This program demonstrates the length array member. class Length {
public static void main(String args[]) { int a1[] = new int[10]; int a2[] = {3, 5, 7, 1, 8, 99, 44, ‐10}; int a3[] = {4, 3, 2, 1}; System.out.println("length of a1 is " + a1.length); System.out.println("length of a2 is " + a2.length); System.out.println("length of a3 is " + a3.length);
} }
Output:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
42
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of arrays. • To declare a multidimensional array variable, specify each additional index using another set of square
brackets. • For example, the following declares a two‐dimensional array variable
int twoD[ ][ ] = new int[4][5];
. // 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++) {
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
43
for(j=0; j<5; j++) System.out.print(twoD[i][j] + " ");
System.out.println(); }
} } Output:
// 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< twoD[i].length; j++) {
twoD[i][j] = k; k++;
} }
for(i=0; i<4; i++) {
for(j=0; j<twoD[i].length; j++) System.out.print(twoD[i][j] + " ");
System.out.println(); }
} }
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
44
Output:
1.17 Understanding Super – Types and Sub ‐ Types in Java OR Super‐type and sub‐type relations in primitive data types
• We hava a relationship of super‐type and sub‐type between data types. • A data type is a sub‐type of a given data type if it is a special kind of the given data type. • The sub‐type would then always be usable wherever the super‐type is usable, e.g. in case of primitive
types, int is a sub‐type of long, as int can always be used wherever long is used. • All ints are long, but not all longs may be ints. i.e. we cannot use the super‐type for sub‐type. • In the Java programming language, for the primitive data types, the super‐type and the sub‐type
relationships are as given in below fig.
• For reference data types, the super‐type and sub‐type relationship involve inheritance. • The java.lang.Object class is the super‐type for all the reference data types.
• The super‐types for class, are
a) The direct super‐class of the class
double
float
long
int
short char
byte
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
45
b) All the super‐types of this super‐class c) The interfaces directly implemented by the class
• The super‐types for any interface, are a) The java.lang.Object class b) All the interfaces directly extended by the interface c) All the super‐types of the interfaces directly extended by the interface
• The super‐types for an array of any primitive type are, a) The java.lang.Object class b) The java.lang.Cloneable interface c) The java.io.Serializable interface
1.18 Operators
• Arithmetic Operators
• String Concatenation
• Relational Operators
• Logical Operators
• Bitwise Operators
• Increment‐Decrement Operators
• Conditional Operator
• Assignment Cast operators
• instanceof operator
• Other Operators ( new , [ ] , . (dot) )
Arithmetic Operators
• Arithmetic Operators are used to perform some mathematical operations like addition, subtraction, multiplication, division, and modulo (or remainder).
• These are generally performed on an expression or operands. • The symbols of arithmetic operators are given in a table:
Symbol Name of the Operator Example
+ Additive Operator n = n + 1;
‐ Subtraction Operator n = n ‐ 1;
* Multiplication Operator n = n * 1;
/ Division Operator n = n / 1;
% Remainder Operator n = n % 1;
• The "+" operator can also be used to concatenate (to join) the two strings together. For example:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
46
String str1 = "Concatenation of the first"; String str2 = "and second String"; String result = str1 + str2;
• The variable "result" now contains a string "Concatenation of the first and second String". • Lets have one more example implementing all arithmetic operators:
class ArithmeticDemo { public static void main(String[] args) { int x = 4; int y = 6; int z = 10; int rs = 0; rs = x + y; System.out.println("The addition of (x+y):"+ rs); rs = y ‐ x; System.out.println("The subtraction of (y‐x):"+ rs); rs = x * y; System.out.println("The multiplication of (x*y):"+ rs); rs = y / x; System.out.println("The division of (y/x):"+ rs);
rs = z % y; System.out.println("The remainder of (z%x):"+ rs); rs = x + (y * (z/x)); System.out.println("The result is now :"+ rs); } } Output of the Program: C:\nisha>javac ArithmeticDemo.java C:\nisha>java ArithmeticDemo The addition of (x + y): 10 The subtraction of (y ‐ x): 2 The multiplication of (x * y): 24 The division of (y / x): 1 The remainder of (z % x): 4 The result is now : 16
String Concatenation
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
47
• In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the + operator, which concatenates two strings, producing a String object as the result. This allows you to chain together a series of + operations.
• For example, the following fragment concatenates three strings:
String age = "9"; String s = "He is " + age + " years old."; System.out.println(s);
Output: "He is 9 years old."
Relational Operators • Whenever we need to compare the results of two expressions or operands in a program then the equality
and relational operators are used to know whether an operand is equal, not equal, greater than, less than to another operand.
• There are different types of equality and relational operators mentioned in a table given below:
Symbol Name of the Operator Example Operation
= = Equal to a = = b a is equal to b
!= Not equal to a ! = b a is not equal to b
> Greater than a > b a is greater than b
< Less than a < b a is less than b
>= Greater than or equal to a > = b a is greater than or equal to b
<= Less than or equal to a > = b a is less than or equal to b
• The Equality operator "= =" differs from an assignment operator "=" i.e. the equality operator is used to
determine whether one operand is equal to another operand or not while the assignment operator is used to assign a value to a variable.
• All these operators are often used in the control structures such as if, do, while with the conditional operators to make decisional expressions.
Lets have an example implementing these operators:
class EquityOperator { public static void main(String[] args){ int x = 5; int y = 10; if(x == y) System.out.println("value of x is equal to the value of y"); if(x != y)
System.out.println("value of x is not equal to the value of y"); if(x > y) System.out.println("value of x is greater then the value of y"); if(x < y)
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
48
System.out.println("value of x is less then the value of y"); if(x >= y) System.out.println("value of x is greater then or equal to the value of y"); if(x <= y) System.out.println("value of x is less then or equal to the value of y"); } }
Output of the Program:
C:\nisha>javac EquityOperator.java
C:\nisha>java EquityOperator value of x is not equal to the value of y value of x is less then the value of y value of x is less then or equal to the value of y
Boolean Logical Operators
• Conditional operators return a true or a false value based on the state of the variables i.e. the operations using conditional operators are performed between the two boolean expressions.
Symbol Name of the Operator
& AND
&& Conditional‐AND
| OR
|| Conditional‐OR
! NOT
AND (&) and Conditional‐AND (&&) operators:
• The AND (&) operator is similar to the Conditional‐AND operator (&&). Both of its operands are of boolean type, even these operands may be boolean expressions. Other Relational operators can also be used with these operators. Lets use a Truth Table to know the status of an output
Op1 AND Exp1 Op2 AND Exp2 Result
True True True
False False False
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
49
True False False
False True False
• If we analyze the table we find that result is always true only in case of first condition where both operands(or expressions) are true. On the other hand result is always false in other conditions. Note that this table works alike for & and && operators.
• In case of "&" operator, if both operands or expressions are true, the result is always true, otherwise it is false if either left‐hand or right‐hand operand is false.
• In case of "&&" operator, the result is also true, if both operands or expressions are true. • But this operator evaluates only the left‐hand operand. It doesn't evaluate the right‐hand operand if the
left‐hand operand is false then it will not jump to the right‐hand operand to evaluate it, and will come out from that statement and read the next statement. That's why this mechanism is known as short‐circuiting. Consider the following statements where the second expression returns false after evaluating only the left‐hand operand.
true && true = true; // both operands are evaluated false && true = false; // only left‐operand is evaluated
• But the "&" operator always evaluates both of its operands whether the first operand is true or false. Consider the following statements where the second expression returns false after evaluating the right‐hand operand.
true & true = true; // both operands are true true & false = false; // both operands are evaluated
OR (|) and Conditional‐OR (||) operators :
• Likewise, the OR operator(|) is similar to the Conditional‐OR operator (||) and returns true, if one or another of its operand is true.
• Lets use a Truth Table to know the status of an output that works alike for "|" and "| |" operators.
Op1 or Exp1 Op2 or Exp2 Result
True True True
False False False
True False True
False True True
• If we analyze the table then we find that, result is always false only if both operands or expression are false. On the other hand, result is always true in rest of the other conditions.
Still these exists a major difference in their mode of use:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
50
• The "|" operator always evaluates both of its operands and returns true if one or other of its operand is true. Otherwise false if both the conditions are false. Consider the following statements where the second expression returns false after evaluating the right‐hand operand.
true | false = true; // left operand is true but both are evaluated false | false = false; //both operands are evaluated
• In case of "||" the result is also true, if one of the both operands is true. Otherwise it evaluates to false if both operands are false. But this operator conditionally evaluates the right‐hand operand only if the left‐hand operands is false. Like the Conditional‐AND operator, this mechanism is also known as short‐circuiting. Consider the following statements where the first expression returns true after evaluating the right‐hand operand.
false || true = true; // both operands are evaluated true || false = true; // only left‐operand is evaluated
NOT ("!") operator :
• The NOT ("!") operator performs the boolean NOT operation on a single operand or an expression. • It checks the boolean status of a current operand or expression and reverses the value of a boolean
expression i.e. if the current value of an operand or expression is true then it reverses as false; but if the value of an operand or expression is false then it reverses as true.
• Consider the following example:
class BoolNotDemo { public static void main(String[] args){ int x = 2; int y = 1; boolean bl; bl = !(x > y); // bl is false System.out.println("x is not greater than y:"+bl); bl = !(y > x); // bl is true System.out.println("y is not greater than x:"+bl); } }
Output of the Program:
C:\nisha>javac BoolNotDemo.java C:\nisha>java BoolNotDemo
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
51
x is not greater than y : false y is not greater than x : true
The Bitwise Operators
• Java's bitwise operators operate on individual bits of integer (int and long) values. If an operand is shorter than an int, it is promoted to int before doing the operations.
• It helps to know how integers are represented in binary. For example the decimal number 3 is represented as 11 in binary and the decimal number 5 is represented as 101 in binary. Negative integers are store in two's complement form. For example, ‐4 is 1111 1111 1111 1111 1111 1111 1111 1100.
Operator Name Example Result Description
a & b and 3 & 5 1 1 if both bits are 1.
a | b or 3 | 5 7 1 if either bit is 1.
a ^ b xor 3 ^ 5 6 1 if both bits are different.
~a not ~3 ‐4 Inverts the bits.
n << p left shift
3 <<< 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low‐order positions.
n >> p right shift
5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high‐order positions.
n >>> p right shift
‐4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high‐order positions.
Increment‐Decrement Operators
• There are two operators : Increment or decrement operators i.e. ++ and ‐‐. • These two operators are unique in that they can be written both before the operand they are applied to,
called prefix increment/decrement, or after, called postfix increment/decrement. • The meaning is different in each case.
Example
x = 1; y = ++x; System.out.println(y); Output is 2
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
52
But x = 1; y = x++; System.out.println(y); Output is 1
Conditional Operator
• The follwing is the conditional operator (ternary operator)
? :
• Java supports conditional operator that is also known as the ternary operator "?:" and basically is used for an if‐then‐else as shorthand as
boolean expression ? operand1 : operand2;
• The "?:" operator evaluates an expression which may also be an operand and returns operand1 if the expression is true; otherwise returns operand2, if the expression is false.
• We can understand this thing with the help of a diagram shown as:
• If we analyze this diagram then we find that, operand1 is returned, if the expression is true; otherwise operand2 is returned in case of false expression.
• Lets have an example implementing some Logical operators:
class ConditionalOperator { public static void main(String[] args){ int x = 5; int y = 10, result=0; boolean bl = true; if((x == 5) && (x < y)) System.out.println("value of x is "+x); if((x == y) || (y > 1)) System.out.println("value of y is greater than the value of x"); result = bl ? x : y;
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
53
System.out.println("The returned value is "+result); } }
Output of the Program:
C:\nisha>javac ConditionalOperator.java C:\nisha>java ConditionalOperator value of x is 5 value of y is greater than the value of x The returned value is 5
Assignment Operators
• Assignment operator is the most common operator almost used with all programming languages. • It is represented by "=" symbol in Java which is used to assign a value to a variable lying to the left side of
the assignment operator. • But, If the value already exists in that variable then it will be overwritten by the assignment operator (=). • This operator can also be used to assign the references to the objects. Syntax of using the assignment
operator is:
<variable> = <expression>;
For example:
int counter = 1; String name = "Nisha"; boolean rs = true; Shape s1 = new Shape(); // creates new object Shape s2 = s1; //assigning the reference of s1 to s2 counter = 5; // previous value is overwritten
• In all cases a value of right side is being assigned to its type of variable lying to the left side. You can also assign a value to the more than one variable simultaneously. For example, see these expressions shown as:
x = y = z = 2;
x =(y + z);
• Where the assignment operator is evaluated from right to left. In the first expression, value 2 is assigned to the variables "z", then "z" to "y", then "y" to "x" together. While in second expression, the evaluated value of the addition operation is assigned to the variable "x" initially then the value of variable "x" is returned.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
54
• Apart from "=" operator, different kind of assignment operators available in Java that are know as compound assignment operators and can be used with all arithmetic or, bitwise and bit shift operators. Syntax of using the compound assignment operator is:
operand operation= operand
• In this type of expression, firstly an arithmetic operation is performed then the evaluated value is assigned to a left most variable. For example an expression as x += y; is equivalent to the expression as x = x + y; which adds the value of operands "x" and "y" then stores back to the variable "x". In this case, both variables must be of the same type.
• The table shows all compound assignment operators which you can use to make your code more readable and efficient. (Assignment Cast)
Operator Example Equivalent Expression
+= x += y; x = (x + y); ‐= x ‐= y; x = (x ‐ y); *= x *= y; x = (x * y); /= x /= y; x = (x / y); %= x %= y; x = (x % y); &= x &= y; x = (x & y); |= x != y; x = (x ! y); ^= x ^= y; x = (x ^ y); <<= x <<= y; x = (x << y); >>= x >>= y; x = (x >> y);
>>>= x >>>= y; x = (x >>> y);
Lets have an example implementing some compound assignment operators:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
55
class CompAssignDemo{ public static void main(String[] args) { int x=5; int y=10;
x += y; System.out.println("The addition is:"+ x); x ‐= y; System.out.println("The subtraction is:"+ x); x *= y; System.out.println("The multiplication is:"+ x); x /= y; System.out.println("The division is"+ x); x %= y; System.out.println("The remainder is:"+x); x &= y; System.out.println("The result of AND operation :"+ x); x |= y; System.out.println("The result of Bitwise inclusive OR operation :"+ x); x <<= y; System.out.println("The result of Signed left shift operation :"+ x); } }
Output of the Program:
C:\nisha>javac CompAssignDemo.java
C:\nisha>java CompAssignDemo The addition is: 15 The subtraction is: 5 The multiplication is: 50 The division is 5 The remainder is: 5 The result of AND operation : 0 The result of Bitwise inclusive OR operation : 10 The result of Signed left shift operation : 10240
instanceof Operator / () operator
• Java provides a run‐time operator instanceof to compare a class and an instance of that class. • This operator " instanceof" compares an object to a specified class type.
The instanceof operator is defined to know about an object's relationship with a class.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
56
• It evaluates to true, if the object or array is an instance of the specified type; otherwise it returns false. • The instanceof operator can be used with the arrays and objects. It can't be used with primitive data types
and values. Its signature is written as:
object instanceof type
Lets have an example :
class X { int i, j; } class Y { int i, j; } class Z extends X { int k; } public class InstanceOfDemo { public static void main(String args[]) { X x = new X(); Y y = new Y(); Z z = new Z(); if(x instanceof X) System.out.println("x is an instance of X"); X obj; obj = z; // X reference to z if(obj instanceof Z) System.out.println("obj is an instance of Z"); } }
Output of the Program:
C:\nisha>javac InstanceOfDemo.java C:\nisha>java InstanceOfDemo x is an instance of X obj is an instance of Z
• In this example the class "Z" extends the class "X". So the expression " if (x instanceof X)" returns true because the object of class "X" has the reference to the object of class "Z". On the other hand, this
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
57
example will generate an error, if the expression is written as "if (y instanceof X)" because the object "y" of class "Y" is not an object of class "X".
new operator: • The new operator dynamically allocates memory for an object. It has this general form:
class‐var = new classname( )
class‐var ‐ is a variable of the class type being created. 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.
[ ] operator: • The [ ] operator is used to access the elements in an array. • This operator requires an int expression. • There can be an error at the runtime if the value of the expression used to access the element is not in the
range from 0 to the array length – 1.
Example :
int x[] = new int[5]; x[0]=10; System.out.println(x[0]); Output is 10
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
58
dot ( . ) operator: • The dot ( . ) operator is used to access any member of an instance or invoking methods of an instance. • This can also result in an error at the runtime in case we try to access any member for the null value.
1.19 Statements
Java’s Control Statements • Selection Statements
• Repetition Statements
• Branching Statements
Selection Statements
if‐else Statements
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
59
Example
int n = 11; if(n%2 = = 0) { System.out.println("This is even number"); } else { System.out.println("This is not even number"); }
Switch Statement:
class SwitchDemo { public static void main(String[] args) { int month = 8;
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
60
switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: System.out.println("Invalid month.");break; } } } Repetition Statements
• while loop statements
• do‐while loop statements
• for loop statements
While Loop
Do‐While Loop
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
61
For Loop
Branching Statements
Break statements:
• The break statement is a branching statement that contains two forms: labeled and unlabeled.
• The break statement is used for breaking the execution of a loop (while, do‐while and for) .
• It also terminates the switch statements. Syntax: break; // breaks the innermost loop or switch statement. break label; // breaks the outermost loop in a series of nested loops. Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
62
executes the statements just following the loop.
Continue statements: This is a branching statement that are used in the looping statements (while, do‐while and for) to skip the current iteration of the loop and resume the next iteration . Syntax: continue; Example:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
63
Return statements:
• It is a special branching statement that transfers the control to the caller of the method.
• This statement is used to return a value to the caller method and terminates execution of method.
• This has two forms: one that returns a value and the other that cannot return.
• The returned value type must match the return type of method. Syntax: return; return values; return; //This returns nothing. So this can be used when method is declared with void return type. return expression; //It returns the value evaluated from the expression.
• Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This is printed to the screen.
Labelled break:
• The general form of the labeled break statement is shown here:
break label; label ‐ is the name of a label that identifies a block of code.
• When this form of break executes, control is transferred out of the named block of code. • The labeled block of code must enclose the break statement, but it does not need to be the immediately
enclosing block. • This means that you can use a labeled break statement to exit from a set of nested blocks. But you cannot
use break to transfer control to a block of code that does not enclose the break statement.
// Using break as a civilized form of goto. class Break {
public static void main(String args[]) {
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
64
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.
• One of the most common uses for a labeled break statement is to exit from nested loops. • For example, in the following program, the outer loop executes only once:
// Using break to exit from nested loops class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": "); for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops System.out.print(j + " ");
} System.out.println("This will not print");
} System.out.println("Loops complete.");
} } Output: Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
65
Labelled continue:
• The general form of the labeled continue statement is shown here:
continue label; label ‐ is the name of a label that identifies a block of code.
• 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();
} } Output: 0 0 1 0 2 4 0 3 6 9 0 4 8 12 16 0 5 10 15 20 25 0 6 12 18 24 30 36 0 7 14 21 28 35 42 49 0 8 16 24 32 40 48 56 64 0 9 18 27 36 45 54 63 72 81
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
66
1.20 Various Members within a class
• Instance Variables
• Methods Overloading Methods Using Objects as Parameters A Closer Look at Argument Passing
Pass‐by‐reference Pass‐by‐value
Returning Objects Recursion
• Constructors Overloading Constructors
• Uses of this keyword Accessing current instance using this keyword Invoking a constructor of the same class using this keyword
• Garbage collector and finalize() method
• static variables
• static methods
• static block / Class Initializer Block
• Initializer Block
Defining Classes
o adding variables o adding methods
• Perhaps the most important thing to understand about a class is that it defines a new data type. • Once defined, this new type can be used to create objects of that type. Thus, a class is a template for an
object, and an object is an instance of a class. 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 }
}
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
67
/* 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);
} }
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
68
Creating Array of Objects class Student {
int EnrlNo; String Name; String Graduate; double CPI; void display() {
System.out.println(“EnrlNo : ”+EnrlNol); System.out.println(“Name : ”+Name); System.out.println(“Graduate : ”+Graduate); System.out.println(“CPI : ”+ CPI);
} } // This class declares an object of type Student. class StudentDemo {
public static void main(String args[]) { Student stud[ ] = new Student[3]; stud[0] = new Student(); stud[0].EnrlNo=30; stud[0].Name=”X”; stud[0].Graduate=”BCA”; stud[0].CPI=7.85; stud[1] = new Student(); stud[1].EnrlNo=31; stud[1].Name=”Y”; stud[1].Graduate=”BCA”; stud[1].CPI=6.05; stud[2] = new Student(); stud[2].EnrlNo=32; stud[2].Name=”Z”; stud[2].Graduate=”BCom”; stud[2].CPI=7.05; stud[0].display(); stud[1].display(); stud[2].display();
} }
Instance Variables and Methods • 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. • In other words, methods define the abilities of an object.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
69
Creating Objects
• Perhaps the most important thing to understand about a class is that it defines a new data type. Box mybox = new Box();
• This statement combines the two steps just described. It can be rewritten like this to show each step more clearly:
Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object
new operator: • The new operator dynamically allocates memory for an object. It has this general form:
class‐var = new classname( )
class‐var ‐ is a variable of the class type being created. 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.
Accessing Class Members
• To access instance variables and methods defined in a class, we need to create object of a class as described above.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
70
• Each object contains its own sets of variables.
• To access members we must use the object and the dot operator ( . ) as shown below: objectname . variablename objectname . methodname(parameter‐list); objectname – is the name of the object variable name – is the name of the instance variable inside the object that we wish to access. method name – is the method that we wish to call, and parameter list – is optional and if exist then it is a comma separated list of “actual values”( or expressions) that must match in type and number with the parameter list of the methodname declared in the class.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
71
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
72
How to define a Method? This is the general form of a method:
type name(parameter‐list) { // body of method
} type ‐
o specifies the type of data returned by the method. o This can be any valid type, including class types that you create. o If the method does not return a value, its return type must be void.
name –
o The name of the method is specified by name. o This can be any legal identifier other than those already used by other items within the
current scope. parameter‐list ‐
o is a sequence of type and identifier pairs separated by commas. o Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called. o If the method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using the following form of the return statement:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
73
return value; Here, value is the value returned Example:
// compute and return volume double volume() {
return width * height * depth; }
Overloading Methods • In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. • When this is the case, the methods are said to be overloaded, and the process is referred to as
method overloading. • Method overloading is one of the ways that Java implements polymorphism. • When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call. • Thus, overloaded methods must differ in the type and/or number of their parameters. • While overloaded methods may have different return types, the return type alone is insufficient
to distinguish two versions of a method. • When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
74
// 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);
}
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
75
} Output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625
Using Objects as Parameters • Using simple types as parameters to methods is very easy. • However, it is both correct and common to pass objects to methods.
// 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(50, 11); Test ob3 = 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
// Here, Box allows one object to initialize another.
class Box { double width; double height;
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
76
double depth; // construct clone of an object 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); 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);
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
77
// 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);
} }
A Closer Look at Argument Passing • There are two ways that a computer language can pass an argument to a subroutine.
o Pass‐by‐value o Pass‐by‐reference
Pass‐by‐value • This way copies the value of an argument into the formal parameter of the method. Therefore,
changes made to the parameter of the method have no effect on the argument. • In Java, when you pass a simple type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
78
Example:
// Simple types are passed by value. class Test {
void meth(int i, int j) { i *= 2; j /= 2;
} } class CallByValue {
public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b);
} } Output: a and b before call: 15 20 a and b after call: 15 20
Pass‐by‐reference • In this way, a reference to an argument (not the value of the argument) is passed to the
parameter. • Inside the subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the argument used to call the subroutine.
• When you pass an object to a method, the situation changes dramatically, because objects are passed by reference.
• Keep in mind that when you create a variable of a class type, you are only creating a reference to an object.
• Thus, when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
• This effectively means that objects are passed to methods by use of call‐by‐reference. Changes to the object inside the method do affect the object used as an argument. // Objects are passed by reference. class Test {
int a, b; Test(int i, int j) {
a = i; b = j;
}
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
79
void meth(Test o) { o.a *= 2; o.b /= 2;
} } class CallByRef {
public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); 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
In short, When a simple type is passed to a method, it is done by use of call‐by‐value. Objects are passed by use of call‐by‐reference.
Returning Objects
• A method can return any type of data, including class types that you create.
// Returning an object. class Test {
int a; Test(int i) {
a = i; } Test incrByTen() {
Test temp = new Test(a+10); return temp;
} } class RetOb {
public static void main(String args[]) { Test ob1 = 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();
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
80
System.out.println("ob2.a after second increase: " + ob2.a); }
} Output: ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
Recursion • Recursion is the process of defining something in terms of itself. • As it relates to Java programming, recursion is the attribute that allows a method to call itself. • A method that calls itself is said to be recursive.
// A simple example of recursion. class Factorial {
// this is a recursive function int fact(int n) {
int result; if(n==1) return 1; result = fact(n‐1) * n; return result;
} } class Recursion {
public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5));
} } Output: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120
Exercises: Write a program to generate Fibonacci Series using recursive method, 0 1 1 2 3 5 ………… (Up to 20 numbers)
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
81
Constructors:
• Java supports a special type of method, called a constructor, that enables an object to initialize itself when it is created.
• Constructor have the same name as the class itself. • Constructors do not specify a return type, not even void. Because they return the instance of the
class itself. • It is the constructor’s job to initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
82
/* Here, Box uses a constructor to initialize the dimensions of a box. */
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 BoxDemo { 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:
Constructing Box
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
83
Constructing Box Volume is 1000.0 Volume is 1000.0
Overloading Constructors
• Like regular methods, constructors can also take varying numbers and types of parameters, enabling you to create your object with exactly the properties you want it to have, or for it to be able to calculate properties from different kinds of input.
• This way you can add parameters to constructors to initialize object of an class.
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */
class Box { double width; double height; double depth; Box() {
width = 10; height = 10;
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
84
depth = 10; } // This is the constructor for Box. Box(double w) {
width = w; height = 10; depth = 10;
} // This is the constructor for Box. Box(double w, double h) {
width = w; height = h; depth = 10;
} // 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 BoxDemo {
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); Box mybox3 = new Box(20); Box mybox4 = 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); // get volume of second box
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
85
vol = mybox3.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox4.volume(); System.out.println("Volume is " + vol);
} }
this keyword
• this keyword refers to the object that is currently executing. • 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
Example: Box(double w, double h, double d) {
this(); this.width = w; this.height = h; this.depth = d;
}
• this also allows one constructor to explicitly invoke another constructor in the same class. this(args)
But you can use this syntax as the first line in a constructor. Otherwise, a compiler error is generated.
• this lets you refer directly to the object, you can use it to resolve any name space collisions that might occur between instance variables and local variables.
For example, here is another version of Box( ), which uses width, height, and depth for parameter
names and then uses this to access the instance variables by the same name: // Use this to resolve name‐space collisions. Box(double width, double height, double depth) {
this.width = width; this.height = height; this.depth = depth;
} Example : /* Here, Box uses a constructor to initialize the dimensions of a box using this keyword
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
86
*/ class Box {
double width; double height; double depth; // This is the constructor for Box. Box() {
this.width = 10; this.height = 10; this.depth = 10;
} // compute and return volume
double volume() { return width * height * depth;
} } class thisKeywordDemo { public static void main(String args[]) {
// declare, allocate, and initialize Box objects Box mybox1 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); }
} Output:
Volume is 1000.0
Example : /* Here, this keyword for same class constructor calling. */
class Box { double width; double height; double depth; Box() {
width = 10; height = 10; depth = 10;
} // This is the constructor for Box.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
87
Box(double w) { this(); width = w;
} // compute and return volume double volume() {
return width * height * depth; }
} class BoxDemo {
public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(20); 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: ………………
Garbage Collection
• Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation.
• Java handles deallocation for you automatically. The technique that accomplishes this is called garbage collection.
• It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
• 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
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
88
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 window character font etc..
then you might want to make sure these resources are freed before an object is destroyed.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
89
• To handle 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.
• To add a finalizer to a class, you simply define the finalize( ) method. • The Java run time calls that method whenever it is about to recycle an object of that class. Inside
the finalize( ) method you will specify those actions that must be performed before an object is destroyed.
• The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects.
• Right before an asset is freed, the Java run time calls the finalize( ) method on the object. • The finalize( ) method has this general form:
protected void finalize( ) { // finalization code here } Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
• It is important to understand that finalize( ) is only called just prior to garbage collection. • It is not called when an object goes out‐of‐scope, for example. This means that you cannot know
when—or even if—finalize( ) will be executed. • Therefore, your program should provide other means of releasing system resources, etc., used
by the object. • It must not rely on finalize( ) for normal program operation.
Check the output for at your own way for the following program.
class X { static final int MAX = 5; static int count = 0; // constructor X() {
if(count<MAX) { count++;
} else {
System.out.println("Error ‐‐ can't construct"); System.exit(1);
} } // finalization protected void finalize() {
count‐‐; } static void f() {
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
90
X ob = new X(); // allocate an object // destruct on way out
} public static void main(String args[]) {
int i; for(i=0; i < (MAX*2); i++) {
f(); System.out.println("Current count is: " + count);
} }
} Check the output in lab :‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
• Understanding static o static variable o static method o static block ( { } )
static variable • When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object. • 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.
Accessing Static variables inside its class .
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
91
Accessing Static variables inside its class + outside its class .
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
92
static method
• You can also declare methods to be static. • A static method means "behavior not dependent on an instance variable, so no instance/object is required. • The most common example of a static member is main( ). main( ) is declared as static because it must be
called before any objects exist. • Methods declared as static have several restrictions:
o They can only call other static methods of the same class. o They must only access static data. o They cannot refer to this or super in any way.
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
93
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
94
static block / Class Initializer Block
• If you need to do computation in order to initialize your static variables, you can declare a static block. • static block gets executed exactly once, when the class is first loaded.
static // will be executed once when the class is first loaded {
//statements }
// 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;
}
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
95
public static void main(String args[]) {
meth(42); }
} Output:
/*Here is an example. Inside main( ), the static method callme( ) and the static variable b are accessed outside of their class.*/
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:
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
96
Initializer Block
• In a class definition, we can have a member block with no name. Such a block is know as the initializer block.
• The general form is: // initializer block, executed whenever any instance is created but before constructor call
{ //statements
} • The initializer block is never invoked by any application directly since it does not have any name. • However, it is always invoked on an instance as soon as it is allocated. • It is invoked just before the constructor is invoked on the instance.
//Initiliazer block invocation demo class X {
int a; int b; static int count=0; X() { } X(int a, int b) { this.a = a; this.b = b; } //Initializer block {
System.out.println("Initilizer block is invoked."); count = count + 1;
} static void showCount() {
System.out.println("count = " + count); } void show() {
System.out.println("a = " + a); System.out.println("b = " + b);
} } class InitBlockDemo {
public static void main(String args[]) {
X obj1 = new X(); obj1.show(); X.showCount(); X obj2 = new X(10,15); obj2.show(); X.showCount();
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
97
} } Output:
1.21.1 Read value from keyboard
import java.io.*; public class Input{ public static void main(String[] args) throws IOException
{ try{ BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.print("Enter Name : "); String i = br.readLine(); System.out.println("Hello " + i); } catch(IOException e){ System.out.println(e.getMessage()); } } }
1.21.2 Read value from keyboard import java.io.*; public class Input{ public static void main(String[] args) throws Exception
{ try{ DataInputStream in = new DataInputStream(System.in); System.out.print("Enter Name : "); String s = in.readLine(); System.out.println("Hello " + s); } catch(IOException e){ System.out.println(e.getMessage());
FUNDAMENTALS OF JAVA PROGRAMMING (JAVA) Unit ‐ 1
Prepared By:‐ Paresh TannaMCA Dept, School of Engineering, RK University ‐ Rajkot
98
} } } Websites
http://java.sun.com/docs/books/tutorial/ http://www.roseindia.net/java/beginners/ http://www.javapassion.com/ http://www.java2s.com/ http://www.java‐examples.com/ http://www.javabeginner.com
Download Free Books http://www.flazx.com/category4.php http://knowfree.net/category/it‐ebooks/java/