Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all...

30
JAVA PROGRAMMING [Document subtitle] DEPARTMENT OF COMPUTER TECHNOLOGY KBP POLYTECHNIC, KOPARGAON

Transcript of Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all...

Page 1: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

JAVA PROGRAMMING [Document subtitle]

DEPARTMENT OF COMPUTER TECHNOLOGY

KBP POLYTECHNIC, KOPARGAON

Page 2: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

1 | P a g e

Page 3: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

2 | P a g e

“James Gosling is a famous Canadian software developer who has been with Sun Microsystems since 1984 and is considered as father of Java programming language. Gosling did the original design of Java and implemented its original compiler and virtual machine.”

Page 4: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

3 | P a g e

Page 5: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

4 | P a g e

Chapter 1

Introduction to Java

1.1 Introduction

Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts and terminologies which has made it a popular programming language. OOP allows to divide the problem into number of entities called objects and then build the data and functions around these entities. The combination of data and methods creates object. The data of an object can be only accessed by the methods associated by that object. However method of one object can access method of another object. C++ is basically a procedural language with object oriented extension. Java is purely object oriented language.

1.2 Fundamentals of Object Oriented Programming 1.2.1 Object

An object can be considered as a thing that can perform a set of operations. Objects are basic run time entities or we can say object is collection of member function and member variables. The object may represent a person, a place, a thing or bank or any real time entity that program can use/handle. When program is executed, the object interact with one another to perform various operations. Objects can be represented in two different ways:

Fig. Two different ways to represent Object

Page 6: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

5 | P a g e

1.2.2 Classes

A class is a simple representation of a type of the object. It is the blueprint or template that describe the details of an object. Class act as a template, which is used to create object. The class is a way of binding data and functions associated with data together. A class is a user defined data type. Thus object is nothing but an instance (variable) of class. We can say class is a collection of similar objects.

1.2.3 Data Abstraction

Data abstraction is a way of hiding details or complex operation and representing simple view to the user or we can say Data Abstraction is a process of representing the essential feature without including implementation details. For this classes use the concept of abstraction. They encapsulate (hides) all essential properties of objet that are to be created. The concept of abstraction is like hiding of data that is not needed for representation. The main idea behind data abstraction is to provide clear separation between data type and implementation details.

1.2.4 Data Encapsulation

The wrapping of data and the function associated with data in to a single unit (i.e. object) is called as data encapsulation. The object contains data and member functions that operate on data and only the member function can access the data. The class is a kind of container, capsule or a cell which encapsulates the set of methods, attributes and properties. Data encapsulation also known data hiding.

1.2.5 Inheritance

Inheritance is the process by which object of one class acquires the properties of object of another class or we can say inheritance is the property by which one class can inherits the properties of another class. In simple words deriving new class form old class is called Inheritance. It provides the concept of code reusability. That is we can add more feature to the already existing class without modifying it. The old class is called Base Class and new class is called Derived class. Following are the types of classes:

1. Single Inheritance 2. Multiple Inheritance 3. Multilevel Inheritance 4. Hierarchical Inheritance 5. Hybrid Inheritance

1.2.6 Polymorphism

Polymorphism means the ability of taking more than one form. Using polymorphism we can use methods or operators in different ways. Polymorphism gives different meaning to methods and functions. In polymorphism Poly means many and morphism means Forms. In polymorphism same code, same objects or same function behaves different in different context. Examples of polymorphism are function overloading, operator overloading and virtual functions.

1.2.7 Dynamic Binding

Binding means linking a process call to the code to be executed in response to that call. In run time polymorphism or dynamic binding this linking is done at run time or at the time of code execution. Virtual function is good example of run time polymorphism.

1.3 History of Java In 1990, Sun Micro Systems Inc. (US) was conceived a project to develop software for

consumer electronic devices that could be controlled by a remote.

This project was called Stealth Project but later its name was changed to Green Project.

Page 7: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

6 | P a g e

In January 1991, Project Manager James Gosling and his team members Patrick Naughton, Mike Sheridan, Chris Wrath, and Ed Frank met to discuss about this project. Gosling thought C and C++ would be used to develop the project.

But the problem he faced with them is that they were system dependent languages.

They are designed to be compiled for a specific target and could not be used on various processors, which the electronic devices might use.

James Gosling with his team started developing a new language, which was completely system independent. This language was initially called OAK.

Since this name was registered by some other company, later it was changed to Java.

James Gosling and his team members were consuming a lot of coffee while developing this language.

Good quality of coffee was supplied from a place called “Java Island’. Hence they fixed the name of the language as Java. The symbol for Java language is cup and saucer.

Sun formally announced Java at Sun World conference in 1995. On January 23rd 1996, JDK1.0 version was released.

1.4 Features of Java/ Java Buzzwords

1. Object Oriented: In java everything is an Object. Java can be easily extended since it is based on the Object model.

2. Platform independent: Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.

3. Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP java would be easy to master.

4. Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption.

5. Architectural- neutral: Java compiler generates an architecture-neutral object file format which makes the compiled code to be executable on many processors, with the presence Java runtime system.

6. Portable: being architectural neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler and Java is written in ANSI C with a clean portability boundary which is a POSIX subset.

7. Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking.

8. Multi-threaded: With Java's multi-threaded feature it is possible to write programs that can do many tasks simultaneously. This design feature allows developers to construct smoothly running interactive applications.

9. Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light weight process.

10. High Performance: With the use of Just-In-Time compilers Java enables high performance.

11. Distributed: Java is designed for the distributed environment of the internet. 12. Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to

adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.

1.5 Java Environment

JDK (Java Development Kit) can be downloaded from Sun Microsystems web site: http://www.oracle.com/technetwork/java/javase/downloads/index.html, which also contains java compiler and runtime engine. Install JDK after downloading. By default JDK will be installed in C:\Program Files\Java\jdk1.7.0_05 or C:\Program Files (x86)\Java\jdk1.7.0_05

Page 8: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

7 | P a g e

1.5.1 Setting up Java Environment

After installing the JDK, we need to set at least one environment variable to compile and run Java programs. A PATH environment variable enables the operating system to find the JDK executables when working directory (working directory means the directory in which we are saving java program) is not the JDK's binary directory.

Setting environment variables from a command prompt: If we set the variables from a command prompt, they will only hold for that session. To set the PATH from a command prompt:

set path=C:\Program Files\Java\jdk1.7.0_05

Fig. Setting up Environmental variables and class path from cmd prompt

Setting environment variables as system variables: If we set the variables as system variables they permeant and there is no need to set the path every time u start the command prompt. Also we can execute java program form anywhere on the HDD.

Fig. Setting up environmental variables as a system variables

Following are steps for setting environment variables as a system variables:

1. Right-click on My Computer 2. Choose Properties 3. Select the Advanced tab 4. Click the Environment Variables button at the bottom 5. In system variables tab, select path (system variable) and click on edit button 6. A window with variable name-path and its value will be displayed.

Page 9: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

8 | P a g e

7. Don’t disturb the default path value that is appearing and just append (add) to that path at the end:

8. ; C:\Program Files\Java\jdk1.7.0_05; 9. Finally press OK button.

1.5.2 Java Programming Structure

Comments: Comments are description about the aim and features of the program. Comments increase readability of a program. Three types of comments are there in Java:

Single line comments: These comments start with // e.g.: // this is comment line

Multi line comments: These comments start with /* and end with */ e.g.: /* this is comment line*/

Java documentation comments: These comments start with /** and end with */. These comments are useful to create a HTML file called API (application programming Interface) document. This file contains description of all the features of software.

Escape Sequence: Java supports all escape sequence which is supported by C/ C++. A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler. When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.

Escape Sequence Description \t Insert a tab in the text at this point. \b Insert a backspace in the text at this point. \n Insert a newline in the text at this point \r Insert a carriage return in the text at this point. \f Insert a form feed in the text at this point. \’ Insert a single quote character in the text at this point. \” Insert a double quote character in the text at this point. \\ Insert a backslash character in the text at this point.

\ddd Octal character (ddd) \uxxxx Hexadecimal UNICODE character (xxxx)

Table. Escape Sequence in Java Programming

As all other programming languages, Java also has its own structure.

The first line of the C/C++ program contains include statement. For example, <stdio.h> is the header file that contains functions, like printf (), scanf () etc. So if we want to use any of these functions, we should include this header file in C/ C++ program.

Similarly in Java first we need to import the required packages. By default java.lang.* is imported.

Java has several such packages in its library. A package is a kind of directory that contains a group of related classes and interfaces. A class or interface contains methods.

Since Java is purely an Object Oriented Programming language, we cannot write a Java program without having at least one class or object. So, it is mandatory to write a class in Java program.

We should use class keyword for this purpose and then write class name.

In C/C++, program starts executing from main method similarly in Java, program starts executing from main method. The return type of main method is void because program starts executing from main method and it returns nothing.

Since Java is purely an Object Oriented Programming language, without creating an object to a class it is not possible to access methods and members of a class. But main method is also a method inside a class, since program execution starts from main method we need to call main method without creating an object.

Page 10: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

9 | P a g e

Static methods are the methods, which can be called and executed without creating objects.

Since we want to call main () method without using an object, we should declare main() method as static. JVM calls main () method using its Classname.main () at the time of running the program.

JVM is a program written by Java Soft people (Java development team) and main () is the method written by us.

Since, main () method should be available to the JVM, it should be declared as public. If we don’t declare main () method as public, then it doesn’t make itself available to JVM and JVM cannot execute it.

JVM always looks for main () method with String type array as parameter otherwise JVM cannot recognize the main () method, so we must provide String type array as parameter to main () method.

A class code starts with a {and ends with a}. A class or an object contains variables and methods (functions).

We can create any number of variables and methods inside the class.

This is our first program, so we had written only one method called main ().

This program just display a string “Hello world”. In Java, print () method is used to display something on the monitor.

A method should be called by using objectname.methodname (). So, to call print () method, create an object to PrintStream class then call objectname.print () method.

An alternative is given to create an object to PrintStream Class i.e. System.out. Here, System is the class name and out is a static variable in System class. out is called a field in System class.

When we call this field a PrintStream class object will be created internally. So, we can call print() method as: System.out.print (“Hello world”);

println () is also a method belonging to PrintStream class. It throws the cursor to the next line after displaying the result.

In the below Sample program System and String are the classes present in java.lang package.

Sample Program:

public class JavaDemo

{ /* This program print 'Hello World' as the output */

public static void main(String args[])

{

System.out.println("Hello World");

}

}

Following steps shows how to save, compile and run java file or program: 1. Open notepad and add the code as above. 2. Save the file as : JavaDemo.java. Here the most important thing here is the name of class

and the name of java file must be exactly same. 3. Open a command prompt window and go to the directory where you saved the class.

Assume its D:\. 4. Type javac JavaDemo.java and press enter to compile your code. If there are no errors in

your code the command prompt will take you to the next line. a. ( Assumption : The path variable is set).

5. Now type java JavaDemo to run your program. 6. You will be able to see ' Hello World ' printed on the window.

D :\> javac JavaDemo.java

D :\> java JavaDemo

Hello World

D : >

Page 11: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

10 | P a g e

1.5.3 Basic Syntax

Following important points must be consider as while writing Java Program: Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have

different meaning in Java. Class Names - For all class names first letter should be in Upper Case. If several words are

used to form a name of the class, first letter of each word starts with Upper Case. Example class JavaDemo

Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName()

Program File Name - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile. Example: Assume 'JavaDemo' is the class name. Then the file should be saved as 'JavaDemo.java'

public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program..

1.6 JVM (Java Virtual Machine)

Java Virtual Machine (also called as JVM) is the heart of entire Java program execution process. First of all, the .java program is converted into a .class file consisting of byte code instructions by the java compiler at the time of compilation. Remember, this java compiler is outside the JVM.

In JVM, there is a module (or program) called class loader sub system, which performs

the following instructions:

First of all, it loads the .class file into memory.

Then it verifies whether all byte code instructions are proper or not. If it finds any instruction suspicious, the execution is rejected immediately.

If the byte instructions are proper, then it allocates necessary memory to execute the program. This memory is divided into 5 parts, called run time data areas, which contain the data and results while running the program. These areas are as follows:

Method area: Method area is the memory block, which stores the c lass code, code of the variables and code of the methods in the Java program. (Method means functions written in a class).

Heap: This is the area where objects are created. Whenever JVM loads a class, method and heap areas are immediately created in it.

Page 12: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

11 | P a g e

Java Stacks: Method code is stored on Method area. But while running a method, it needs some more memory to store the data and results. This memory is allotted on Java Stacks. So, Java Stacks are memory area where Java methods are executed. While executing methods, a separate frame will be created in the Java Stack, where the method is executed. JVM uses a separate thread (or process) to execute each method.

PC (Program Counter) registers: These are the registers (memory areas), which contain memory address of the instructions of the methods. If there are 3 methods, 3 PC registers will be used to track the instruction of the methods.

Native Method Stacks: Java methods are executed on Java Stacks. Similarly, native methods (for example C/C++ functions) are executed on Native method stacks. To execute the native methods, generally native method libraries (for example C/C++ header files) are required. These header files are located and connected to JVM by a program, called Native method interface.

Execution Engine contains interpreter and JIT compiler which translates the byte code instructions into machine language which are executed by the microprocessor. Hot spot (loops/iterations) is the area in .class file i.e. executed by JIT compiler. JVM will identify the Hot spots in the .class files and it will give it to JIT compiler where the normal instructions and statements of Java program are executed by the Java interpreter. To illustrate how the bytecode looks like above avaDemo.java programs byte code is shown below.

D:\>javap -c JavaDemo

Compiled from "JavaDemo.java"

public class JavaDemo {

public JavaDemo();

Code:

0: aload_0

1: invokespecial #1 // Method java/lang/Object."<init>":()V

4: return

public static void main(java.lang.String[]);

Code:

0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;

3: ldc #3 // String Hello World

5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V

8: return

}

D:\>

1.7 Naming Conventions

Naming conventions specify the rules to be followed by a Java programmer while writing the names of packages, classes, methods etc.

1. Package names are written in small letters. e.g.: java.io, java.lang, java.awt etc

2. Each word of class name and interface name starts with a capital e.g.: Sample, AddTwoNumbers

3. Method names start with small letters then each word start with a capital e.g.: sum (), sumTwoNumbers (), minValue ()

4. Variable names also follow the same above method rule e.g.: sum, count, totalCount

5. Constants should be written using all capital letters e.g.: PI, COUNT

6. Keywords are reserved words and are written in small letters. e.g.: int, short, float, public, void

Page 13: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

12 | P a g e

1.8 Basic Datatypes

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or characters in these variables. There are two data types available in Java:

1. Primitive Data Types 2. Reference/Object Data Types

Primitive Data Types: There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.

1. byte: Byte data type is a 8-bit signed two's complement integer. Minimum value is -128 (-2^7) Maximum value is 127 (inclusive)(2^7 -1) Default value is 0 Byte data type is used to save space in large arrays, mainly in place of integers, since a

byte is four times smaller than an int. Example : byte a = 100 , byte b = -50

2. short: Short data type is a 16-bit signed two's complement integer. Minimum value is -32,768 (-2^15) Maximum value is 32,767(inclusive) (2^15 -1) Short data type can also be used to save memory as byte data type. A short is 2 times

smaller than an int Default value is 0.

Example : short s= 10000 , short r = -20000

3. int: Int data type is a 32-bit signed two's complement integer. Minimum value is - 2,147,483,648.(-2^31) Maximum value is 2,147,483,647(inclusive).(2^31 -1) Int is generally used as the default data type for integral values unless there is a

concern about memory. The default value is 0.

Example : int a = 100000, int b = -200000

4. long: Long data type is a 64-bit signed two's complement integer. Minimum value is -9,223,372,036,854,775,808.(-2^63) Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1) This type is used when a wider range than int is needed. Default value is 0L.

Example : long a = 100000L, int b = -200000L

5. float: Float data type is a single-precision 32-bit IEEE 754 floating point. Float is mainly used to save memory in large arrays of floating point numbers. Default value is 0.0f. Float data type is never used for precise values such as currency.

Example : float f1 = 234.5f

6. double: double data type is a double-precision 64-bit IEEE 754 floating point. This data type is generally used as the default data type for decimal values. generally

the default choice.

Page 14: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

13 | P a g e

Double data type should never be used for precise values such as currency. Default value is 0.0d.

Example : double d1 = 123.4

7. boolean: boolean data type represents one bit of information. There are only two possible values : true and false. This data type is used for simple flags that track true/false conditions. Default value is false.

Example : boolean one = true

8. char: char data type is a single 16-bit Unicode character. Minimum value is '\u0000' (or 0). Maximum value is '\uffff' (or 65,535 inclusive). Char data type is used to store any character.

Example . char letterA ='A'

1.9 Java Literals

Java Literals are syntactic representations of Boolean, character, numeric, or string data. Literals provide a means of expressing specific values in java program. A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. Literals can be assigned to any primitive type variable. For example:

byte a = 68;

char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals. For example:

int decimal = 100;

int octal = 0144;

int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are:

"Hello World"

"two\nlines"

"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example:

char a = '\u0001';

String a = "\u0001";

1.10 Java Symbolic Constants

Symbolic constants are named constants like: final double PI = 3.14 ;

These are constants because of the 'final' keywords, so they can NOT be reassigned a new value after being declared as final and they are symbolic, because they have a name. A NON symbolic constant is like the value of '2' in expression

int multi = 2 * 3

Page 15: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

14 | P a g e

1.11 Scope of Variable

The scope of a variable is the part of the program at which the variable name can be referenced or used.

You cannot refer to a variable before its declaration.

You can declare variables in several different places:

1. In a class body as class fields. Variables declared here are referred to as class-level variables.

2. As parameters of a method or constructor. 3. In a method's body or a constructor's body. 4. Within a statement block, such as inside a while or for block.

Variable scope refers to the accessibility of a variable.

The rule 1 is that variables defined in a block are only accessible from within the block. The scope of the variable is the block in which it is defined. For example, consider the following for statement.

public class MainClass

{

public static void main(String[] args)

{

for (int x = 0; x < 5; x++)

{

System.out.println(x);

}

}

}

Rule number 2 is a nested block can access variables declared in the outer block. Consider this code.

public class MainClass {

public static void main(String[] args) {

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

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

System.out.println(x);

System.out.println(y);

}

}

}

}

Variables declared as method parameters can be accessed from within the method body. Class-level variables are accessible from anywhere in the class.

If a method declares a local variable that has the same name as a class-level variable, the former will 'shadow' the latter. To access the class-level variable from inside the method body, use the this keyword.

Variable Scope in Block

public class MainClass {

public static void main(String[] args) {

int outer = 1;

{

int inner = 2;

System.out.println("inner = " + inner);

System.out.println("outer = " + outer);

}

int inner = 3;

System.out.println("inner = " + inner);

System.out.println("outer = " + outer);

Page 16: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

15 | P a g e

}

}

inner = 2

outer = 1

inner = 3

outer = 1

1.12 Type Casting & Conversion

Java supports two type of type Casting – Primitive Data Type Casting & Reference Type Casting. Reference type casting means assigning one Java object to another Java object. It comes with very strict rules. Java Data Type Casting comes with two flavors:

1 Implicit Casting 2 Explicit Casting

1. Implicit Casting (Widening Conversion) A data type of lower size (requires less memory) is assign to a data type of higher memory size. This is done implicitly (automatically) by JVM. The lower size is widen to higher size. This is also called as automatic type conversion. Examples: int x = 10; // occupies 4 bytes

double y = x; // occupies 8 bytes

System.out.println(y); // prints 10.0

In above code 4 byte integer value is assigned to 8 byte double value.

2. Explicit Type Casting (Narrowing Conversion)

A data type of higher size cannot be assigned to a data type of lower size. This is not done

implicitly by JVM and requires explicit casting; a casting is performed manually by the

programmer. The higher size is narrowed to lower size.

double x = 10.5; // 8 bytes

int y = x; // 4 bytes ; raises compilation error

In above code 8 byte double value is narrowed to 4 byte int value but it will generate an error.

So this can be done manually as:

double x = 10.5;

int y = (int) x;

1.13 Operators and Expressions

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups: 1 Arithmetic Operators 2 Relational Operators 3 Bitwise Operators 4 Logical Operators 5 Assignment Operators 6 Misc Operators

1.13.1 Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Assume integer variable A holds 10 and variable B holds 20 then:

Page 17: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

16 | P a g e

Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give 30

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

* Multiplication - Multiplies values on either side of the operator A * B will give 200

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

% Modulus - Divides left hand operand by right hand operand and returns remainder

B % A will give 0

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19

The following simple example program demonstrates the arithmetic operators. Copy and paste following Java program in Test.java file and compile and run this program:

public class Test {

public static void main(String args[]) {

int a = 10;

int b = 20;

int c = 25;

int d = 25;

System.out.println("a + b = " + (a + b) );

System.out.println("a - b = " + (a - b) );

System.out.println("a * b = " + (a * b) );

System.out.println("b / a = " + (b / a) );

System.out.println("b % a = " + (b % a) );

System.out.println("c % a = " + (c % a) );

System.out.println("a++ = " + (a++) );

System.out.println("b-- = " + (a--) );

// Check the difference in d++ and ++d

System.out.println("d++ = " + (d++) );

System.out.println("++d = " + (++d) );

}

}

This would produce following result:

a + b = 30

a - b = -10

a * b = 200

b / a = 2

b % a = 0

c % a = 5

a++ = 10

b-- = 11

d++ = 25

++d = 27

1.13.2 Relational Operators

There are following relational operators supported by Java language Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the value of two operands are equal or not, if yes then condition becomes true.

(A == B) is not true.

!= Checks if the value of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

Page 18: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

17 | P a g e

> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

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

(A >= B) is not true.

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

(A <= B) is true.

The following simple example program demonstrates the relational operators:

public class Test {

public static void main(String args[]) {

int a = 10;

int b = 20;

System.out.println("a == b = " + (a == b) );

System.out.println("a != b = " + (a != b) );

System.out.println("a > b = " + (a > b) );

System.out.println("a < b = " + (a < b) );

System.out.println("b >= a = " + (b >= a) );

System.out.println("b <= a = " + (b <= a) );

}

}

This would produce following result:

a == b = false

a != b = true

a > b = false

a < b = true

b >= a = true

b <= a = false

1.13.3 Bitwise Operators

Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------- a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 The following table lists the bitwise operators:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| Binary OR Operator copies a bit if it exists in eather operand.

(A | B) will give 61 which is 0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

Page 19: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

18 | P a g e

~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits.

(~A ) will give -60 which is 1100 0011

<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.

A << 2 will give 240 which is 1111 0000

>> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.

A >> 2 will give 15 which is 1111

>>> Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.

A >>>2 will give 15 which is 0000 1111

Assume integer variable A holds 60 and variable B holds 13 then: The following simple example program demonstrates the bitwise operators:

public class Test {

public static void main(String args[]) {

int a = 60; /* 60 = 0011 1100 */

int b = 13; /* 13 = 0000 1101 */

int c = 0;

c = a & b; /* 12 = 0000 1100 */

System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */

System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */

System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */

System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */

System.out.println("a << 2 = " + c );

c = a >> 2; /* 215 = 1111 */

System.out.println("a >> 2 = " + c );

c = a >>> 2; /* 215 = 0000 1111 */

System.out.println("a >>> 2 = " + c );

}

}

This would produce following result:

a & b = 12

a | b = 61

a ^ b = 49

~a = -61

a << 2 = 240

a >> 15

a >>> 15

1.13.4 Logical Operators

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

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero then then condition becomes true.

(A && B) is false.

Page 20: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

19 | P a g e

|| Called Logical OR Operator. If any of the two operands are non-zero then then condition becomes true.

(A || B) is true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

!(A && B) is true.

The following simple example program demonstrates the logical operators. Copy and paste following Java program in Test.java file and compile and run this program:

public class Test {

public static void main(String args[]) {

boolean a = true;

boolean b = false;

System.out.println("a && b = " + (a&&b));

System.out.println("a || b = " + (a||b) );

System.out.println("!(a && b) = " + !(a && b));

}

}

This would produce following result:

a && b = false

a || b = true

!(a && b) = true

1.13.5 Assignment Operators

There are following assignment operators supported by Java language

Operator Description Example

= Simple assignment operator, Assigns values from right side operands to left side operand

C = A + B will assign value of A + B into C

+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand

C += A is equivalent to C = C + A

-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand

C -= A is equivalent to C = C - A

*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand

C *= A is equivalent to C = C * A

/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand

C %= A is equivalent to C = C % A

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

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

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

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

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

The following simple example program demonstrates the assignment operators:

public class Test {

public static void main(String args[]) {

Page 21: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

20 | P a g e

int a = 10;

int b = 20;

int c = 0;

c = a + b;

System.out.println("c = a + b = " + c );

c += a ;

System.out.println("c += a = " + c );

c -= a ;

System.out.println("c -= a = " + c );

c *= a ;

System.out.println("c *= a = " + c );

a = 10;

c = 15;

c /= a ;

System.out.println("c /= a = " + c );

a = 10;

c = 15;

c %= a ;

System.out.println("c %= a = " + c );

c <<= 2 ;

System.out.println("c <<= 2 = " + c );

c >>= 2 ;

System.out.println("c >>= 2 = " + c );

c >>= 2 ;

System.out.println("c >>= a = " + c );

c &= a ;

System.out.println("c &= 2 = " + c );

c ^= a ;

System.out.println("c ^= a = " + c );

c |= a ;

System.out.println("c |= a = " + c );

}

}

This would produce following result:

c = a + b = 30

c += a = 40

c -= a = 30

c *= a = 300

c /= a = 1

c %= a = 5

c <<= 2 = 20

c >>= 2 = 5

c >>= 2 = 1

c &= a = 0

c ^= a = 10

c |= a = 10

1.13.6 Miscellaneous Operators

There are few other operators supported by Java Language.

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

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

Page 22: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

21 | P a g e

Following is the example:

public class Test {

public static void main(String args[]){

int a , b;

a = 10;

b = (a == 1) ? 20: 30;

System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;

System.out.println( "Value of b is : " + b );

}

}

This would produce following result:

Value of b is : 30

Value of b is : 20

instanceOf Operator:

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

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

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

String name = = 'James';

boolean result = name instanceOf String;

// This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type on the right. Following is one more example:

class Vehicle {}

public class Car extends Vehicle {

public static void main(String args[]){

Vehicle a = new Car();

boolean result = a instanceof Car;

System.out.println( result);

}

}

This would produce following result:

true

1.14 Precedence of Java Operators

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

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

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

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Page 23: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

22 | P a g e

Multiplicative * / % Left to right

Additive + - Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

1.15 Decision Making & Branching 1.15.1 if Statement

An if statement consists of a Boolean expression followed by one or more statements.

Syntax: The syntax of if statement is:

if(Boolean_expression)

{

//Statements will execute if the Boolean expression is true

}

If the boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed. Example:

public class Test {

public static void main(String args[]){

int x = 10;

if( x < 20 ){

System.out.print("This is if statement");

}

}

}

This would produce following result:

This is if statement

1.15.2 if…else Statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.

Syntax: The syntax of a if...else is:

Page 24: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

23 | P a g e

if(Boolean_expression){

//Executes when the Boolean expression is true

}else{

//Executes when the Boolean expression is false

}

Example:

public class Test {

public static void main(String args[]){

int x = 30;

if( x < 20 ){

System.out.print("This is if statement");

}else{

System.out.print("This is else statement");

}

}

}

This would produce following result:

This is else statement

1.15.3 else…if Ladder

if statement can be followed by an optional else if...else statement, which is very use full to test various conditions using single if...else if statement. When using if , else if , else statements there are few points to keep in mind.

An if can have zero or one else's and it must come after any else if's. An if can have zero to many else if's and they must come before the else. Once an else if succeeds, none of he remaining else if's or else's will be tested.

Syntax:

The syntax of a if...else is:

if(Boolean_expression 1){

//Executes when the Boolean expression 1 is true

}else if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true

}else if(Boolean_expression 3){

//Executes when the Boolean expression 3 is true

}else {

//Executes when the none of the above condition is true.

}

Example:

public class Test {

public static void main(String args[]){

int x = 30;

if( x == 10 ){

System.out.print("Value of X is 10");

}else if( x == 20 ){

System.out.print("Value of X is 20");

}else if( x == 30 ){

System.out.print("Value of X is 30");

}else{

System.out.print("This is else statement");

}

}

}

This would produce following result:

Value of X is 30

Page 25: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

24 | P a g e

1.15.4 Nested if…else Statement

It is always legal to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement.

Syntax:

if(Boolean_expression 1){

//Executes when the Boolean expression 1 is true

if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true

}

}

You can nest else if...else in the similar way as we have nested if statement. Example:

public class Test {

public static void main(String args[]){

int x = 30;

int y = 10;

if( x == 30 ){

if( y == 10 ){

System.out.print("X = 30 and Y = 10");

}

}

}

This would produce following result:

X = 30 and Y = 10

1.15.5 switch Statement

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

switch(expression){

case value :

//Statements

break; //optional

case value :

//Statements

break; //optional

//You can have any number of case statements.

default : //Optional

//Statements

}

The following rules must be consider while using switch statement:

1. The variable used in a switch statement can only be a byte, short, int, or char. 2. You can have any number of case statements within a switch. Each case is followed by the

value to be compared to and a colon. 3. The value for a case must be the same data type as the variable in the switch, and it must

be a constant or a literal. 4. When the variable being switched on is equal to a case, the statements following that case

will execute until a break statement is reached. 5. When a break statement is reached, the switch terminates, and the flow of control jumps

to the next line following the switch statement. 6. Not every case needs to contain a break. If no break appears, the flow of control will fall

through to subsequent cases until a break is reached.

Page 26: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

25 | P a g e

7. A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

Example:

public class Test {

public static void main(String args[]){

char grade = args[0].charAt(0);

switch(grade)

{

case 'A' :

System.out.println("Excellent!");

break;

case 'B' :

System.out.println("Very good!");

Break;

case 'C' :

System.out.println("Well done");

break;

case 'D' :

System.out.println("You passed");

case 'F' :

System.out.println("Better try again");

break;

default :

System.out.println("Invalid grade");

}

System.out.println("Your grade is " + grade);

}

}

Compile and run above program using various command line arguments. This would produce following result:

$ java Test a

Invalid grade

Your grade is a a

$ java Test A

Excellent!

Your grade is a A

$ java Test C

Well done

Your grade is a C

$

1.16 Decision Making & Looping

There may be a situation when we need to execute a block of code several number of times, and is often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the following three loops:

1. while Loop 2. do...while Loop 3. for Loop

As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

1.16.1 while Loop

A while loop is a control structure that allows you to repeat a task a certain number of times.

Syntax:

while(Boolean_expression)

{

//Statements

}

Page 27: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

26 | P a g e

When executing, if the boolean_expression result is true then the actions inside the loop will be executed. This will continue as long as the expression result is true. Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example:

public class Test {

public static void main(String args[]) {

int x = 10;

while( x < 20 ) {

System.out.print("value of x : " + x );

x++;

System.out.print("\n");

}

}

}

This would produce following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

1.16.2 do while Loop

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

do

{

//Statements

}while(Boolean_expression);

The Boolean expression appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

Example:

public class Test {

public static void main(String args[]){

int x = 10;

do{

System.out.print("value of x : " + x );

x++;

System.out.print("\n");

}while( x < 20 );

}

}

This would produce following result:

value of x : 10

value of x : 11

Page 28: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

27 | P a g e

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

1.16.3 for Loop

A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. A for loop is useful when you know how many times a task is to be repeated.

Syntax:

for(initialization; Boolean_expression; update)

{

//Statements

}

Flow of control in a for loop:

1. The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past the for loop.

3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the Boolean expression.

4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the for loop terminates.

Example:

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x+1) {

System.out.print("value of x : " + x );

System.out.print("\n");

}

}

}

This would produce following result:

value of x : 10

value of x : 11

value of x : 12

value of x : 13

value of x : 14

value of x : 15

value of x : 16

value of x : 17

value of x : 18

value of x : 19

1.16.4 Enhanced For Loop in Java

As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.

Page 29: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Department of Computer Technology

28 | P a g e

Syntax: The syntax of enhanced for loop is:

for(declaration : expression)

{

//Statements

}

Declaration . The newly declared block variable, which is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.

Expression . This evaluate to the array you need to loop through. The expression can be an array variable or method call that returns an array. Example

public class Test {

public static void main(String args[]){

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

for(int x : numbers ){

System.out.print( x );

System.out.print(",");

}

System.out.print("\n");

String [] names ={"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {

System.out.print( name );

System.out.print(",");

}

}

}

This would produce following result:

10,20,30,40,50,

James,Larry,Tom,Lacy,

1.16.5 break Keyword

The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement. The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

Syntax:

break;

Example:

public class Test {

public static void main(String args[]) {

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

for(int x : numbers ) {

if( x == 30 ) {

break;

}

System.out.print( x );

System.out.print("\n");

}

}

}

This would produce following result:

10

Page 30: Java programmingIntroduction to Java 1.1 Introduction Object-Oriented Programming supports all features of normal programming languages. In addition, it support some important concepts

Chapter 1: Introduction to Java

29 | P a g e

20

1.16.6 continue Keyword

The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.

In for loop, the continue keyword causes flow of control to immediately jump to the update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

Syntax: The syntax of continue is a single statement inside any loop:

continue;

Example

public class Test {

public static void main(String args[]) {

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

for(int x : numbers ) {

if( x == 30 ) {

continue;

}

System.out.print( x );

System.out.print("\n");

}

}

}

This would produce following result:

10

20

40

50