0% found this document useful (0 votes)
14 views55 pages

Java Programming Part 1

Java is a programming language developed by Sun Microsystems, released in 1995, and made open source in 2006. It is characterized by its object-oriented nature, platform independence, simplicity, security, and robustness, allowing it to run on various platforms through the Java Virtual Machine (JVM). The document also covers Java's syntax, data types, and provides examples of basic Java programs.

Uploaded by

myai123r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views55 pages

Java Programming Part 1

Java is a programming language developed by Sun Microsystems, released in 1995, and made open source in 2006. It is characterized by its object-oriented nature, platform independence, simplicity, security, and robustness, allowing it to run on various platforms through the Java Virtual Machine (JVM). The document also covers Java's syntax, data types, and provides examples of basic Java programs.

Uploaded by

myai123r
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

Part 1: Introduction to Java

Java programming language was originally developed by Sun Microsystems, which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems.s Java
platform (Java 1.0 [J2SE]).

On 13 November 2006, Sun released much of Java as free and open source software under the
terms of the GNU General Public License (GPL). Sun promised Write Once, Run Anywhere
(WORA), providing no-cost run-times on popular platforms.

On 8 May 2007 Sun finished the process, making all of Java's core code free and open-source,
aside from a small portion of code to which Sun did not hold the copyright.

The latest release of the Java Standard Edition is 7 (J2SE). With the advancement of Java and its
wide spread popularity, multiple configurations were built to suite various types of platforms.
Ex: J2EE for Enterprise Applications, J2ME for Mobile Applications.

Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java ME
respectively.

Java characteristics

Java is:

• Object Oriented: In java everything is an Object. Java can be easily extended since it is
based on the Object model.
• 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.
• Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP
java would be easy to master.
• Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
• 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.
• Portable: Being architectural neutral and having no implementation dependent aspects of
the specification makes Java portable.
• Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.

Page 1 of 55
• 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.
• 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.
• High Performance: With the use of Just-In-Time compilers Java enables high
performance.
• Distributed: Java is designed for the distributed environment of the internet.
• 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.

Why Java is different


What makes Java different from any other programming language is that the output of a Java
compiler is not an executable code. Rather, it is bytecode (.class files). Bytecode is a highly
optimized set of instructions designed to be executed by the Java run-time system called Java
Virtual Machine (JVM). A little explanation needed here - pretty much any programming
language like C, C++ when compiled gives the output as executable code. This executable
code interacts directly with the hardware or operating system to provide the desired output of
the application. A java application acts very differently in the scenario. The compiled
bytecode may be termed as half compiled executable code in the sense that it acts as an
intermediary, without interacting directly either with the hardware or operating system. JVM
provides the playground for bytecode and sits between Java application and the operating
system.

Modern language such as C, C++ are designed to be compiled to executable code mostly because
of performance concerns. Translating a Java program into bytecode makes it easier to run a
program in a wide variety of environments. The reason is pretty much straightforward, only the
JVM needs to be implemented for each operating system or platform. Once the run-time package
exists for a given system, any Java program can run on it. In other words - write a program in
Java, compile it, it will create a .class (which is the bytecode) file, take the class file in any
platform such as Windows, Linux, Mac etc. It will run provided there is a JVM installed on those
systems. While in case of C or C++, the program has to be compiled every time to run when

Page 2 of 55
transitioned from platform to platform basis. This makes programs written in C or C++, platform
specific, on the other hand Java, platform independent.

Though Java is platform independent but the details of JVM in which it runs differs from
platform to platform. The JVM which you may have installed in Windows will not install in
Linux. Each platform has a specific JVM which is packaged with JDK (java development kit
with JRE) or singleton JRE (only the run-time environment). Developers of the Java compiler
took all the pains of creating JVM for almost all platforms; you don't have to worry about that.

Popular Java Editors:

To write your java programs you will need a text editor. There are even more sophisticated IDE
available in the market. You can consider one of the following:

• Notepad: On Windows machine you can use any simple text editor like Notepad,
TextPad.
• Netbeans: is a Java IDE that is open source and free which can be downloaded from
[Link]
• Eclipse: is also a java IDE developed by the eclipse open source community and can be
downloaded from [Link]
• [Link]: a simple IDE developed at Rice University.

Java application programming

Most programs you will come across generally do three primary things – get the input, process
the information and display the result. Let’s start with examples that demonstrate how your
program can display messages and how they can obtain information from the user for processing.

First Program

Let us consider a simple application that displays a line of text

//simple text printing program

//file name: [Link]


package mypackage;
/*
* In Java everything is written within a class and the
* filename and class name remains the same, in this case
* [Link]
*/
public class MyClass
{
//main method begins execution of Java application
public static void main(String[] args) // args refers to arguments accepted by main function
{

Page 3 of 55
[Link]("My first Java program");
}//end of main method
}//end of class MyClass
Let us now consider each line of the program in order.
Comments
The program begins with //, indicating that the remainder of the line is a comment. Programmers
insert comments to document programs and improve their readability. This helps other people to
read and understand programs. The java compiler ignores comments, so they do not cause the
computer to perform any action when the program runs. There are two way comments are
inserted in Java code: one is called single line comment represented by // i.e. comment terminates
at the end of line. Another is multiple line comment represented by /* */. This type of comments
begin with the delimiter /* and ends with */. Also there is another type of comments called
javadoc comment that are delimited by /** and */. These type of comments are used to embed
program documentation directly in the program and preferred Java commenting format in the
industry, but the basic idea is same for all formats of comment.
Package
The declaration package mypackage indicates a user defined package. Placing a package
declaration at the beginning of a Java source file indicates that the class declared in the file is a
part of the specified package.
User defined class
The declaration of class MyClass is the user defined class defined by you. Every program in
Java consists of at least one such class declaration. The class is a keyword which introduces class
declaration in Java and is immediately followed by the class name (here, MyClass). Class name
is an identifier consisting of letters, digits, underscores(_), dollar signs($) but cannot begin with
digit and does not contain spaces.
Note: Keywords are nothing but reserved words used by Java. Java is case sensitive i.e. b2 and
B2 are different. By convention, in Java all class names begin with capital letter and capitalize
the first letter of each word they include. Also observe that each statement is delimited by a
semicolon ';' to signify the end of a statement in Java, failure to indicate one is a compile time
error
Braces
A left brace, {, begins the body of a class, function, loops, conditional statement etc. And the
corresponding ,}, ends the body. There should always be a matching pair of braces.
Method
The parenthesis, (), after the identifier main indicate that it is a program building block called
method. A Java class declaration normally contain one or more methods. For a Java Application
there must be one main method otherwise the JVM will not start the execution. The main method
is the starting point of a Java Application. Methods are like verbs in a sentence. It takes some
information, process it and return information when they complete their task
Standard object and method
[Link] is known as standard output object. Method [Link] displays a line of text
in the console window. When it completes its task, it positions the output cursor to the beginning
of the next line in the console. There are several variations of this method.
[Link]("My first Java program");

This will print the text and the cursor will be at the end of the line.

Page 4 of 55
[Link]("My first Java program");

This will print the text and the cursor will be at the beginning of the next line

[Link]("My first Java program\n");

This will print the text and the cursor will be at the beginning of the next line due to '\n'

[Link]("My first Java program");

print the text and the cursor will be at the end of the line, a formatted print function.

Let's modify our first program and try to print same text with similar formatted output with
different print function
//simple text printing program
//file name: [Link]
package mypackage;
/*
* In Java everything is written within a class and the
* filename and class name remains the same, in this case
* [Link]
* */
public class MyClass
{
// main method begins execution of Java application
public static void main(String[] args)
{
//with println function
[Link]("Using println function");
[Link]("Hello World");
[Link]("Welcome to the world of Java");
// with print function
[Link]("Using print function\n");
[Link]("Hello World\n");
[Link]("Welcome to the world of Java\n");
// with printf function
[Link]("Using printf function\n");
[Link]("Hello World\n");
[Link]("Welcome to the world of Java\n");
}//end of main method
}//end of class MyClass

Escape sequence
The \n used in the above programs is called an escape sequence. There are several escape
sequences in Java as follows

Page 5 of 55
• \n Newline. Position the screen cursor at the beginning of the next line.
• \t Horizontal tab. Move the screen cursor to the next tab stop.
• \r Carriage return. Position the screen cursor at the beginning of the current line and do
not advance to the next line. Any character written after the carriage return overwrites the
character previously output on that line.
• \\ Backslash, used to print backslash '\' character (imagine, how will you print \ in the
output without double backslash, \\)
• \” Double quote, used to print double quote. Imagine how to print exactly this line –
Teacher says, “Very Good”.

Third Program
Let's write a program to input two numbers from the user, add them up and show the result.

package mymath;
import [Link];
public class SimpleMath {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
int a;
int b;
int sum;
[Link]("Enter first number: ");
a = [Link]();
[Link]("Enter second number: ");
b = [Link]();
sum = a + b;
[Link]("Sum is %d\n", sum);
}
}
Here,
import [Link]

is an import declaration that helps the compiler locate a class that is used in this program. A great
strength of Java is its rich set of predefined classes that programmers can reuse rather than invent
them. These classes are grouped into packages – named collection of classes. These packages are
collectively referred to as Java class library or the Java API (Application Program
Interface). Programmers use import declarations to identify the predefined classes used in a Java
program. In the above program import declaration indicates that this example uses Java's
predefined Scanner class from package [Link].

Scanner input = new Scanner([Link]);

is a variable declaration statement that specifies the type and name of a variable (input) that is
used in this program. A variable is a location in the computer's memory where values can be
stored for use later in the program. All variables must be declared with a name and a type before
they are used. A Scanner is a built in Java class that enables a program to read data for use in a

Page 6 of 55
program and initialize the input variable with equal sign (=). The expression new
Scanner([Link]) creates a Scanner object that reads data typed by the user at the keyboard.
[Link] is a standard input object (Similarly, [Link] is a standard output object) that
enables Java application to read information typed by the user.

int a;
int b;
int sum;
these variables will hold integers values and are of primitive data type int. Other such primitive
data types are – boolean, byte, short, char, long, float and double. We shall see their usages in
other programs down the line. The primitive data types start with lower case letter, unlike all
other classes in Java which start with capital one (like Scanner)
sum = a + b;
Here values contained in a and in b are added through + operator and assigned to the variable
sum.
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 kinds of data types available in Java:

• Primitive Data Types


• 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.

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

short:

• Short data type is a 16-bit signed two's complement integer.


Page 7 of 55
• 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

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

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

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

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.
• Double data type should never be used for precise values such as currency.
• Default value is 0.0d.
• Example : double d1 = 123.4

Page 8 of 55
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

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'

Reference Data Types:

Java Literals:

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 indicates 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:

Page 9 of 55
char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char literals as well. They
are:

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t Tab

\" Double quote

\' Single quote

\\ Backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Points to Remember:

• All numeric data types are signed(+/-).


• The size of data types remain the same on all platforms (standardized)
• char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java
supports internationalization. UNICODE is a character set which covers all known scripts and
languages in the world

About Java programs, it is very important to keep in mind the following points.

• Case Sensitivity - Java is case sensitive which means identifier Hello and hello would
have different meaning in Java.
• Class Names - For all class names the first letter should be in Upper Case.

If several words are used to form a name of the class each inner words first letter should

Page 10 of 55
be in Upper Case.

Example class MyFirstJavaClass


• 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 'MyFirstJavaProgram' is the class name. Then the file should be saved
as '[Link]'
• public static void main(String args[]) - java program processing starts from the main()
method which is a mandatory part of every java program..

Java Identifiers:

All java components require names. Names used for classes, variables and methods are called
identifiers.

In java there are several points to remember about identifiers. They are as follows:

• All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an


underscore (_).
• After the first character identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly identifiers are case sensitive.
• Examples of legal identifiers:age, $salary, _value, 1_value
• Examples of illegal identifiers : 123abc, -salary

Java Modifiers:

Like other languages it is possible to modify classes, methods etc by using modifiers. There are
two categories of modifiers.

• Access Modifiers : default, public , protected, private


• Non-access Modifiers : final, abstract, strictfp

Variables
A variable can be thought of as a container which holds value for you during the life of your program.

Page 11 of 55
Every variable is assigned a data type which designates the type and quantity of a value it can hold.

To use a variable in your program you need to perform 2 steps

1. Variable Declaration
2. Variable Initialization

1) Variable Declaration

To declare a variable , you must specify the data type & give the variable a unique name.

Examples of other Valid Declarations are:

int a,b,c;

float pi;

double d;

char a;

2) Variable Initialization:

To initialize a variable you must assign it a valid value.

Example of other Valid Initializations are

pi =3.14f;

do =20.22d;

a=’v’;

Page 12 of 55
You can combine variable declaration and initialization.

Example :

int a=2,b=4,c=6;

float pi=3.14f;

double do=20.22d;

char a=’v’;

Variable Type Conversion & Type Casting

A variable of one type can receive the value of another type. Here there are 2 cases -

case 1) Variable of smaller capacity is assigned to another variable of bigger capacity.

This process is Automatic, and non-explicit and is known as Conversion

case 2) Variable of larger capacity is assigned to another variable of smaller capacity

In such cases you have to explicitly specify the type cast operator. This process is known as
Type Casting.

Page 13 of 55
In case, you do not specify a type cast operator, the compiler gives an error. Since this rule is
enforced by the compiler, it makes the programmer aware that the conversion he is about to do
may cause some loss in data and prevents accidental losses.

Assignement: To Understand Type Casting

Step 1) Copy the following code into an editor.

1 class Demo{

2 public static void main(String args[]){

3 byte x;

4 int a=270;

5 double b =128.128;

[Link]("int converted to byte");


6
x=(byte) a;
7
[Link]("a and x "+ a +" "+x);
8
[Link]("double converted to int");
9
a=(int) b;
10
[Link]("b and a "+ b +" "+a);
11 [Link](" double converted to byte");

12 x= b;

13 [Link]("b and x "+b +" "+x);

14 }
}
15

Step 2) Save, Compile & Run the code.

Step 2) Error =? Try to debug. Hint – Typecasting is missing for one operation.

Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:

Page 14 of 55
• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Miscellaneous Operators

The 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:

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
% B % A will give 0
remainder

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

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

The 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
== (A == B) is not true.
condition becomes true.

!= Checks if the value of two operands are equal or not, if values are not (A != B) is true.

Page 15 of 55
equal then condition becomes true.

Checks if the value of left operand is greater than the value of right
> (A > B) is not true.
operand, if yes then condition becomes true.

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

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

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

The 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 performs 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:

Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B) will give 12

Page 16 of 55
operands. which is 0000 1100

(A | B) will give 61
| Binary OR Operator copies a bit if it exists in eather operand.
which is 0011 1101

Binary XOR Operator copies the bit if it is set in one operand but not (A ^ B) will give 49
^
both. which is 0011 0001

Binary Ones Complement Operator is unary and has the efect of 'flipping' (~A ) will give -60
~
bits. which is 1100 0011

Binary Left Shift Operator. The left operands value is moved left by the A << 2 will give 240
<<
number of bits specified by the right operand. which is 1111 0000

Binary Right Shift Operator. The left operands value is moved right by the A >> 2 will give 15
>>
number of bits specified by the right operand. which is 1111

Shift right zero fill operator. The left operands value is moved right by the
A >>>2 will give 15
>>> number of bits specified by the right operand and shifted values are filled
which is 0000 1111
up with zeros.

The 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
&& (A && B) is false.
condition becomes true.

Called Logical OR Operator. If any of the two operands are non zero then
|| (A || B) is true.
then condition becomes true.

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

The Assignment Operators:

There are following assignment operators supported by Java language:

Page 17 of 55
Operator Description Example

C = A + B will
Simple assignment operator, Assigns values from right side operands to
= assigne value of A +
left side operand
B into C

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

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

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

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

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

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

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

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

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

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

Miscellaneous Operators

There are few other operators supported by Java Language.

Page 18 of 55
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

Following is the example:

public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
[Link]( "Value of b is : " + b );

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


[Link]( "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();

Page 19 of 55
boolean result = a instanceof Car;
[Link]( result);
}
}

This would produce following result:

true

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:

For example 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 precedenace operators will be evaluated first.

Category Operator Associativity

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

Unary ++ - - ! ~ Right to left

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

Page 20 of 55
Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right

Quizzes

1. Which one is a standard input object


(1) [Link]
(2) println
(3) [Link]
(4) printf

2. Which one is a standard output object


(1) [Link]
(2) println
(3) [Link]
(4) printf

3. The method from which Java program starts is called


(1) class
(2) main
(3) printf
(4) None of the above

4. which of the following is a primitive data type


(1) int
(2) float
(3) char
(4) All of the above

5. Which package contains Scanner object


(1) [Link]
(2) [Link]
(3) [Link]
(4) [Link]

6. Which of the following is a valid comment


(1) /* ...*/
(2) /**... */
(3) //...
(4) All of the above

Page 21 of 55
7. Which of the following is not a valid variable declaration
(1) int 67val
(2) double char99
(3) char b23$
(4) boolean _11;

8. Java considers variables number and NuMbEr to be the same


(1) True
(2) False
(3) Most of the time true
(4) Sometimes false

9. Every statement ends with


(1) =
(2) }
(3) )
(4) ;

10. are reserved for use by Java


(1) methods
(2) Packages
(3) Keywords
(4) All of the above

11. Parenthesis and braces always need to balance in Java code


(1) True
(2) False

12. The predefined classes of Java are called


(1) Packages
(2) Methods
(3) Java API
(4) User defined classes
Tasks: Try yourself

• Write an application that asks the user to enter two integers, obtain them from the user
and prints their sum, product, difference and quotient.
• Write an application that inputs three integers from the user and displays the average.

Control Structures
Generally statements in a program are executed sequentially one after another in the order they
are written. There are java statements that enable the programmer to specify that the next
statement to execute is not necessarily the next one in the sequence. This transfer of control can
be specified according to the logical requirement of the program through selection statements
and repetition statements.

Page 22 of 55
There are two types of decision making statements in Java. They are:

• if statements
• switch statements

The if Statement:

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

Syntax:

The syntax of an 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 ){
[Link]("This is if statement");
}
}
}

This would produce following result:

This is if statement

The 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 23 of 55
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 ){
[Link]("This is if statement");
}else{
[Link]("This is else statement");
}
}
}

This would produce following result:

This is else statement

The if...else if...else Statement:

An if statement can be followed by an optional else if...else statement, which is very usefull 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 {

Page 24 of 55
public static void main(String args[]){
int x = 30;

if( x == 10 ){
[Link]("Value of X is 10");
}else if( x == 20 ){
[Link]("Value of X is 20");
}else if( x == 30 ){
[Link]("Value of X is 30");
}else{
[Link]("This is else statement");
}
}
}

This would produce following result:

Value of X is 30

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:

The syntax for a nested if...else is as follows:

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 ){
[Link]("X = 30 and Y = 10");
}
}
}
}

Page 25 of 55
This would produce following result:

X = 30 and Y = 10

The 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:

The syntax of switch is:

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 apply to a switch statement:

• The variable used in a switch statement can only be a byte, short, int, or char.
• 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.
• 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.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• 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.
• 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);
char grade = 'C';

Page 26 of 55
switch(grade)
{
case 'A' :
[Link]("Excellent!");
break;
case 'B' :
case 'C' :
[Link]("Well done");
break;
case 'D' :
[Link]("You passed");
case 'F' :
[Link]("Better try again");
break;
default :
[Link]("Invalid grade");
}
[Link]("Your grade is " + grade);
}
}

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

$ java Test
Well done
Your grade is a C
$
Repetition statements or Loops

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:

• while Loop
• do...while Loop
• for Loop

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

The while Loop:

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

Syntax:

The syntax of a while loop is:

while(Boolean_expression)

Page 27 of 55
{
//Statements
}

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 ) {
[Link]("value of x : " + x );
x++;
[Link]("\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

The 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:

The syntax of a do...while loop is:

do
{
//Statements
}while(Boolean_expression);

Page 28 of 55
Notice that 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{
[Link]("value of x : " + x );
x++;
[Link]("\n");
}while( x < 20 );
}
}

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

The 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:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

Page 29 of 55
• 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.
• 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.
• 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.
• 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) {
[Link]("value of x : " + x );
[Link]("\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

Enhanced for loop in Java:

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

Syntax:

The syntax of enhanced for loop is:

for(declaration : expression)
{
//Statements
}

Page 30 of 55
• 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 ){
[Link]( x );
[Link](",");
}
[Link]("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
[Link]( name );
[Link](",");
}
}
}

This would produce following result:

10,20,30,40,50,
James,Larry,Tom,Lacy,

The 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:

The syntax of a break is a single statement inside any loop:

break;

Example:
public class Test {

public static void main(String args[]) {


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

Page 31 of 55
for(int x : numbers ) {
if( x == 30 ) {
break;
}
[Link]( x );
[Link]("\n");
}
}
}

This would produce following result:

10
20

The 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 a 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 a 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;
}
[Link]( x );
[Link]("\n");
}
}
}

This would produce following result:

10
20

Page 32 of 55
40
50

Nested Loops
Any of the for, while or do-while loops may be nested i.e. We may put one loop inside another
with pretty much any combination like a while loop inside a for loop or for inside do-while etc.
Lets try an example how it can be done.

//program to print the pattern


/*
*1
* 12
* 123
* 1234
*/
public class Pattern1 {
public static void main(String[] args) {
int height = 4;
for(int i=1;i<=height;i++){
for(int j=1;j<=i;j++){
[Link](j);
}
[Link]("");
}
}// end of main
}// end of class

Quizzes
1. Which of the following are selection statements
(1) if, while, for
(2) if, if...else, while
(3) if, if...else, switch
(4) if, if...else, do-while
2. When break is written inside a loop what does it do
(1) control gets out of the loop
(2) control return to the previous statement
(3) controls remains there
(4) control goes to the beginning of the loop
3. When continue is written inside a loop what does it do
(1) control gets out of the loop
(2) control return to the previous statement
(3) controls remains there
(4) control goes to the beginning of the loop
4. Which of the following is not a loop
(1) for
(2) while
(3) if...else

Page 33 of 55
(4) do...while
6. What do you think following program would do

public class XYZ {


public static void main(String[] args) {
for (int i = 0; true; i++)
{
[Link]("hehe!");
}
}
}
(1) The program will never run
(2) The program has a syntax error in the for loop
(3) “hehe” will be printed
(4) The program will not stop printing
7. What do you think following program would do
int a=5;
if(a%2==0)
[Link]("even");
(1) The program will print - even
(2) The program will print - odd
(3) There is a syntax error
(4) Nothing will be printed
8. ! operator
(1) reverses the condition
(2) there is no such operator
(3) a factorial sign
(4) none of the above
9. if a=5, b=a++, then a, b respectively contains
(1) 5, 5
(2) 6, 5
(3) 6, 6
(4) 5, 6
10. if a=5, b=--a, then a, b respectively contains
(1) 5, 5
(2) 4, 4
(3) 5, 4
(4) 4, 5
11. What happen when no break is stated inside switch block
(1) control does not enter inside switch
(2) All the cases are evaluated
(3) Logical error
(4) Program does not compile
12. What will be the output of the following code
int i=10;
for(;;i++)

Page 34 of 55
{
if(i>10)
break;
else
[Link](i);
}
(1) 10
(2) Never ending loop
(3) The program will not compile
(4) Prints 1 through 10
Tasks: Try yourself

Write a program to print the following patterns

*
**
***
****

1
22
333
4444
1
121
12321
1234321
1
010
10101
0101010

• Write a program to reverse a number

Method
Programs we write to solve real world problems are actually much larger than the programs we
have learned so far. As we know solving a problem starts from the first line of code and large
programs are an illusion of many a smaller pieces of code compiled as a group that gives the idea
of a larger problem scenario. It is like taking care of the words with the view of creating a bigger
sentence. Thus to penetrate the problem, we simply follow the technique – divide and conquer
through methods.

What is a Method?

Page 35 of 55
A Java method is a collection of statements that are grouped together to perform an operation. When
you call the [Link] method, for example, the system actually executes several statements in
order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a
method with or without parameters, overload methods using the same names, and apply method
abstraction in the program design.

Creating a Method:

In general, a method has the following syntax:

modifier returnValueType methodName(list of parameters) {


// Method body;
}

A method definition consists of a method header and a method body. Here are all the parts of a
method:

• Modifiers: The modifier, which is optional, tells the compiler how to call the method.
This defines the access type of the method.
• Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without
returning a value. In this case, the returnValueType is the keyword void.
• Method Name: This is the actual name of the method. The method name and the
parameter list together constitute the method signature.
• Parameters: A parameter is like a placeholder. When a method is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a method.
Parameters are optional; that is, a method may contain no parameters.
• Method Body: The method body contains a collection of statements that define what the
method does.

Note: In certain other languages, methods are referred to as procedures and functions. A method
with a nonvoid return value type is called a function; a method with a void return value type is
called a procedure.

Page 36 of 55
Example:

Here is the source code of the above defined method called max(). This method takes two
parameters num1 and num2 and returns the maximum between the two:

/** Return the max between two numbers */


public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;

return result;
}
User defined function
Methods can be invoked from Java API library or you may create your own. A method that is
created by programmer is called user defined method/function. Some such user defined
functions structure may be as follows:
int calcFactorial(int number) {...} // takes one argument and return int value
void setName(String name){...} //takes one argument and returns nothing
Object getDateOfBirth(){...} // takes no argument and returns an Object
boolean isValid(String userName, String password){...}
//takes two argument and returns boolean value – true or false

static Methods

As we have seen, every class provides methods that perform common tasks on objects of the
class. For example to input data from keyboard, you have called methods on a Scanner object
that was initialized in its constructor to obtain input from the standard input ([Link]).
Although most methods execute in response to method calls on specific objects, this is not the
case. Sometimes a method performs a task that does not depend on the contents of any object.
Such method applies to the class in which it is declared as a whole and is known as a static
method or a class method. To declare a method static, place the keyword static before the return
type in the method's declaration. One can call any static method by specifying the name of the
class in which the method is declared, followed by a dot(.) and the method name, as in
[Link](arguments)
e.g. [Link](32.0);
For example, you can calculate the square root of 49.0 with the static method call
[Link](49.0).

Why is main method declared static

When Java application run, JVM attempts to invoke main method of the class you specify.
Declaring main as static allows the JVM to invoke main without creating an instance of the class
such as – [Link]. JVM simply seeks for main function inside the classes and tries
to execute it to kick start the application.

Page 37 of 55
Calling a Method:

In creating a method, you give a definition of what the method is to do. To use a method, you
have to call or invoke it. There are two ways to call a method; the choice is based on whether the
method returns a value or not.

When a program calls a method, program control is transferred to the called method. A called
method returns control to the caller when its return statement is executed or when its method-
ending closing brace is reached.

If the method returns a value, a call to the method is usually treated as a value. For example:

int larger = max(30, 40);

If the method returns void, a call to the method must be a statement. For example, the method
println returns void. The following call is a statement:

[Link]("Welcome to Java!");

Example:

Following is the example to demonstrate how to define a method and how to call it:

public class TestMax {


/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
[Link]("The maximum between " + i +
" and " + j + " is " + k);
}

/** Return the max between two numbers */


public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;

return result;
}
}

This would produce following result:

The maximum between 5 and 2 is 5

Page 38 of 55
This program contains the main method and the max method. The main method is just like any
other method except that it is invoked by the JVM.

The main method's header is always the same, like the one in this example, with the modifiers
public and static, return value type void, method name main, and a parameter of the String[]
type. String[] indicates that the parameter is an array of String.

There are three ways to call a method

1. Using method name such as – getName()


2. Using a variable that contains a reference to an object, followed by a dot(.) and the
method name to call a method referenced by that object.
3. Using the class name and a dot(.) to call a static method of a class.

Lets try an example to implement the above type of function call

import [Link];
public class MaxFinder {
//user defined function public
void findMax(){
Scanner input = new Scanner([Link]);
double val1 = [Link]();// Java API library function
double val2 = [Link]();// for keyboard input
double val3 = [Link]();// function called with referenced object - input
[Link]();
double result = max(val1, val2, val3); // user defined function call
[Link]("Maximum value is: "+ result);
}

//user defined function


public double max(double n1, double n2, double n3){
double maximum = n1;
if(n2>maximum)
maximum = n2;
if(n3>maximum)
maximum = n3;
return maximum;
}

//user defined static function


public static void doubleRange(){
[Link](Double.MIN_VALUE);
[Link](Double.MAX_VALUE);
}
}// end of MaxFinder class

Page 39 of 55
//
public class MaxFinderApp {
public static void main(String[] args) {
MaxFinder maxFinder = new MaxFinder();
[Link]();
[Link]();
}// end of main
} //end of MaxFinderApp class

Note: static method can call only other static methods of the same class directly and can
manipulate only static fields in the same class directly.

The void Keyword:

This section shows how to declare and invoke a void method. Following example gives a
program that declares a method named printGrade and invokes it to print the grade for a given
score.

Example:
public class TestVoidMethod {

public static void main(String[] args) {


printGrade(78.5);
}

public static void printGrade(double score) {


if (score >= 90.0) {
[Link]('A');
}
else if (score >= 80.0) {
[Link]('B');
}
else if (score >= 70.0) {
[Link]('C');
}
else if (score >= 60.0) {
[Link]('D');
}
else {
[Link]('F');
}
}
}

This would produce following result:

Page 40 of 55
Here the printGrade method is a void method. It does not return any value. A call to a void
method must be a statement. So, it is invoked as a statement in line 3 in the main method. This
statement is like any Java statement terminated with a semicolon.

Passing Parameters by Values:

When calling a method, you need to provide arguments, which must be given in the same order
as their respective parameters in the method specification. This is known as parameter order
association.

For example, the following method prints a message n times:

public static void nPrintln(String message, int n) {


for (int i = 0; i < n; i++)
[Link](message);
}

Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3)
statement passes the actual string parameter, "Hello", to the parameter, message; passes 3 to n;
and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be wrong.

When you invoke a method with a parameter, the value of the argument is passed to the
parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal
value, the value of the variable is passed to the parameter. The variable is not affected, regardless
of the changes made to the parameter inside the method.

For simplicity, Java programmers often say passing an argument x to a parameter y, which
actually means passing the value of x to y.

Example:

Following is a program that demonstrates the effect of passing by value. The program creates a
method for swapping two variables. The swap method is invoked by passing two arguments.
Interestingly, the values of the arguments are not changed after the method is invoked.

public class TestPassByValue {

public static void main(String[] args) {


int num1 = 1;
int num2 = 2;

[Link]("Before swap method, num1 is " +


num1 + " and num2 is " + num2);

// Invoke the swap method


swap(num1, num2);
[Link]("After swap method, num1 is " +
num1 + " and num2 is " + num2);
}

Page 41 of 55
/** Method to swap two variables */
public static void swap(int n1, int n2) {
[Link]("\tInside the swap method");
[Link]("\t\tBefore swapping n1 is " + n1
+ " n2 is " + n2);
// Swap n1 with n2
int temp = n1;
n1 = n2;
n2 = temp;

[Link]("\t\tAfter swapping n1 is " + n1


+ " n2 is " + n2);
}
}

This would produce following result:

Before swap method, num1 is 1 and num2 is 2


Inside the swap method
Before swapping n1 is 1 n2 is 2
After swapping n1 is 2 n2 is 1
After swap method, num1 is 1 and num2 is 2

Overloading Methods:

The max method that was used earlier works only with the int data type. But what if you need to
find which of two floating-point numbers has the maximum value? The solution is to create
another method with the same name but different parameters, as shown in the following code:

public static double max(double num1, double num2) {


if (num1 > num2)
return num1;
else
return num2;
}

If you call max with int parameters, the max method that expects int parameters will be invoked;
if you call max with double parameters, the max method that expects double parameters will be
invoked. This is referred to as method overloading; that is, two methods have the same name
but different parameter lists within one class.

The Java compiler determines which method is used based on the method signature. Overloading
methods can make programs clearer and more readable. Methods that perform closely related
tasks should be given the same name.

Overloaded methods must have different parameter lists. You cannot overload methods based on
different modifiers or return types. Sometimes there are two or more possible matches for an
invocation of a method due to similar method signature, so the compiler cannot determine the
most specific match. This is referred to as ambiguous invocation.

Page 42 of 55
The Scope of Variables:

The scope of a variable is the part of the program where the variable can be referenced. A
variable defined inside a method is referred to as a local variable.

The scope of a local variable starts from its declaration and continues to the end of the block that
contains the variable. A local variable must be declared before it can be used.

A parameter is actually a local variable. The scope of a method parameter covers the entire
method.

A variable declared in the initial action part of a for loop header has its scope in the entire loop.
But a variable declared inside a for loop body has its scope limited in the loop body from its
declaration to the end of the block that contains the variable as shown below:

You can declare a local variable with the same name multiple times in different non-nesting
blocks in a method, but you cannot declare a local variable twice in nested blocks.

Quizzes
1. A method is invoked with
(1) a method call
(2) a stack
(3) return type
(4) function signature
2. A variable known only within the method in which it is declared is called
(1) global variable
(2) function variable
(3) local variable
(4) variable
3. The statement in a called method can be used to pass the value back to the calling
method
(1) break
(2) continue
(3) return
(4) void
4. Which keyword indicate that the method does not return a value
(1) int

Page 43 of 55
(2) void
(3) public
(4) static
5. Data can be added or removed only from the of a stack
(1) bottom
(2) void
(3) left side
(4) none of the above
6. Stacks are known as which of the following data structure
(1) FIFO
(2) LRU
(3) Tree
(4) LIFO
7. static methods are called
(1) static function
(2) class method
(3) main function
(4) none of the above
8. double is a primitive
(1) class
(2) method
(3) object
(4) data type
9. User defined functions are created by
(1) Java API Library
(2) Java Virtual Machine
(3) Java Application
(4) programmers
10. Java application without main declared as static
(1) will not run
(2) will not compile
(3) will run without error
(4) will neither compile nor run
11. A static method can only manipulate static fields
(1) true
(2) false
Task: Try yourself

• Write a program with user defined function that prompts the user for temperature in
Fahrenheit and convert it into Celsius. (hint. Celsius = 5.0/9.0 * (Fahrenheit-32);
• Write a method gcd that returns the greatest common divisor of two integers.
• Modify the MaxFinder program into MinFinder program.
• Write a method that takes a number as argument and returns the number with digits
reversed (e.g. 1234 reversed to 4321)

Arrays
Page 44 of 55
Arrays are a very important data structure encountered by programmers. It is basically a
collection of related items and is of fixed length entries. The variable declaration we learned so
far occupies a single location of memory, on the other hand array occupies a consecutive
collection of memory. But the elements contained in the array must be of same type.

Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.

This sectionl introduces how to declare array variables, create arrays, and process arrays using
indexed variables.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable:

dataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.

Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[]
comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example:

The following code snippets are examples of this syntax:

double[] myList; // preferred way.

or

double myList[]; // works but not preferred way.

Creating Arrays:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

Page 45 of 55
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to [Link]-1.

Example:

Following statement declares an array variable, myList, creates an array of 10 elements of double
type, and assigns its reference to myList.:

double[] myList = new double[10];

Following picture represents array myList. Here myList holds ten double values and the indices
are from 0 to 9.

Processing Arrays:

When processing array elements, we often use either for loop or foreach loop because all of the
elements in an array are of the same type and the size of the array is known.

Example:

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

Page 46 of 55
// Print all the array elements
for (int i = 0; i < [Link]; i++) {
[Link](myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < [Link]; i++) {
total += myList[i];//total=total+ myList[i];
}
[Link]("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < [Link]; i++) {
if (myList[i] > max)
max = myList[i];
}
[Link]("Max is " + max);
}
}

This would produce following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

The foreach Loops:

JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.

Example:

The following code displays all the elements in the array myList:

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
[Link](element);
}
}
}

This would produce following result:

Page 47 of 55
1.9
2.9
3.4
3.5

Passing Arrays to Methods:

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For
example, the following method displays the elements in an int array:

public static void printArray(int[] array) {


for (int i = 0; i < [Link]; i++) {
[Link](array[i] + " ");
}
}

You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2:

printArray(new int[]{3, 1, 2, 6, 4, 2});

Returning an Array from a Method:

A method may also return an array. For example, the method shown below returns an array that
is the reversal of another array:

public static int[] reverse(int[] list) {


int[] result = new int[[Link]];

for (int i = 0, j = [Link] - 1; i < [Link]; i++, j--) {


result[j] = list[i];
}
return result;
}

The Arrays Class:

The [Link] class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all primitive
types.

SN Methods with Description

public static int binarySearch(Object[] a, Object key)


Searches the specified array of Object ( Byte, Int , double etc) for the specified value using the binary
1
search algorithm. The array must be sorted prior to making this call. This returns index of the search
key, if it is contained in the list; otherwise, (-(insertion point + 1).

Page 48 of 55
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered
2 equal if both arrays contain the same number of elements, and all corresponding pairs of elements in
the two arrays are equal. This returns true if the two arrays are equal. Same method could be used
by all other premitive data types ( Byte, short, Int etc.)

public static void fill(int[] a, int val)


3 Assigns the specified int value to each element of the specified array of ints. Same method could be
used by all other premitive data types ( Byte, short, Int etc.)

public static void sort(Object[] a)


4 Sorts the specified array of objects into ascending order, according to the natural ordering of its
elements. Same method could be used by all other primitive data types ( Byte, short, Int etc.)

Some examples
Example 1: Program to demonstrate array initialization, manipulation

import [Link];
public class ArrayDemo {
public static void main(String[] args) {
//array initialized at compile time through initializer and the same values are displayed
when the program is running.
int array[] = { 12, 34, 56, 78, 89, 32, 56, 22 };
for (int i = 0; i < [Link]; i++) {
[Link]("Value " + array[i] + " is at array[" + i + "]");
}
// array initialized at run time from keyboard input
Scanner input = new Scanner([Link]);
String colors[] = new String[3];
for (int j = 0; j < [Link]; j++) {
[Link]("Enter color: ");
colors[j] = [Link]();
}
// values are displayed when the program is running.
for (int k = 0; k < [Link]; k++) {
[Link]("Color " + colors[k] + " is at colors[" + k +"]");
}
}
}

Note: Every array object knows its own length in Java and maintains this information in a
length field. Thus the expression, for example [Link] accesses colors' length field to
determine the length of the array.
Example 2: Program to find the sum of all array elements

Page 49 of 55
public class ArraySum {
public static void main(String[] args) {
int sum = 0;
int array[] = { 12, 34, 56, 78, 89, 32, 56, 22 };
for (int i = 0; i < [Link]; i++) {
sum += array[i]; // same as writing sum =sum + array[i]
}
[Link]("Sum is :"+ sum);
}
}
Example 3: Program to create a bar chart from the list of array elements

public class ArrayDemo {

public static void main(String[] args) {


int sum = 0;
int array[] = { 10, 0, 5, 7, 1, 0, 12, 22 };
for (int i = 0; i < [Link]; i++) {
[Link](array[i]+"\t|");
for(int j = 0; j < array[i]; j++){
[Link]("=");
}
[Link]("");
}
}
}
Multidimensional arrays
Arrays which have two rows and two columns are called two-dimensional, similarly there are
three-dimensional, four-dimensional in fact arrays may be declared as n-dimensional. But
practically visualizing arrays of more than two-dimension is difficult and rarely used. Java does
not support multidimensional arrays directly, but it does allow the programmer to specify one
dimensional arrays whose elements are also one-dimensional arrays, thus achieving the same
effect. Two dimensional arrays, analogically, is more like a table and to identify a particular table
element, we must specify two indices. The first identifies the row element and second its column.

Like one dimensional arrays, multidimensional arrays can be initialized with array initializers in
declaration. A two-dimensional array with two rows and two columns could be declared and
initialized as follows:
int array[][] = { { 11, 22, 66 }, { 33, 44, 99, 77 }};

Page 50 of 55
A multidimensional array with the same number of columns in every row can be created with an
array creation expression as follows:
int array[][];
array = new int[3][4];
In this case, we use literal 3 and 4 to specify the number of rows and columns respectively. But if
we want a multidimensional array in which each row has a different number of columns, we can
create it as follows:
int array[][];
array = new int[2][];
array[0] = new int[7];

array[1] = new int[5];


Thus the statements create a two-dimensional arrays with two rows where row 0 has seven
columns and row 1 has five columns.
Example 3: Program to demonstrate two-dimensional arrays

import [Link];
public class Array2DDemo {
public static void main(String[] args) {
int array2d[][] = {{11,22},{33},{44,55,66}};
[Link]("Values in the array are");
for(int row = 0;row<[Link];row++){
for(int col=0;col<array2d[row].length;col++){
[Link](array2d[row][col]+" ");
}
[Link]();
}
}
}

Passing arrays to methods


To pass an array argument to a method, specify the name of the array without any brackets. For
example if array price is declared as
double price[]=new double[5];

then the method call


addTax(price);
passes the array price to method addTax. For a method to receive an array reference through a
method call, the method's parameter list must specify an array parameter. For example, the
Page 51 of 55
method header for method addTax might be written as void addTax(double p[]), which indicates
that addTax receives the reference of an double array in parameter p. The method call passes
price's reference, so when the called method uses the array variable p, it refers to that same array
object as price in the calling method.
Example 4: Program to demonstrate passing arrays to methods and modifying the elements

public class ArrayToMethodDemo {


public static void main(String[] args) {
double price[] = { 12.20, 45.25, 78.10, 35.40, 78.50 };
[Link]("Price before tax imposed");
display(price);
addTax(price);
[Link]("Price after 12.75% tax imposed");
display(price);
}
public static void addTax(double p[]) {
for (int i = 0; i < [Link];i++) {
p[i] = p[i] + p[i] * 0.1275;
}
}
public static void display(double p[]) {
for (int i=0; i < [Link]; i++) {
[Link](p[i]);
}
}
}

On passing arguments to methods


Many programming language have two ways to pass arguments in method calls: pass-by-value
(or call-by-value) and pass-by-reference(call-by-reference). When a argument is called by value,
a copy of the argument's value is passed to the called method. The called method works
exclusively with the copy. Any changes made to the copy do not affect the original variable's
value in the caller. On the other hand, when an argument is called by reference, the called
method can access the argument's value in the caller directly and modify the data. However, Java
does not give programmer much of a choice. All arguments are passed by value in Java.
Example 5: Program to demonstrate passing arguments by value

public class PassByValueDemo {


public static void main(String[] args) {
float value = 2.5f;
[Link]("Value before modification " + value);
changeValue(value);
[Link]("Value after modification " + value);
}
public static void changeValue(float f) {
f *= 2;

Page 52 of 55
[Link]("Modified value " + f);
}
}

About String[] args in main


Java allows arguments to be passed from command line to an application by including a
parameter of type String[]in the parameter list of main. When an application is executed, Java
passes the command line arguments that appear after the class name in the java command to the
application's main method as strings in the array args. For example
java MyApp Hello world

passes two command line argument to application MyApp. MyApp's main method receives the
two element array args in which args[0] contains the String “Hello” and args[1] contains the
String “world”.

Quizzes
1. List and table of values can be stored in
(1) variables
(2) table
(3) arrays
(4) program
2. An array is a group of
(1) variables
(2) table
(3) arrays
(4) program
3. The word homogeneous with respect to array refers to
(1) element of same size
(2) element of same type
(3) data type
(4) variables
4. What allows programmer to iterate through the elements in an array
(1) conditional statements
(2) functions
(3) loops
(4) only for loop
5. An array that uses two indices is called
(1) one dimensional array
(2) two dimensional array
(3) three dimensional array
(4) four dimensional array
6. command line arguments are stored in
(1) main
(2) String[] args
(3) Java
(4) stack

Page 53 of 55
7. Array length is denoted by the field
(1) size()
(2) length()
(3) max()
(4) length
8. Can an array index be of type float
(1) yes
(2) no
9. Given the command java abc xyz, the first command line argument is
(1) java
(2) abc
(3) xyz
(4) none of the above
10. String is a primitive data type
(1) true
(2) false

Task: Try yourself

• Write a program to copy elements in one array to another array.


• Write a program to simulate a stack with the help of an array
• Write a program to reverse the element in an array
• Write a program to search an element in an array
• Write a program to prompt the user to enter the desired rows and columns of a matrix and
display its transpose

Page 54 of 55
Part 2: Object oriented programming

Page 55 of 55

Common questions

Powered by AI

Nested if-else structures enable cleaner logic where decisions branch off a preceding condition, allowing for more specific control flows and tighter coupling of related decisions. This also reduces redundant checks and enhances readability and maintainability compared to flat if statements, which repeat conditions and lead to oversights in logical paths .

Java methods are invoked via method calls and must return control upon completion using either a return statement, if a value is required, or naturally by reaching the closing brace. Methods returning values are called expressions, while void methods are called statements, ensuring seamless flow and structured error handling .

Local variables in Java are scoped to the code block in which they are declared. They exist only within this block and are created each time the block is executed anew. Errors such as "cannot find symbol" occur when trying to access these outside their scope. Shadowing, or declaring variables with the same name in overlapping scopes, can cause misinterpretations, often leading to bugs or unintended behaviors .

Static methods in Java perform tasks that are not dependent on instance fields, thus allowing the method to be invoked without creating an instance of the class. This makes them suitable for utility or helper methods, like Math.sqrt(). The main method is static so that the Java Virtual Machine (JVM) can invoke it without instantiating the class, which is crucial for starting the application .

The enhanced for loop, introduced in Java 1.5, simplifies iteration over arrays by eliminating the need for an explicit counter or index variable. It provides cleaner code with fewer opportunities for off-by-one errors and enhances readability. It's particularly suited for iterating through collections or arrays sequentially when indices are not needed .

The primary difference between a "while" loop and a "do...while" loop is execution guarantee. A "while" loop checks its condition at the start, potentially skipping the loop body if the condition is false initially. Conversely, a "do...while" loop guarantees at least one execution, as it checks the condition after running the loop body .

The Arrays.binarySearch() method requires that the array be sorted prior to performing a binary search, as unsorted arrays lead to incorrect results. The method returns the index of the element if found; otherwise, it returns -(insertion point + 1) for the key, indicating where it would be if it were present. This must be handled correctly to avoid logic errors in application flow .

In Java, arrays are fixed-size collections of elements with the same data type. When declared, an array occupies a contiguous block of memory appropriate for its length. "Fixed size" means once an array's length is set during creation, it cannot be changed, requiring new arrays for resizing or dynamic collections like ArrayLists instead .

The "default" case in a switch statement provides a fallback mechanism for handling cases where none of the specified case values match the switch variable. It enhances code robustness by ensuring that there is a defined action or error handling path, reducing the risk of unhandled cases leading to undefined behavior .

In Java, a "switch" statement tests a variable against a list of values, each associated with a "case" label. When the variable equals a case, statements following that case execute until a "break" statement is reached, which terminates the switch. If no "break" appears, control flows into subsequent cases, referred to as "fall-through." This is particularly useful if multiple cases should yield the same result but can lead to logic errors if unintended .

You might also like