Sei sulla pagina 1di 90

Blue Java

Chapter – 01
Introduction to Java & BlueJ
Introduction to Java Programming Language
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented,
and specifically designed to have as few implementation dependencies as possible. It is intended to let
application developers "write once, run anywhere", meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation. Java applications are typically compiled to bytecode
that can run on any Java virtual machine (JVM) regardless of computer architecture. As of 2015, Java is one of
the most popular programming languages in use, particularly for client-server web applications, with a
reported 9 million developers. Java was originally developed by James Gosling at Sun Microsystems (which
has since been acquired by Oracle Corporation) and released in 1995 as a core component of Sun
Microsystems' Java platform. The language derives much of its syntax from C and C++, but it has fewer low-
level facilities than either of them.

Characteristics of Java

Java has many characteristics that have contributed to its popularity:

1. Platform independence - If a program is compiled in Java, it can run on any operating


system in the world without any modification or recompilation at all. The only restriction is
that the operating systems must have a Java Virtual Machine available and installed.
2. Simple and easy to use - Java was designed from ground up to be object oriented and hence
code could be written efficiently and easily.
3. Multi-functional - Java can produce many applications from command-line programs to
applets to Swing based GUI applications.

Features of Java Programming Language


1. Simple:
 Java is Easy to write and more readable and eye catching.
 Java has a concise, cohesive set of features that makes it easy to learn and use.
 Most of the concepts are drew from C++ thus making Java learning simpler.
2. Secure:
 Java program cannot harm other system thus making it secure.
 Java provides a secure means of creating Internet applications.
 Java provides secure way to access web applications.
3. Portable:
 Java programs can execute in any environment for which there is a Java run-time system.(JVM)
 Java programs can be run on any platform (Linux, Window, Mac)
 Java programs can be transferred over world wide web (e.g applets)
4. Object-oriented:
 Java programming is object-oriented programming language.
 Like C++ java provides most of the object oriented features.
 Java is pure OOP. Language. (while C++ is semi object oriented)
5. Robust:
 Java encourages error-free programming by being strictly typed and performing run-time
checks.
6. Multithreaded:
 Java provides integrated support for multithreaded programming.
Page 1 of 90
Blue Java
7. Architecture-neutral:
 Java is not tied to a specific machine or operating system architecture.
 Machine Independent i.e Java is independent of hardware.
8. Interpreted:
 Java supports cross-platform code through the use of Java bytecode.
 Bytecode can be interpreted on any platform by JVM.
9. High performance:
 Bytecodes are highly optimized.
 JVM can executed them much faster.
10. Distributed:
 Java was designed with the distributed environment.
 Java can be transmit, run over internet.
11. Dynamic:
 Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at run time.

Types of JAVA Programs


As we all know, Java is a programming language that’s used to build programs that can work on the local
machine and on the internet as well. Its primary features are that it is object-oriented and a cross platform
language. So there are various categories of programs that can be developed in Java.

STAND-ALONE APPLICATIONS

Console Applications

An application is a program that runs on the computer under the operating system of your computer. Creating
an application in java is similar to doing so in any other computer language. The application can either be GUI
based or console based.

Console based applications are Java programs that run from a command prompt and do not display any GUI
based screen. Such programs have console based outputs.

GUI based applications are the Java programs that run stand-alone and accept user input through a GUI based
screen.

Page 2 of 90
Blue Java

WEB APPLICATIONS

These are the applications which are web-based in nature and requires a web browser for execution. The
Web applications makes use of a Server to store the data, and every time a user requests to execute that
application, the request is passed on to the server for suitable reply.
Applets
Applets are Java programs that are created specially to work on the internet. They run through a Java
embedded browser such as Firefox, Chrome, Internet Explorer, Netscape and many more. An applet can be
created using any Java development kit or tool. To work it out through the internet, it must be contained or
embedded within a web page or HTML file.
Examples of Java Applets include developing games, visual effects and so on.

Servlets
Java is suitable for web based n-tier application development. In a web based application, the client sends a
request to a server. The server processes the request and sends a response back to the client. The server
side Java Application Programming Interfaces (APIs) takes care of the program process and the response of
the client’s request. These server side APIs extend capabilities of standard Java APIs and are known as Java

Page 3 of 90
Blue Java
servlets (also known as server side applets). HTML form processing is one of the simplest uses of servlets.
These servlets can also process databases and perform server side transactions. Servlets make use of web
servers for their execution.
DISTRIBUTED APPLICATIONS
It requires a server to run these applications. A number of servers are used simultaneously for backup to
prevent any data losses.
Database Applications
These are the programs that use the JDBC API for database connectivity. They could either be applets or
applications, though applets may face security problems when dealing with databases.
CLIENT SERVER APPLICATIONS
These application too makes use of web technology for their execution. They follow simple Client-Server
model, where a client makes requests directly to the server.

What is BlueJ?
BlueJ or Blue Java is an integrated development environment (IDE) for the Java programming language,
developed mainly for educational purposes, but also suitable for small-scale software development. It runs
with the help of JDK (Java Development Kit).

BlueJ was developed to support the learning and teaching of object-oriented programming, and its design
differs from other development environments as a result. The main screen graphically shows the class
structure of an application under development (in a UML-like diagram), and objects can be interactively
created and tested. This interaction facility, combined with a clean, simple user interface, allows easy
experimentation with objects under development. Object-oriented concepts (classes, objects, communication
through method calls) are represented visually and in its interaction design in the interface.

Writing Java Programs using BlueJ


1. Create a folder/directory using Microsoft Explorer: Suppose you want to store your Java projects
under the directory C:\CSC211. If this directory (say C:\CSC211) does not exist yet, use the Microsoft
Explorer to create it. First start Explorer and go to C:\ (the root directory of C drive). Then under File,
select New, and Folder. Change the name of the folder from "New Folder" to "CSC211".
2. Invoke BlueJ: Start BlueJ by finding and double clicking on its icon. If you followed the
installation directions for home, it will have an icon on the desktop. In the computer labs, select
Course Applications, CSC, then BlueJ.
3. Create a new project: In BlueJ's top menu bar, select Project and New.... to get the New
Project Dialog. In Look In box, find and select the CSC211 folder that you created in Step 1.
This may require you to go up/down the directory tree a few times. Enter the name of the
project (say "HelloWorld") in File name and click on Create.

Page 4 of 90
Blue Java

The Project Display Area to the middle right should turn white, and an icon that looks like a piece
of paper should appear.

4. Create a new class: Click on the button New Class... to obtain the Create New Class Dialog.
Enter "HelloWorld" in the Class Name textbox, and make sure that the Class radio button is
selected. Then click on the OK button.

Page 5 of 90
Blue Java

A yellow icon with the lable HelloWorld and diagonal lines should appear.

5. Open the editor for the class: Double click on the yellow HelloWorld icon to open the editor
for that class.
6. Modify the code for the class: When you open the HelloWorld Class, you will see some
sample code for the class, including an instance variable x, a constructor HelloWorld, and the
method named sampleMethod. This code may be interesting the first time you see it, but it is
totally worthless. Select all of the code and delete it. Then add your code. For example, the
HelloWorld program would be:

Page 6 of 90
Blue Java

7. Compile the class: Click on the Compile button at the top of the editor. You should get the
message "Class compiled - no syntax erors."

8. Run the application: Go back to the main BlueJ window. If you don't see it on the desktop
screen, look at the bottom of the monitor screen -- there are two BlueJ windows. Then, right
click on the yellow HelloWorld icon, and select void main(args) to run the main method.

Page 7 of 90
Blue Java

You will get the Method Call Dialog. Since you don't have any command line arguments for this
method, simply click on OK.

Note: If your program (or method) takes arguments and you want to enter them, type in values
separated by commas.

You will get the Terminal Window with the message "Hello, world!"

If you like to save the output to a file, select Options and Save to file... Specify the name of the
file in File name, such as "output.txt", and press Save.

Page 8 of 90
Blue Java

9. Get out of BlueJ: Close the Terminal Window, the Editor, and the Main BlueJ Window. The
console window that opened when you invoked BlueJ should close automatically.

Working with BlueJ IDE


Starting the BlueJ IDE application

Click on BlueJ Icon from Start Button  All Program  BjueJ or Double click on BuleJ icon from the desktop
shortcut icon.

After starting the BlueJ You will first see an announcement window:

When it's ready, you will see the main window:

Page 9 of 90
Blue Java

How to create a new project


Click on “New project……” from the project menu.

Page 10 of 90
Blue Java
A new window will pop up

Enter the name of the new project directory (/home/cheung/cs170/TestProj) and click on the Create
button

When BlueJ has successful created an new project, it will show the following window

Page 11 of 90
Blue Java

How to create a Java program file


Suppose we want to create a file that contains the following Java program (given above):
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello Class");
System.out.println(" How is everyone doing so far ?");
}
}

To create a java prohram –

click on the New Class button

Page 12 of 90
Blue Java

A new window will pop up

Type in the name of the "class" (example Hello) and select Class under the class type and then click OK.

Page 13 of 90
Blue Java

Final result is the, you can see the new file Hello in the TestProj area.

How we open a program file for editing


If you want to edit a program file, do the following –

 Right click on the file icon


 Then left click on the Open Editor option from the popup menu

Page 14 of 90
Blue Java

The new window contains the content of the file Hello.java

Deleting text from a file

Highlight the text in BlueJ that you want to delete

Page 15 of 90
Blue Java

Press the backspace key. You can also press the delete key or control-X and the result is –

Page 16 of 90
Blue Java

Inserting text into a file


 Use the scroll bar on the right to find the location in the file where you want to insert
text.
 Left click at the insert location
 Then type in the new text.
 You can insert text from another window into the document in BlueJ by using the copy and paste
facility

Saving the changes

You can choose to save your work explicit by clicking of Class and then Save

Page 17 of 90
Blue Java

Exit BlueJ

 To exit BlueJ, click Project in the BlueJ's main window


 and select Quit

Using BlueJ with an existing Java program


Open a non-BlueJ project
Page 18 of 90
Blue Java
To use BlueJ on an existing Java program, use the Open Non-BlueJ project button in the File menu:

A window will pop up

Page 19 of 90
Blue Java

Navigate to the directory that contains your Java program and Select the directory that contains the Java
program

Finally, click on Open in BlueJ button, you should see BlueJ's main window

Page 20 of 90
Blue Java

Compiling and running Java programs with BlueJ


 You can tell from the shade of a program icon in BlueJ whether the program has been successfully
compiled or not.
o Shaded: this program has not been compiled successfully

Page 21 of 90
Blue Java

o Unshaded: this program has been compiled successfully

Compiling your Java program with BlueJ

 You can compile a Java program in BlueJ in 2 different ways:

1. click on the Compile button from BlueJ's editor window

Page 22 of 90
Blue Java

2. Right click on the program file and then left click of the Compile menu

When the program is compiled successfully, the icon in the main window (associated with the
program) become unshaded:

Page 23 of 90
Blue Java

Running a (successfully compiled) Java program with BlueJ

 Execute a Java program in BlueJ:


1. Right click on the program file in BlueJ's main window, and then Left click on the void
main(String[]args) tab:

2. A window will pop up:

Page 24 of 90
Blue Java

3. Left click on OK to run the program. Result: the output of the program is shown in BlueJ's
"terminal" window:

Writing Java program using simple text editor (Notepad)


Now we will use Notepad to write a simple application, Hello World and execute it

• Create a text file with content as below:

• Save file with same name of the class and .java extension. In this case, file name is HelloWorld.java

Compile the source code

Open the Command console window:

1. Press Start button

2. Click Run…

3. Type cmd and press OK. This will display a screen similar to the one below

Page 25 of 90
Blue Java

Jump to the folder storing the source code file

Use the javac command with input is the source code file name to compile

This output console above shows that no error occurred during compiling code. After compiling code, you also
can see into the source folder for the new file created with name as HelloWorld.class

• Run the compiled code, type the command java with input is name of the class file. You will see result as
below, the greet Hello Java World is printed out:

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

Case Sensitivity - Java is case sensitive which means identifier RCLD and rcld would have different meaning in
Java.

Program File Name - Name of the program file should exactly match the class name.

Page 26 of 90
Blue Java
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).

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 programming languages 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.

Java Keywords
The following list shows the reserved words in Java. These reserved words may not be used as constant or
variable or any other identifier names.

abstract assert boolean break


byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while
Comments in Java
Java supports single line and multi-line comments very similar to C and JAVA. All characters available inside
any comment are ignored by Java compiler.

public class RCLD


{

/* This is my first java program.


* This will print 'RCLD' as the output
* This is an example of multi-line comments.
*/

public static void main(String[] args)


{
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("RCLD");
}
}
Page 27 of 90
Blue Java
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank line, and Java totally ignores
it.

Chapter – 02
Variables, Data Types, Operators & User Input
Variables are nothing but it reserved memory locations to store some values, i. e. when you create a variable
you reserve some space in memory for storing some value.

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


Primitive Data Types are previously defined by the java and named by a key word. There are eight primitive
data types.

Data Type Description Size Value Range


byte Byte data type is used to store integer values. 1 Byte +2 to -27-1
7

short Short data type is used to store integer values. 2 Bytes +215 to -215-1
int Int data type is used to store integer values. 4 Bytes +231 to -231-1
long Long data type is used to store integer values. 8 Bytes +263 to -263-1
float Float data type is used to store floating point values. 4 Bytes 1.40129846432481707E-45
to
3.40282346638528860E+38
double Double data type is used to store floating point values. 8 Bytes 4.94065645841246544E-324
to
1.79769313486231570E+308
boolean boolean data type represents one bit of information. 1 Bit true and false
There are only two possible values : true and false.
char Char data type is used to store 16-bit Unicode 2 Bytes '\u0000' (or 0) to '\uffff' (or
character. 65,535 inclusive)

Reference Data Types


Reference data types are used to access objects. These variables are declared to be of a specific type that
cannot be changed. Class objects, and various type of array variables come under reference data type. Default
value of any reference variable is null.

Variables
A variable refers to the memory location that holds values like – integer, character, float etc. in the computer
memory. A variable is a name of memory location where the data is stored when a program executes. The
Java contains the following types of variables:

 Instance Variables (Non-static fields)


 Class Variables (Static fields)
 Local Variables
 Parameters

Page 28 of 90
Blue Java
Declaring and defining variables
Before using variables you must declare the variables name and there type. The general syntax of declaring
variables is –

<Data Type> <VatiableName> [ = value][, <VariableName> [= value] ...] ;

The Data Type is one of Java's data types (byte, short, int, long, float etc.). The VariableName is the name of
the variable. To declare more than one variable of the specified type, use a comma-separated list.

Here are several examples of variable declarations of various types. Note that some include an initialization.

public class RCLD


{
public static void main(String[] args)
{
int x, y; // declares two ints, x, and y.
int a = 3, b, c = 5; // declares three more ints, initializing
// d and f.
byte d = 22; // initializes d.
double pi = 3.14159; // declares an approximation of pi.
char f = 'x'; // the variable x has the value 'x'.
}
}

Java Literals
A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point),
character, boolean or string values.

Integer Literal

int decimalNumber1 = -25; //represent a -ve int


int decimalNumber2 = -25; // represent a +ve int
int octalNumber1 = 025; // rpredent a +ve octal int
int octalNumber2 = -025; //represent a -ve octal number
int hexNumber1 = 0x25A2; // represent a hexadecimal +ve number
int hexNumber2 = -0x25A2; // represent a hexadecimal -ve number

byte byteInt = 25;


short shortInt = 25;
long longInt = 25L;

So, to represent an octal number, the number is start with a 0 (zero), to represent a hexadecimal number the
number is start with 0x or 0X. To denote the long int, the number is end with L or l.

Floating-Point Literal
float f1 = 25.22f;
float f2 = 2573.279F;
double d1 = 22.25d;
double d2 = 2798.2345D;

So, to denote the number is float use f or F at the end of the number and denotes double number use d or D
at the end of the number.

Character Literal
Character literals have the primitive data type character. A character is quoted in single quote (').
Page 29 of 90
Blue Java
char c1 = 'a';
char c2 = '@';

String Literal
A string literal is a sequence of characters which has to be double-quoted (") and occur on a single line.

String s1 = "Rashtriya Computer Literacy Drive";


String s2 = "a";

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. Java language supports few special escape sequences for String and char
literals as well. They are:

Notation Character represented


\n Newline
\r Carriage return
\f Formfeed
\b Backspace
\s Space
\t tab
\" Double quote
\' Single quote
\\ backslash

Operators in Java
Operators are used to manipulate primitive data types. Java operators can be classified as –

 Unary Operator: Unary operators are taking one argument.


 Binary Operator: Binary Operators are taking two arguments.
 Ternary Operators: Ternary Operators are taking three arguments.

Java operators fall into eight different categories –

 Assignment Operator: = (assignment)


 Arithmetic Operator: + (addition), – (subtraction), * (multiplication), / (division), % (modulus), ++
(increment), - - (decrement)
 Relational Operator: <(less then), <= (less than or equal to), > (greater then), >= (greater than or equal
to), == (equal to), != (not equal to)
 Logical Operator: && (AND), || (OR), ! (NOT)
 Bitwise Operator: & (AND), | (OR), ~ (NOT), ^ (X-OR), << (left shift), >> (right shift)
 Compound Assignment Operator: +=, -+, *=, /=, %=, <<=, >>=
 Conditional Operator: :?

Assignment operator
Assignment operator is represented by "=" symbol in Java which is used to assign a value to a variable lying to
the left side of the assignment operator. Syntax of using the assignment operator is:

<variable> = <expression>;

For example:

int i = -25;

Page 30 of 90
Blue Java
float f = 25.22f;

char c = 'a';

String s = "Rashtriya Computer Literacy Drive;

You can also assign a value to the more than one variable simultaneously. For example –

int x, y, z;
x = y = z = 50;

You can assign a value of a variable by using calculating an expression. For example –

int x, y = 10, z = 20;


x = (y + z) * 25;

Arithmetic operators
Java provides eight Arithmetic operators. They are – addition (+), subtraction (-), multiplication (*), division (/),
modulo or remainder (%), increment (++), decrement (--), and negation (-). An example program is shown
below that demonstrates the different arithmetic operators in java.

public class RCLD


{
public static void main(String[] args)
{
int x, y = 10, z = 5;
x = y + z;
System.out.println("+ operator resulted in " + x);
x = y - z;
System.out.println("- operator resulted in " + x);
x = y * z;
System.out.println("* operator resulted in " + x);
x = y / z;
System.out.println("/ operator resulted in " + x);
x = y % z;
System.out.println("% operator resulted in " + x);
x = y++;
System.out.println("Postfix ++ operator resulted in " + x);
x = ++z;
System.out.println("Prefix ++ operator resulted in " + x);
x = -y;
System.out.println("Unary operator resulted in " + x);
}
}

+ Operator in String
In general, Java does not allow operators to be applied to String objects. The one exception to this rule is the
+ operator, which concatenates two strings, producing a String object as the result. This allows you to chain
together a series of + operations. For example, the following fragment concatenates three strings:
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
Page 31 of 90
Blue Java
String age = "29";
String s = "I am " + age + " years old.";
System.out.println(s);
}
}

This displays the string "I am s9 years old."

One practical use of string concatenation is found when you are creating very long strings. Instead of letting
long strings wrap around within your source code, you can break them into smaller pieces, using the + to
concatenate them. Here is an example:
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
String longStr = "On the Insert tab, the " +
"galleries include items that are " +
"designed to coordinate with the overall " +
"look of your document.";
System.out.println(longStr);
}
}

String Concatenation with other Data Types

You can concatenate strings with other types of data. For example, consider this slightly different version of
the earlier example:

import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int age = 29;
String s = "I Am " + age + " years old.";
System.out.println(s);
}
}

In this case, age is an int rather than another String, but the output produced is the same as before. This is
because the int value in age is automatically converted into its string representation within a String object.
This string is then concatenated as before. The compiler will convert an operand to its string equivalent
whenever the other operand of the + is an instance of String. Be careful when you mix other types of
operations with string concatenation expressions, however. You might get surprising results. Consider the
following:
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int i = 10, j = 20;
String s = "Sum = " + i + j;
System.out.println(s);
}

Page 32 of 90
Blue Java
}

This fragment displays “Sum = 1020” rather than the “Sum = 30” that you probably expected. Here's why.
Operator precedence causes the concatenation of "Sum = " with the string equivalent of 10 to take place
first. This result is then concatenated with the string equivalent of 20 a second time. To complete the integer
addition first, you must use parentheses, like this:
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int i = 10, j = 20;
String s = "Sum = " + (i + j);
System.out.println(s);
}
}

Now contains the string "Sum = 30".

Relational operators
Relational operators are used to compare 2 or more objects. Java provides six relational operators: greater
than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=). The
relational operator is used to compare two or more values and return a Boolean value. For example –

public class RCLD


{
public static void main(String[] args)
{
int x = 10, y = 5;
System.out.println("x > y : " + (x > y));
System.out.println("x < y : " + (x < y));
System.out.println("x >= y : " + (x >= y));
System.out.println("x <= y : " + (x <= y));
System.out.println("x == y : " + (x == y));
System.out.println("x != y : " + (x != y));
}
}

Logical operators
Logical operators return a true or false value based on the state of the Variables. There are three logical
operators. They are AND (&&), OR (||), and NOT(|).

Each argument of a logical operator must be a boolean data type, and the result is always a boolean data
type. For example –

public class RCLD


{
public static void main(String[] args)
{
boolean x = true;
boolean y = false;
System.out.println("x && y : " + (x && y));
System.out.println("x && x : " + (x && x));
System.out.println("x || y : " + (x || y));
System.out.println("x || x: " + (x || x));

Page 33 of 90
Blue Java
System.out.println("!x : " + (!x));
System.out.println("!y : " + (!y));
}
}

Bitwise operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level. Java provides seven
bitwise operators. They are AND (&), OR (|), Exclusive-OR (^), Complement (~), Left-shift (<<), Signed Right-
shift (>>), and Unsigned Right-shift (>>>). For example –

public class RCLD


{
public static void main(String[] args)
{
int x = 10;
int y = 5;
System.out.println("x = " + x + " y = " + y);
System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
}
}

Compound Assignment Operators

The compound operators perform shortcuts in common programming operations. Syntax is –

argument1 operator = argument2;

The above statement is the same as –

argument1 = argument1 operator argument2;

For example –

public class RCLD


{
public static void main(String[] args)
{
int x = 0, y = 5;
x += 3;
System.out.println("x : " + x);
y *= x;
System.out.println("y : " + y);
}
}

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:

Page 34 of 90
Blue Java

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


For example –
public class RCLD
{
public static void main(String[] args)
{
int a = 10, b = 20, c;
c = (a > b) ? a : b;
System.out.println("Value of c is : " + c);

c = (a < b) ? a : b;
System.out.println("Value of c is : " + c);
}
}
Precedence of Operators

The precedence of operators dictates the order of evaluation within an expression. The precedence of the
operators introduced here is summarized in bellow. The highest precedence operators are given first.

Operators Associativity
[] () . left to right
! ~ + - ++ -- & * right to left
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
& | left to right
&& || left to right
= *= /= %= += -= right to left
How to get input from user?
Reading a String from command- prompt
The basic technique of reading a String provided by a user at a command-line is fairly simple, but lengthier
than you'd expect. It involves the use of the System.in object, along with the InputStreamReader and
BufferedReader classes. For example –
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
String name;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter Your Name: ");


name = br.readLine();
System.out.println("Hello " + name);

}
}

Reading a Byte(Small Integer) from command- prompt


import java.io.*;
Page 35 of 90
Blue Java

public class RCLD


{
public static void main(String[] args) throws Exception
{
byte myByte;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter a Byte: ");


temp = br.readLine();
myByte = Byte.parseByte(temp);
System.out.println("You entered Byte is: " + myByte);

}
}

Reading a Short Integer from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
short myShortInt;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Short Int: ");


temp = br.readLine();
myShortInt = Short.parseShort(temp);
System.out.println("You entered Short Int is: " + myShortInt);
}
}

Reading an Integer from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int myInt;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Int: ");


temp = br.readLine();
myInt = Integer.parseInt(temp);
System.out.println("You entered Int is: " + myInt);
}
}

Page 36 of 90
Blue Java
Reading a Long Integer from command- prompt
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
long myLongInt;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Long Int: ");


temp = br.readLine();
myLongInt = Long.parseLong(temp);
System.out.println("You entered Long Int is: " + myLongInt);
}
}

Reading a Octal (Integer Number) from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int myOctal;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Octal Number: ");


temp = br.readLine();
myOctal = Integer.parseInt(temp, 8);
System.out.println("You entered Octal Number is: " +
Integer.toOctalString(myOctal));
System.out.println(" = " + myOctal + " in Decimal");
}
}

Reading a Hexadecimal (Integer Number) from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int myHex;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Hexadecimal Number: ");


temp = br.readLine();
myHex = Integer.parseInt(temp, 16);
System.out.println("You entered Hexadecimal Number is: " +
Integer.toHexString(myHex));

Page 37 of 90
Blue Java
System.out.println(" = " + myHex + " in Int");
}
}

Reading a Binary (Integer Number) from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int myBbinary;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Binary Number: ");


temp = br.readLine();
myBinary = Integer.parseInt(temp, 2);
System.out.println("You entered Binary Number is: " +
Integer.toBinaryString(myBinary));
System.out.println(" = " + myBinary + " in Decimal");
}
}

Reading a Floating-point number from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
float myFloat;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter a Float: ");


temp = br.readLine();
myFloat = Float.parseFloat(temp);
System.out.println("You entered Float is: " + myFloat);
}
}

Reading a Double from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
double myDouble;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Double: ");

Page 38 of 90
Blue Java
temp = br.readLine();
myDouble = Double.parseDouble(temp);
System.out.println("You entered Double is: " + myDouble);
}
}

Reading a Boolean Value (true/false) from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
boolean myBool;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Boolean (true/false): ");


temp = br.readLine();
myBool = Boolean.valueOf(temp);
System.out.println("You entered Char is: " + myBool);
}
}

Reading a Single Character from command- prompt


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
char c;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter an Character: ");


c =(char) br.read();
System.out.println("You entered Char is: " + c);
}
}

Write a program to calculate the sum of two numbers


import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
int num1, num2, sum;

String temp;

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("\n Enter First Number: ");


temp = br.readLine();
num1 = Integer.parseInt(temp);

Page 39 of 90
Blue Java
System.out.print("\n Enter Second Number: ");
temp = br.readLine();
num2 = Integer.parseInt(temp);

sum = num1 + num2;

System.out.print("\n Sum = " + sum);


}
}

Page 40 of 90
Blue Java
Chapter – 03
Decisions, Control and Looping Statements
Statements
A Java Program is made up of statements. Statement is a part of your program that can be executed. Every
statement in your program tells the computer what to do. There are different types of statements –
1. Selection/Conditional Statement: decide the flow of statements on based on a condition. Examples - if
- else and switch statements.
2. Iteration Statements: used to run a particular block of statements repeated for a particular number of
times or a certain condition. Examples – for loop, while loop and do-while loop.
3. Jump Statements: used to jump the program flow control from one point to another point in your
program. Examples - break, continue and return.
4. Label Statements: use for naming a point in your program.
5. Expression Statements: Any valid expression makes an expression statement.
6. Block Statement: A group of statements which are bind together to form a logical group are called
block statements. Block statement begins with a { and ends with a }.
Selection Statements
Java supports two selection statements: if and switch. In addition, the ? operator is an alternative to if in certain
circumstances.
if statements
The general form of the if statement is:
if(Condition)
{
//Statement 1
//Statement 2
//………………
}
else
{
//Statement 1
//Statement 2
//………………..
}
Condition: If the Condition evaluate to true or false. Example of conditions statements –
 (5 > 10)
 (a >= b)
 (i%2==2)
 (a > b && a > c)
 (a <=b || a >= c) etc.
If the Condition statement evaluated to true, then if block is executed. If the condition statement evaluated to
false then else block is executed.
If a single statement exist in the if block or else block then we can omit the opening and closing brackets { and
}.

if(Condition) //Statement if(Condition) if(Condition)


else { Statement
//Statement //Statement 1 else
//Statement 2 {
//………………. //Statement 1
} //Statement 2
Page 41 of 90
Blue Java
else //……………….
Statement }

We can omit the else block. Then the structure of else block is
if(Condition)
{
//Statement 1
//Statement 2
//………………..
//Statement n
}
Example: Write a program to print the bigger of two numbers.
public class RCLD
{
public static void main(String[] args)
{
int x = 5, y = 10;
if(x>y)
System.out.println("\n x is big");
else
System.out.println("\n y is big");
}
}
Nested if statement
if statement can be nested in another if statement; i.e., an if statement is place into the other if statement.
if(Condition 1)
{
if(condition 2)
{
//Statements
}
else
{
//Statements
}
else
{
if(Condition 3)
{
//Statements
}
else
{
//Statements
}
}
Example 1: Write a program to display the biggest of three numbers using nested if.

public class RCLD


{
public static void main(String[] args)
Page 42 of 90
Blue Java
{
int x = 5, y = 10, z = 30;
if(x>y)
{
if(x>z)
System.out.println("\n x is big");
else
System.out.println("\n z is big");
}
else
{
if(y>z)
System.out.println("\n y is big");
else
System.out.println("\n z is big");
}
}
}

Example 2: Write a Program to display the grade using nested if statement.

public class RCLD


{
public static void main(String[] args)
{
int p = 65;
if (p >= 90)
{
System.out.println("\n Grade=A");
}
else
{
if (p < 90 && p >= 80)
{
System.out.println("\n Grade=B");
}
else
{
if (p < 80 && p >= 70)
{
System.out.println("\n Grade=C");
}
else
{
if (p < 70 && p >= 60)
{
System.out.println("\n Grade=D");
}
else
{
if (p < 60 && p >= 50)
{
System.out.println("\n Grade=E");
}

Page 43 of 90
Blue Java
else
{
System.out.println("\n Grade=F");
}
}
}
}
}
}
}

The else-if Statement


The syntax of the elase-if statement is shown bellow-

if(Condition 1)
{
}
else if(condition 2)
{
//Statements
}
else if(Condition 3)
{
//Statements
}
else if(Condition 3)
{
//Statements
}
else
{
//Statements
}

Example 2: Write a Program to display the grade using nested if statement.

public class RCLD


{
public static void main(String[] args)
{
int p = 65;
if (p >= 90)
System.out.println("\n Grade=A");
else if (p < 90 && p >= 80)
System.out.println("\n Grade=B");
else if (p < 80 && p >= 70)
System.out.println("\n Grade=C");
else if (p < 70 && p >= 60)
System.out.println("\n Grade=D");
else if (p < 60 && p >= 50)
System.out.println("\n Grade=E");
else

Page 44 of 90
Blue Java
System.out.println("\n Grade=F");
}
}

switch case Statement


The switch case statements are a substitute for long if statements that compare a variable to several integer or
character. The basic format for using switch case is shown below. The value of the variable given into switch is
compared to the value following each of the cases, and when one value matches the value of the variable, the
computer continues executing the program from that point.
switch (expression)
{
case value 1:
//statement sequence
break;
case value 2:
//statement sequence
break;
case value 3:
//statement sequence
break;
.
.
.
default
//statement sequence
}
The expression must evaluate to of type character or integer values, but floating-point expressions, for example,
are not allowed.
The value of expression is tested against the values, one after another, of the constants specified in the case
statements. When a match is found, the statement sequence associated with that case is executed until the
break statement or the end of the switch statement is reached.
The default statement is executed if no matches are found. The default is optional, and if it is not present, no
action takes place if all matches fail.
The break statement is one of jump statements. You can use it in loops as well as in the switch statement. When
break is encountered in a switch, program execution "jumps" to the line of code following the switch statement.
Example:
public class RCLD
{
public static void main(String[] args)
{
int d = 7;
switch (d)
{
case 0:
System.out.println("\n Zero");
break;
case 1:
System.out.println("\n One");
break;
case 2:
System.out.println("\n Two");
break;
Page 45 of 90
Blue Java
case 3:
System.out.println("\n Three");
break;
case 4:
System.out.println("\n Four ");
break;
case 5:
System.out.println("\n Five");
break;
case 6:
System.out.println("\n Six");
break;
case 7:
System.out.println("\n Seven");
break;
case 8:
System.out.println("\n Eight");
break;
case 9:
System.out.println("\n Nine");
break;
default:
System.out.println("\n Invalid Digit");
}
}
}
Iteration Statement
In Java, iteration statements or loops allow a set of instructions or some portion of the program to be executed
repeatedly either a specific number of times or until a certain condition is reached. This repetition is done
through loop control statement.
while loop
The general form of the while loop is:

while(Condition)
{
//Statement;
}

Statement: Statement is either an empty statement, or a single statement, or a block of statements.


Condition: Condition may be any expression which evaluates to true or false.
The loop iterates while the condition is true. When the condition becomes false, program control passes to the
line of code immediately following the loop.
Here the loop condition is tasted first, if the condition is true then the body of the loop executed. After execute
the body of the loop, the condition is check again and if the condition is true then the body of the loop is
executed and repeated the same process until the loop condition evaluated to false.
Example 1: Write a program to print the number from 1 to 100 using while loop.
public class RCLD
{
public static void main(String[] args)
{
int i = 1;
while (i <= 100)
Page 46 of 90
Blue Java
{
i++;
System.out.print(i + "\t");
}
}
}
do-while loop
while loop test the loop condition at the top of the loop, the do-while loop checks its condition at the bottom
of the loop. This means that a do-while loop always executes at least once. The general form of the do-while
loop is

do {
statement;
} while(condition);

The do-while loop iterates until condition becomes false.

Here the body of the loop is executed first and then check the loop condition, if the condition become true then
the body of the loop is executed again. After finishing the body again checks the loop condition. This process is
repeated until the loop condition is evaluated to false.

Example 1: Write a program to print the number 1 to 100 using do-wile loop.
public class RCLD
{
public static void main(String[] args)
{
int i = 1;
do
{
i++;
System.out.print(i + "\t");
} while (i <= 100);
}
}
for loop
The for loop is used to repeat the execution of set of statements for a fixed number of times. The for loop is
also an entry-controlled loop. Syntax of a for loop is:

for(Initialization; Condition; Increment) statement(s)

Initialization: It is an assignment statement that is used to set the loop control variable.
Condition: It is a relational expression that determines when the loop exits.
Increment: It defines how the loop control variable changes each time the loop is repeated.

Note: The initialization, condition and increment statements are separate by semicolons.

The for loop continues to execute as long as the condition is true. Once the condition becomes false, program
execution resumes on the statement following the for.

Example 1: Write a program to print the numbers 1 through 100 on the screen.
public class RCLD
Page 47 of 90
Blue Java
{
public static void main(String[] args)
{
for(int i = 1; i <= 100; i++)
{
System.out.print(i + "\t");
}
}
}

Example 2: Write a program to print the numbers 100 through 1 on the screen.
public class RCLD
{
public static void main(String[] args)
{
for(int i = 100; i > 0; i--)
{
System.out.print(i + "\t");
}
}
}
Example 3: Write a program to print the numbers 1 through 100 on the screen.
public class RCLD
{
public static void main(String[] args)
{
int i = 1;
for(; i <=100; i++)
{
System.out.print(i + "\t");
}
}
}
Note: Here the Initialization is done before the for loop start.

Example 4: Write a program to print the numbers 1 through 100 on the screen.
public class RCLD
{
public static void main(String[] args)
{
for(int i = 1; i <=100; )
{
System.out.print(i + "\t");
i++;
}
}
}
Note: Here incremental statement is execute inside of the for loop;
Example 5: Write a program to print the numbers 1 through 100 on the screen.
public class RCLD
{
public static void main(String[] args)
{
Page 48 of 90
Blue Java
for(int i = 1; ; i++)
{
System.out.print(i + "\t");
if(i ==100)
break;
}
}
}
Note: Here the terminate condition is check inside the for loop.

Example 5: Write a program to print the numbers 1 through 100 on the screen.
public class RCLD
{
public static void main(String[] args)
{
int i = 1;
for( ; ; )
{
System.out.print(i + "\t");

if(i ==100)
break;

i++;
}
}
}

Note: Here initialization is done before the loop start and increment and terminate condition is execute inside
the for loop.

Note: We can any increment or decrement expression a for loop.

Example: Write a program to print numbers 5, 10, 15, 20, 25, ………., 100.
public class RCLD
{
public static void main(String[] args)
{
for(int i = 5; i <= 100; i = i + 5)
{
System.out.print(i + "\t");
}
}
}
break Statement
The break statement has two uses. We can use it to terminate a case in the switch statement and we can also
use it to force immediate termination of a loop, bypassing the normal loop conditional test.
When the break statement is encountered inside a loop, the loop is immediately terminated, and program
control resumes at the next statement following the loop.
continue Statement
The continue statement forces the next iteration of the loop to take place, skipping any code in between. For
the for loop, continue causes the increment and then the conditional test portions of the loop to execute. For
Page 49 of 90
Blue Java
the while and do-while loops, program control passes to the conditional tests. For example, the following
program counts the number of spaces contained in the string entered by the user:
Example 1: Write a program to print the even numbers from 1 to 100.
public class RCLD
{
public static void main(String[] args)
{
for(int i = 1; i <= 100; i++)
{
if (i % 2 == 1)
continue;

System.out.print(i + "\t");
}
}
}

Page 50 of 90
Blue Java
Chapter – 04
Array
Introduction
An array is a group of variables of the same data type and referred to by a common name. An array is
contiguous block of memory locations referred by a common name. For example, to store the marks of 5000
students, you can declare an array, marks, of size 5000 and can store the marks of as many students.

Why array is needed?

When you need to store similar type of values for a large number of data items, you can use array.

An array consists of a name and the number of elements of the array. You can refer to a specific array
element by the array name and the element number, which is known as the index number. Array index
element number always starts with 0(zero).
Advantages of Java Array

 An array can hold primitive types data.


 An array has its size that is known as array length.
 An array knows only its type that it contains. Array type is checked at the compile-time.
Disadvantages of Java Array

 An array has fixed size.


 An array holds only one type of data (including primitive types).

There are various types of arrays in java –


1. Single-dimensional arrays
2. Multi-dimensional arrays
Single-Dimension Arrays
The general form for declaring a single-dimension array is-
Data_Type[] var_name = new Data_Type[Array_Length];

Example: To declare a 100 element array type int


int[] N = new int[100];
An array element is accessed by index number. This is done by placing the index of the element within square
brackets after the name of the array. Example –
N[5] = 275;
N[6] = 300;
N[7] = N[5] + N[6];

In Java, all arrays have 0 as the index of the first element and (size-1) as the index of the last element.
One Dimensional Array Initialization
We can initialize an array when we declare the array.

Example:

int m[6]={256, 67, -56, 0, -22, 33};

int n[]={11, 22, 33, 44, 55, 66, 77, 88, 99};

Note: If we declare an array as int n[]={11, 22, 33, 44, 55, 66, 77, 88, 99} then the automatically sate size of the
array. Here the size is 9.
Page 51 of 90
Blue Java
Two Dimensional Array
Two dimensional arrays are used when it is required to process the matrices, tabular data etc.

Syntax:

Data_Type[ ][ ] var_name = new Data_Type[no of rows][no of columns];

Example:
int[ ][ ] n = new int[4][5];
float[ ] [ ] m=new float[5][3];

Two Dimensional Array Initialization


We can initialize two dimensional arrays.

Example:
int[][] x1={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}};

Two dimensional array element is accessed by two index number. Example –


int[ ] [ ] N = new int[3][4];

N[1][0] = 275;
N[0][1] = 300;
N[1][1] = N[1][0] + N[0][1];

Program to insert 10 integers in a single dimensional array and calculate the sum.
import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int num[] = new int[10];
int i, sum = 0;
for (i = 0; i < num.length; i++)
{
System.out.print("\n Enter Array Element " + (i + 1) + ": ");
num[i] = Integer.parseInt(br.readLine());
}
System.out.println("\n Array Elements are: \n");
for (i = 0; i < num.length; i++)
{
System.out.print(" " + num[i] + "\t");
sum = sum + num[i];
}
System.out.println("\n Sum of the Array = " + sum);
}
}

Program to insert 3 X 4 integers in a two dimensional array and calculate the sum.

import java.io.*;

public class RCLD


{
public static void main(String[] args) throws Exception
{

Page 52 of 90
Blue Java
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int[][] num = new int[3][4];
int i, j, sum = 0;
for (i = 0; i < num.length; i++)
{
for (j = 0; j < num[i].length; j++)
{
System.out.print("\n Enter Array Element(" + (i + 1) + ",
" + (j + 1) + "): ");
num[i][j] = Integer.parseInt(br.readLine());
}
}
System.out.println("\n Array Elements are: \n");
for (i = 0; i < num.length; i++)
{
for (j = 0; j < num[i].length; j++)
{
System.out.print("\t" + num[i][j]);
sum = sum + num[i][j];
}
System.out.println();
}
System.out.println("\n Sum of the Array = " + sum);
}
}
Program to search an element in an array
import java.io.*;

class RCLD
{
public static void main(String arg[]) throws Exception
{
int[] a;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int i, n=0, q=0;

System.out.print("Enter Array Length ");


n=Integer.parseInt(br.readLine());
a = new int[n];
System.out.println("Enter array elements ");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine());
}

System.out.println("Enter element to be searched ");

q=Integer.parseInt(br.readLine());

for(i=0;i<n;i++)
{
if(a[i]==q)
System.out.println("Element found at "+(i+1)+"
position");
}
}
}
Print Reverse of an Array
import java.io.*;

class RCLD
Page 53 of 90
Blue Java
{
public static void main(String S[])throws Exception
{
int a
int n, i;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\nEnter Length of the array: ");
n = Integer.parseInt(br.readLine());
a = new int[n];
System.out.println("\nEnter " + n + " Array Elements \n");
for(i=0; i<n; i++)
{
a[i]= Integer.parseInt(br.readLine());
}
System.out.println("\nOriginal Array\n");
for(i=0; i<n; i++)
{
System.out.print(a[i] + "\t");
}
System.out.println("\nReverse Order \n");
for(i=n-1; i>=0; i--)
{
System.out.print(a[i] + "\t");
}
}
}
Transpose of a Matrix
import java.io.*;

class RCLD
{
public static void main(String S[])throws Exception
{
int i, j, row, col;
int a[][];
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));

System.out.print("\nEnter Number of Rows and Columns of the Matrix:


");
row = Integer.parseInt(in.readLine());

col = row;

a = new int[row][col];

System.out.println("\nEnter " + row + " X " + col + " Matrix


Elements\n");

for(i = 0; i < row; i++)


{
for(j = 0; j < col; j++)
{
a[i][j]=Integer.parseInt(in.readLine());
}
}

System.out.println("\nOriginal Array\n");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{

Page 54 of 90
Blue Java
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println("The transpose is");
for(i = 0; i < row; i++)
{
for(j = 0; j < col; j++)
{
System.out.print(a[j][i] + " ");
}
System.out.println();
}
}
}
Matrix Multiplication
import java.io.*;

class RCLD
{
public static void main(String a[])throws Exception
{
int i, j, k, row, col;
int b[][];
int c[][];
int d[][];

BufferedReader in=new BufferedReader(new


InputStreamReader(System.in));

System.out.print("\nEnter Number of Rows and Columns of the Matrix:


");
row = Integer.parseInt(in.readLine());
col = row;

b = new int[row][col];
c = new int[row][col];
d = new int[row][col];

System.out.println("\nEnter " + row + " X " + col + " Matrix Elements


for the First Matrix\n");
for(i = 0; i < row; i++)
{
for(j = 0; j < col;j++)
{
b[i][j]=Integer.parseInt(in.readLine());
}
}

System.out.println("\nEnter " + row + " X " + col + " Matrix Elements


for the Second Matrix\n");
for(i = 0; i < row; i++)
{
for(j = 0; j < col;j++)
{
c[i][j]=Integer.parseInt(in.readLine());
}
}

for(i = 0; i < row; i++)


{
for(j = 0; j < row; j++)

Page 55 of 90
Blue Java
{
for(k = 0; k < col; k++)
{
d[i][j]+=(b[i][k]*c[k][j]);
}
}
}

System.out.println("\nMatrix A = \n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.print(b[i][j] + " ");
}
System.out.println();
}
System.out.println("\nMatrix B =\n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
System.out.println("\nA X B = \n");
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
System.out.print(d[i][j] + " ");
}
System.out.println();
}
}
}

Page 56 of 90
Blue Java
Chapter – 05
Class, Object, Function & Inheritance

Class
A class is a conceptual idea that can be represent with data structure and function. A class is a mechanism for
creating user-defined data types, similar to the structure data type. A structure is composed of a set of data
members, but a class is composed of a set of data members which can used to hold some data and a set of
function members that operate on the data members.

The general syntax for creating class is –

class <Class Name>

//class Body

};

Example of a class
class address
{
String name, addr;
long phone;
public void set_address(String NAME, String ADDRESS, long PHONE)
{
name = NAME;
addr = ADDRESS;
phone = PHONE;
}
void display_address()
{
System.out.println("Name:\t" + name);
System.out.println("Address:\t" + addr);
System.out.println("Phone No.:\t" + phone);
}
}

A class may content two types of member –

1. Data members (example – String name, String addr, long phone)


2. Function Member (example – set_address(…), display_address())
Object
Object is an instance of a class. An instance of an object is an actual thing that can be manipulated. The
properties of an object are –

 Identity: the property of an object that distinguishes it from other objects


 State: describes the data stored in the object
 Behavior: describes the methods in the object's interface by which the object can be used
Syntax for creating object

<Class Name> <Object Variable Name>;

Example
class address
{
Page 57 of 90
Blue Java
String name, addr;
long phone;
public void set_address(String NAME, String ADDRESS, long PHONE)
{
name = NAME;
addr = ADDRESS;
phone = PHONE;
}
void display_address()
{
System.out.println("Name:\t" + name);
System.out.println("Address:\t" + addr);
System.out.println("Phone No.:\t" + phone);
}
}

class RCLD
{
public static void main(String args[])
{
address add1 = new address();
address add2 = new address();
}
}

Here add1 and add2 are two objects of class address.


Access class members using objects
The syntax for accessing class members through class objects –
<Object Name>.<Member Name>
Examples –
add1.name = "Uttam Kumar Majhi";
add1.addr = "Durgapur";
add1.phone = 1234567890;
add1.display_address();

add2.set_address("Sujoy", "Burdwan", 4567891203L);


add1.display_address();

The complete code of the above example is –


1. First add a class “address” in BlueJ and edit the code as shown bellow –
class address
{
String name, addr;
long phone;
public void set_address(String NAME, String ADDRESS, long PHONE)
{
name = NAME;
addr = ADDRESS;
phone = PHONE;
}
void display_address()
{
System.out.println("Name:\t" + name);
System.out.println("Address:\t" + addr);
System.out.println("Phone No.:\t" + phone);
}
}

Page 58 of 90
Blue Java
2. After editing the “address” Class, compile the class.

3. Next, add an another class “RCLD” and edit the class as shown bellow -

class RCLD
{
public static void main(String args[])
{
address add1 = new address();
address add2 = new address();

add1.name = "Uttam Kumar Majhi";


add1.addr = "Durgapur";
add1.phone = 1234567890;
add1.display_address();

add2.set_address("Sujoy", "Burdwan", 4567891203L);


add2.display_address();
}
}

4. Now compile and run the RCLD class.

Functions/Method
A function is a self-contained block of code with a specific purpose. A function has a name that both
identifies it and is used to call it for execution in a program. The name of a function is not necessarily
unique in Java.
We can pass information to a function. These arguments need to correspond with parameters that
appear in the definition of the function. A function can returns either a single value to the point in the
program where it was called, or nothing, depending on how the function is defined.
Need of Functions
The major advantage of functions is that it can be executed as many times as necessary from different
points in a program.
The function is used to break up a program into easily manageable block for development and testing.
Functions enable us to segment a program so that we can write the code piece by piece, and test each
piece independently before bringing it together with the other pieces.
It also allows the work to be divided among members of a programming team, with each team member
taking responsibility for a tightly specified piece of the program, with a well-defined functional
interface to the rest of the code.
Types of Functions
There are two types of functions –
1. Library functions.
2. User-defined functions.
Library functions
Library functions are nothing but commonly required functions grouped together and stored in what is
called a Library. This library of functions is present on the disk and is written for us by people who write
compilers for us. Almost always a compiler comes with a library of standard functions. The procedure of
calling both types of functions is exactly same.

Mathematical Functions
Function Name Description
IEEEremainder(double x, Returns the remainder of x divided by y as defined by IEEE 754
double y)
Page 59 of 90
Blue Java
abs(int a) Returns the absolute integer value of a
abs(long a) Returns the absolute long value of a
abs(float a) Returns the absolute float value of a
abs(double a) Returns the absolute double value of a
acos(double a) Returns the arc cosine of a, in the range of 0.0 through pi
asin(double a) Returns the arc sine of a, in the range of -pi/2 through pi/2
atan(double a) Returns the arc tangent of a, in the range of -pi/2 through pi/2
atan2(double a, double b) Converts rectangular coordinates (a, b) to polar (r, theta)
ceil(double a) Returns the "ceiling," or smallest whole number greater than or
equal to a
cos(double) Returns the trigonometric cosine of an angle
exp(double a) Returns the exponential number e(2.718...) raised to the power
of a
floor(double a) Returns the "floor," or largest whole number less than or equal
to a
log(double a) Returns the natural logarithm (base e) of a
max(int a, int b) Takes two int values, a and b, and returns the greater of the two
max(long a, long b) Takes two long values, a and b, and returns the greater of the
two
max(float a, float b) Takes two float values, a and b, and returns the greater of the
two
max(double a, double b) Takes two double values, a and b, and returns the greater of the
two
min(int a, int b) Takes two integer values, a and b, and returns the smaller of the
two
min(long a, long b) Takes two long values, a and b, and returns the smaller of the
two
min(float a, float b) Takes two float values, a and b, and returns the smaller of the
two
min(double a, double b) Takes two double values, a and b, and returns the smaller of the
two
PI Return the value of PI.
pow(double a, double b) Returns the number a raised to the power of b
random() Generates a random number between 0.0 and 1.0
rint(double) Returns the closest integer to the argument, but as a floating-
point number
round(float) Rounds off a float value by first adding 0.5 to it and then
returning the largest integer that is less than or equal to this
new value
round(double) Rounds off a double value by first adding 0.5 to it and then
returning the largest integer that is less than or equal to this
new value
sin(double) Returns the trigonometric sine of an angle
sqrt(double) Returns the square root of a
tan(double) Returns the trigonometric tangent of an angle
toDegrees(double) Translates radians to degrees
toRadians(double) Translates degrees to radians
Page 60 of 90
Blue Java

Example –
import java.math.*;

class RCLD
{
public static void main(String args[])
{
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;

System.out.println("i is " + i);


System.out.println("j is " + j);
System.out.println("x is " + x);
System.out.println("y is " + y);

// The absolute value of a number is equal to


// the number if the number is positive or
// zero and equal to the negative of the number
// if the number is negative.

System.out.println("|" + i + "| is " + Math.abs(i));


System.out.println("|" + j + "| is " + Math.abs(j));
System.out.println("|" + x + "| is " + Math.abs(x));
System.out.println("|" + y + "| is " + Math.abs(y));

// Truncating and Rounding functions

// You can round off a floating point number


// to the nearest integer with round()
System.out.println(x + " is approximately " + Math.round(x));
System.out.println(y + " is approximately " + Math.round(y));

// The "ceiling" of a number is the


// smallest integer greater than or equal to
// the number. Every integer is its own
// ceiling.
System.out.println("The ceiling of " + i + " is " + Math.ceil(i));
System.out.println("The ceiling of " + j + " is " + Math.ceil(j));
System.out.println("The ceiling of " + x + " is " + Math.ceil(x));
System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

// The "floor" of a number is the largest


// integer less than or equal to the number.
// Every integer is its own floor.
System.out.println("The floor of " + i + " is " + Math.floor(i));
System.out.println("The floor of " + j + " is " + Math.floor(j));
System.out.println("The floor of " + x + " is " + Math.floor(x));
System.out.println("The floor of " + y + " is " + Math.floor(y));

// Comparison operators

// min() returns the smaller of the two arguments you pass it


System.out.println("min(" + i + "," + j + ") is " + Math.min(i, j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x, y));
System.out.println("min(" + i + "," + x + ") is " + Math.min(i, x));
System.out.println("min(" + y + "," + j + ") is " + Math.min(y, j));

// There's a corresponding max() method


// that returns the larger of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i, j));
Page 61 of 90
Blue Java
System.out.println("max(" + x + "," + y + ") is " + Math.max(x, y));
System.out.println("max(" + i + "," + x + ") is " + Math.max(i, x));
System.out.println("max(" + y + "," + j + ") is " + Math.max(y, j));

// The Math library defines a couple


// of useful constants:
System.out.println("Pi is " + Math.PI);
System.out.println("e is " + Math.E);
// Trigonometric methods
// All arguments are given in radians

// Convert a 45 degree angle to radians


double angle = 45.0 * 2.0 * Math.PI / 360.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));

// Inverse Trigonometric methods


// All values are returned as radians

double value = 0.707;

System.out.println("acos(" + value + ") is " + Math.acos(value));


System.out.println("asin(" + value + ") is " + Math.asin(value));
System.out.println("atan(" + value + ") is " + Math.atan(value));

// Exponential and Logarithmic Methods

// exp(a) returns e (2.71828...) raised


// to the power of a.
System.out.println("exp(1.0) is " + Math.exp(1.0));
System.out.println("exp(10.0) is " + Math.exp(10.0));
System.out.println("exp(0.0) is " + Math.exp(0.0));

// log(a) returns the natural


// logarithm (base e) of a.
System.out.println("log(1.0) is " + Math.log(1.0));
System.out.println("log(10.0) is " + Math.log(10.0));
System.out.println("log(Math.E) is " + Math.log(Math.E));

// pow(x, y) returns the x raised


// to the yth power.
System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0, 2.0));
System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0, 3.5));
System.out.println("pow(8, -1) is " + Math.pow(8, -1));

// sqrt(x) returns the square root of x.


for (i = 0; i < 10; i++)
{
System.out.println(
"The square root of " + i + " is " + Math.sqrt(i));
}

// Finally there's one Random method


// that returns a pseudo-random number
// between 0.0 and 1.0;

System.out.println("Here's one random number: " + Math.random());


System.out.println("Here's another random number: " + Math.random());
}
}

Character Functions
Functions Description

Page 62 of 90
Blue Java
isLetter() Determines whether the specified char value is a letter.

isDigit() Determines whether the specified char value is a digit.

isWhitespace() Determines whether the specified char value is white space.

isUpperCase() Determines whether the specified char value is uppercase.

isLowerCase() Determines whether the specified char value is lowercase.

toUpperCase() Returns the uppercase form of the specified char value.

toLowerCase() Returns the lowercase form of the specified char value.

toString() Returns a String object representing the specified character valuethat is, a one-character string.

Example –

import java.math.*;

class RCLD
{
public static void main(String args[])
{
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));

System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));

System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));

System.out.println(Character.isUpperCase('c'));
System.out.println(Character.isUpperCase('C'));
System.out.println(Character.isUpperCase('\n'));
System.out.println(Character.isUpperCase('\t'));

System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
System.out.println(Character.isLowerCase('\n'));
System.out.println(Character.isLowerCase('\t'));

System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C'));

System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));

System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}

String Functions
Function
Description
char charAt(int index) Returns the character at the specified index.
Compares two strings lexicographically.
int compareTo(String
anotherString)
Compares two strings lexicographically, ignoring case differences.
int
compareToIgnoreCase(String
str)
Page 63 of 90
Blue Java
String concat(String str) Concatenates the specified string to the end of this string.
Tests if this string ends with the specified suffix.
boolean endsWith(String
suffix)
Compares this String to another String, ignoring case considerations.
boolean
equalsIgnoreCase(String
anotherString)
Returns the index within this string of the first occurrence of the specified
int indexOf(int ch) character.
Returns the index within this string of the first occurrence of the specified
int indexOf(int ch, int character, starting the search at the specified index.
fromIndex)
Returns the index within this string of the first occurrence of the specified
int indexOf(String str) substring.
Returns the index within this string of the first occurrence of the specified
int indexOf(String str, int substring, starting at the specified index.
fromIndex)
Returns the index within this string of the last occurrence of the specified
int lastIndexOf(int ch) character.
Returns the index within this string of the last occurrence of the specified
int lastIndexOf(int ch, int character, searching backward starting at the specified index.
fromIndex)
Returns the index within this string of the rightmost occurrence of the specified
int lastIndexOf(String str) substring.
Returns the index within this string of the last occurrence of the specified
int lastIndexOf(String str, int substring, searching backward starting at the specified index.
fromIndex)
int length() Returns the length of this string.
Returns a new string resulting from replacing all occurrences of oldChar in this
String replace(char oldChar, string with newChar.
char newChar)
Replaces each substring of this string that matches the given regular expression
String replaceAll(String regex, with the given replacement.
String replacement
Tests if this string starts with the specified prefix.
boolean startsWith(String
prefix)
Tests if this string starts with the specified prefix beginning a specified index.
boolean startsWith(String
prefix, int toffset)
Returns a new string that is a substring of this string.
String substring(int
beginIndex)
Returns a new string that is a substring of this string.
String substring(int
beginIndex, int endIndex)
char[] toCharArray() Converts this string to a new character array.
Converts all of the characters in this String to lower case using the rules of the
String toLowerCase() default locale.
Converts all of the characters in this String to upper case using the rules of the
String toUpperCase() default locale.
String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
Returns the string representation of the passed data type argument.
static String valueOf(primitive
data type x)

For example –
import java.math.*;

class RCLD
{
public static void main(String args[])
{
String s = "Strings are immutable";
System.out.println(s.charAt(8));

Page 64 of 90
Blue Java

String str1 = "Strings are immutable";


String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";

System.out.println(str1.compareTo(str2));
System.out.println(str2.compareTo(str3));
System.out.println(str3.compareTo(str1));
System.out.println(str1.compareToIgnoreCase(str2));
System.out.println(str2.compareToIgnoreCase(str3));
System.out.println(str3.compareToIgnoreCase(str1));

s = s.concat(" all the time");


System.out.println(s);

String Str1 = new String("This is really not immutable!!");


boolean retVal;

retVal = Str1.endsWith("immutable!!");
System.out.println("Returned Value " + retVal);

retVal = Str1.endsWith("immu");
System.out.println("Returned Value " + retVal);

String Str2 = new String("Welcome to Tutorialspoint.com");


String SubStr1 = new String("Tutorials");
String SubStr2 = new String("Sutorials");

System.out.print("Found Index :");


System.out.println(Str2.indexOf('o'));
System.out.print("Found Index :");
System.out.println(Str2.indexOf('o', 5));
System.out.print("Found Index :");
System.out.println(Str2.indexOf(SubStr1));
System.out.print("Found Index :");
System.out.println(Str2.indexOf(SubStr1, 15));
System.out.print("Found Index :");
System.out.println(Str2.indexOf(SubStr2));
}
}
User Define Functions

Structure of a Function
As we have seen when writing the function main(), a function consists of a function header that
identifies the function, followed by the body of the function between curly braces containing the
executable code for the function.

The general structure of a function is:

<Access Specifier> <Function Modifier> <Return Type> <Function Name>(<Parameter List>)


{
//Function body
}

Example:

public static void main(String args[] )


{
Page 65 of 90
Blue Java
// Body of the function
}

Part of a Function
The function can be divides into three parts –
1. Function header
2. Function body
3. Return statement

General Form of a Function Header


The general form of a function header can be written as follows—

[<Access Specifier>] [<Function Modifier>] <Return Type> <Function Name>([<Parameter List>])

Access Specifier: The Access Specifier can be public or private or protected. It is optional.
Function Modifier: The Function Modifier can be static, final, native, abstract, or synchronized etc. it is
optional.
Return Type: The return type can be any legal data type. If the function does not return a value, the
return type is specified by the keyword void.
Function Name: Function name is any valid identifier name.
Parameter List: Parameter List is used to pass information to a function. The keyword void is also
used to indicate the absence of parameters. An empty parameter list also indicates that a function
takes no arguments, so you could omit the keyword void between the parentheses.

Function Body
The desired computation in a function is performed by the statements in the function body following
the function header. The function body start with { and end with }. All the valid statements are place
between { and }.

The return Statement


The return statement returns the value of result to the point where the function was called. The
general form of the return statement is:
return expression;
where expression must evaluate to a value of the type specified in the function header for the return
value.
If the type of return value has been specified as void, there must be no expression appearing in the
return statement.

Function Prototypes
A prototype of a function provides the basic information that the compiler needs to check that we are
using a function correctly. It specifies the parameters to be passed to the function, the function name,
and the type of the return value—basically, it contains the same information as appears in the function
header, with the addition of a semicolon.
Clearly, the number of parameters and their types must be the same in the function prototype as they
are in the function header in the definition of the function.
The prototypes for the functions that you call from within another function must appear before the
statements doing the calling and are usually placed at the beginning of the program source file.
Page 66 of 90
Blue Java

Example: Write a Function to calculate x to the power n.

import java.io.*;

class RCLD
{
public int power(int p, int q)
{
int i, result = 1;
for (i = 1; i <= q; i++)
{
result = result * p;
}
return result;
}
public static void main(String args[])
{
RCLD ob = new RCLD();
int r;
r = ob.power(2, 3);
System.out.println("\n 2 ^ 3 = " + r);
System.out.println("\n 8 ^ 2 = " + ob.power(8, 2));
}
}

Different structure of a function

1. Function that have not any parameter and return type void.
import java.io.*;

class RCLD
{
public void power()
{
int p = 4, q = 3;
int i, result = 1;
for (i = 1; i <= q; i++)
{
result = result * p;
}
System.out.println("\n 4 ^ 3 = " + result);
}
public static void main(String args[])
{
RCLD ob = new RCLD();
ob.power();
}
}

2. Function that have parameter and return type void.


import java.io.*;

class RCLD
{
public void power(int p, int q)
{
int i, result = 1;
for (i = 1; i <= q; i++)
{
result = result * p;
}
Page 67 of 90
Blue Java
System.out.println("\n " + p + " ^ " + q + " = " + result);
}
public static void main(String args[])
{
RCLD ob = new RCLD();
ob.power(3, 4);
ob.power(3, 2);
}
}

3. Function that have not parameter and have a specific return type.
import java.io.*;

class RCLD
{
public int power()
{
int p = 5, q = 2;
int i, result = 1;
for (i = 1; i <= q; i++)
{
result = result * p;
}
return result;
}
public static void main(String args[])
{
RCLD ob = new RCLD();
int r;
r = ob.power();
System.out.println("5 ^ 2 = " + r);
System.out.println("5 ^ 2 = " + ob.power());
}
}

4. Function that have parameter and have a return value.


import java.io.*;

class RCLD
{
public int power(int p, int q)
{
int i, result = 1;
for (i = 1; i <= q; i++)
{
result = result * p;
}
return result;
}
public static void main(String args[])
{
RCLD ob = new RCLD();
int r;
r = ob.power(2, 3);
System.out.println("\n 2 ^ 3 = " + r);
System.out.println("\n 8 ^ 2 = " + ob.power(8, 2));
}
}
Recursion
In C++ any function call any other function, even a function can call itself. When a function calls itself
then this function is said to be recursive.

Page 68 of 90
Blue Java
Recursion is the process of defining something in terms of itself, and is sometimes called circular
definition.
Example:
The factorial of a number n is the product of all the whole numbers between 1 and n. For example,
factorial of 3 is 1 ×2 ×3, or 6.
import java.io.*;

class RCLD
{
public int fact(int n)
{
int f = 1;
if (n <= 1)
return 1;
else
f = fact(n - 1) * n; /* recursive call */
return f;
}

public static void main(String args[])


{
RCLD ob = new RCLD();
int n = 5, f;
f = ob.fact(n);
System.out.println("\n \n Factorial of " + n + " is " + f);
System.out.println("\n Factorial of 6 is " + ob.fact(6));
System.out.println("\n Factorial of 7 is " + ob.fact(7));
}
}
Example: Write a program to construct a calculator using functions.
import java.io.*;

class RCLD
{
int x, y;
public static void main(String args[])throws Exception
{
String st;
int c;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
RCLD ob = new RCLD();
for( ; ; )
{
ob.MENU();
try
{
st = br.readLine();
c = Integer.parseInt(st);
}
catch (Exception e)
{
c = -1;
}
switch(c)
{
case 1:
ob.SUM();
break;
case 2:
ob.SUB();

Page 69 of 90
Blue Java
break;
case 3:
ob.MULT();
break;
case 4:
ob.DIV();
break;
case 5:
System.exit(0);
break;
default:
System.out.println("\n\n\t Please Insert a Valid
Choice");
System.out.println("\007\007");//Beep Sound
}
System.out.println("\n\n\n\t Press any key to
continue...............");
br.readLine();
}
}

public void MENU()


{
System.out.println("\n\n Select a Menu Item\n");
System.out.println("\n\n 1. Summation");
System.out.println("\n\n 2. Subtraction");
System.out.println("\n\n 3. Multiplication");
System.out.println("\n\n 4. Division");
System.out.println("\n\n 5. Exit");
System.out.print("\n\n\n Your Choice: ");
}

public void INPUT() throws Exception


{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("\n\n Enter Value of X: ");
x = Integer.parseInt(br.readLine());
System.out.print("\n\n Enter Value of Y: ");
y = Integer.parseInt(br.readLine());
}

public void SUM()throws Exception


{

System.out.println("\n\n Summation of two numbers");


INPUT();
System.out.println("\n\n Sum of " + x + " and " + y + " is " + (x +
y));
}

public void SUB()throws Exception


{
System.out.println("\n\n Subtraction of two numbers");
INPUT();
System.out.println("\n\n Subtraction of " + x + " and " + y + " is "
+ (x - y));
}

public void MULT()throws Exception


{
System.out.println("\n\n Multiplication of two numbers");
INPUT();

Page 70 of 90
Blue Java
System.out.println("\n\n Multiplication of " + x + " and " + y + " is
" + (x * y));
}

public void DIV()throws Exception


{
System.out.println("\n\n Division of two numbers");
INPUT();
System.out.println("\n\n Division of " + x + " and " + y + " is " +
(x / y));
}
}
Function Prototype
A function prototype is the first line of the function definition that tells the programmer about the type of the
value returned by the function and the number and type of arguments. A function prototype describes the
function interface to the compiler by given details such as the number and type of the arguments and the
type of return values.
Function Signature
A function signature basically refers to the number and types of the arguments. It is part of the function
prototype.
Function Overloading
C++ enables several functions of the same name to be defined, as long as these functions have different sets
of parameters (at least as far as their types are concerned). This capability is called function overloading.

When an overloaded function is called, the C++ compiler selects the proper function by examining the number,
types and order of the arguments in the call.

Function overloading is commonly used to create several functions of the same name that perform similar
tasks but on different data types.

Example –
#include<iostream.h>
#include<conio.h>

int sum(int, int);


float sum(float, float);

void main()
{
int intX = 45, intY = 55, intZ;
float floatX = 256.7213, floatY = 548.3252, floatZ;

clrscr();

intZ = sum(intX, intY);


cout << "\n\nSum of " << intX << " and " << intY
<< " is = " << intZ;

floatZ = sum(floatX, floatY);


cout << "\n\nSum of " << floatX << " and " << floatY
<< " is = " << floatZ;

getch();
}
int sum(int a, int b)
{
return (a + b);

Page 71 of 90
Blue Java
}
float sum(float a, float b)
{
return ( a + b);
}

Scope and Lifetime of variables


Local variable/Auto Variables
Variables that are defined within a function are called local variables or auto variables.
 Lifetime of a local variable comes into existence when the function is entered and is
destroyed when the function is exit.
 A local variable cannot hold its value between function calls.
 The scope of a local variable is local to the block in which the variable define.
 Local variable define inside a function or function parameter.

Example of a Local Variable:

import java.io.*;

class RCLD
{
public int sum(int x, int y)
{
int r;
r = x + y;
return r;
}
public static void main(String args[])
{
int r2;
}
}

Note 1: In this example we used four variables r, x and y. the variable r is defined inside of the
sum() function. Variables x and y are define in function parameters place in sum() function. And
variable r is define inside the function sum(). So, all the variables x, y and r are local variable.

Note 2: We can’t access the variables x, y and r from main() function or similarly we can’t access
the variable r2 from the sum() function. Because, local variables can access from the local to the
block where the variables are defined.

Note 3: In this example, we call the sum() function twice. When we call the sum() function first
time, then variable x, y and r are created. After returning value from the sum() function the
variables x, y and r are destroyed. When we call the sum() function again, then variables x, y, r
are created again and destroy again after returning value.

Note 4: We can declare variables with same name in different function block. Example-

import java.io.*;

class RCLD
{
public int sum(int x, int y)
{
int r;
Page 72 of 90
Blue Java
r = x + y;
return r;
}
public static void main(String args[])
{
int r;
}
}

In this example, we declare the variable r in two place; first, in the main() function block and the
second, in the sum() function block. Actually, there is two variable with same name. So, we can
store two different values in two different places.
Global Variables
Variables that are declared outside all function are called global variables.
 Lifetime of a global variable comes into existence as long as the object of the class is exit.
 A global variable can hold its value between function calls.
 The scope of a global variable is anywhere in the class.
 Global variable define outside all function but within a class.

Example of global variable:


class RCLD
{
int x, y;

int sum(int x, int y)


{
x = 5;
y = 10;
System.out.println("Sum = " + (x + y));
}

int dif(int x, int y)


{
x = 15;
y = 10;
System.out.println("Dif = " + (x - y));
}
}
Here, we used two global variable x and y and use them anywhere in the class.
Function Overloading
Java enables several functions of the same name to be defined, as long as these functions have different sets
of parameters (at least as far as their types are concerned). This capability is called function overloading.

When an overloaded function is called, the Java compiler selects the proper function by examining the
number, types and order of the arguments in the call.

Function overloading is commonly used to create several functions of the same name that perform similar
tasks but on different data types.

Example –
import java.io.*;

class RCLD
{
public void sum(int x, int y)
{

Page 73 of 90
Blue Java
System.out.println(x + " + " + y + " = " + (x + y));
}
public void sum(int x, int y, int z)
{
System.out.println(x + " + " + y + " + " + z + " = " + (x + y + z));
}
public void sum(float x, float y)
{
System.out.println(x + " + " + y + " = " + (x + y));
}
public void sum(float x, float y, float z)
{
System.out.println(x + " + " + y + " + " + z + " = " + (x + y + z));
}
public static void main(String args[])
{
RCLD ob = new RCLD();
ob.sum(10, 20);
ob.sum(10, 20, 30);
ob.sum(22.23F, 55.23F);
ob.sum(22.23F, 55.23F, 77.32F);
}
}

Constructors
A constructor is a member function like other member functions. It executes automatically when an object is
created. Constructor can be overloaded. There is no return value from the constructors. A constructor
always has the same name as the class name.

Syntax for creating constructor –


class <Class Name>
{
public <Class Name>([<Parameter List>])
{
//Body of the constructor
}
}

Characteristic of the constructor


 A java constructor has the same name as the name of the class to which it belongs.
 Constructors never return a value, so it doesn’t have any return data type, not even void.
 Constructors may include parameters of various types, so constructor can be overloaded.
 Constructor is invoked automatically when object is created using the new operator.
 Java provides a default constructor which takes no arguments and performs no special actions or
initializations, when no explicit constructors are provided.
 The only action taken by the implicit default constructor is to call the super class constructor using
the super() call. Constructor arguments provide you with a way to provide parameters for the
initialization of an object.

Example of constructor –
class Cube
{

int length;
int breadth;
int height;

public int getVolume()


Page 74 of 90
Blue Java
{
return (length * breadth * height);
}

public Cube()
{
length = 10;
breadth = 10;
height = 10;
}

public static void main(String[] args)


{
Cube cubeObj;
cubeObj = new Cube();
System.out.println("Volume of Cube is : " + cubeObj.getVolume());
}
}

Overloaded Constructors
Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name
as the class name, their signatures are differentiated by their parameter lists. The example below shows that
the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized
constructor.
class Cube
{

int length;
int breadth;
int height;

public int getVolume()


{
return (length * breadth * height);
}

public Cube()
{
length = 10;
breadth = 10;
height = 10;
}

public Cube(int l, int b, int h)


{
length = l;
breadth = b;
height = h;
}

public static void main(String[] args)


{
Cube cubeObj1, cubeObj2;
cubeObj1 = new Cube();
cubeObj2 = new Cube(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}

It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a
constructor invokes than other constructor with the corresponding parameter list within the same class.
Page 75 of 90
Blue Java
Calling the default constructor to create a Cube object results in the second and third parameterized
constructors being called as well. Java requires that any this() call must occur as the first statement in a
constructor.
class Cube
{

int length;
int breadth;
int height;

public int getVolume()


{
return (length * breadth * height);
}

public Cube()
{
this(10, 10);
System.out.println("Finished with Default Constructor");
}

public Cube(int l, int b)


{
this(l, b, 10);
System.out.println("Finished with 2 Parameterized Constructors");
}

public Cube(int l, int b, int h)


{
length = l;
breadth = b;
height = h;
System.out.println("Finished with 3 Parameterized Constructors");
}

public static void main(String[] args)


{
Cube cubeObj1, cubeObj2, cubeObj3;
cubeObj1 = new Cube();
cubeObj2 = new Cube(10, 20);
cubeObj3 = new Cube(10, 20, 5);

System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());


System.out.println("Volume of Cube2 is : " + cubeObj2.getVolume());
System.out.println("Volume of Cube3 is : " + cubeObj3.getVolume());
}
}

Different between constructor and methods

Topic Constructors Methods


Purpose Create an instance of a class Group Java statements
Modifiers Cannot be abstract, final, native, static, Can be abstract, final, native, static,
or synchronized or synchronized
Return type No return type, not even void void or a valid return type
Name Same name as the class Any name except the class.
this Refers to another constructor in the Refers to an instance of the owning class.
same class. If used, it must be the first Cannot be used by static methods
line of the constructor

Page 76 of 90
Blue Java
super Calls the constructor of the parent Calls an overridden method in the parent
class. If used, must be the first line of class
the constructor
Inheritance Constructors are not inherited Methods are inherited
Compiler automatically If the class has no constructor, a no- Does not apply
supplies a default argument constructor is automatically
constructor supplied
Compiler automatically If the constructor makes no zero-or- Does not apply
supplies a default call to more argument calls to super, a no-
the super class constructor argument call to super is made

static keyword

The static keyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than instance
of the class.

The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

static variable

If you declare any variable as static, it is known static variable.

 The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees, college name of students etc.
 The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

 It makes your program memory efficient (i.e it saves memory).


 Java static property is shared to all objects

Understanding problem without static variable

class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created. All student have its unique rollno and name so instance data member is
good. Here, college refers to the common property of all objects. If we make it static, this field will
get memory only once.

Page 77 of 90
Blue Java
Example of static variable

Program of counter without static variable

In this example, we have created an instance variable named count which is incremented in the
constructor. Since instance variable gets the memory at the time of object creation, each object will
have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each
objects will have the value 1 in the count variable.

class Counter {
int count = 0;//will get memory when instance is created
Counter() {
count++;
System.out.println(count);
}

public static void main(String args[]) {

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();
}
}

Output:
1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object changes the value
of the static variable, it will retain its value.
class Counter2{
static int count=0;//will get memory only once and retain its value

Counter2(){
count++;
System.out.println(count);
}

public static void main(String args[]){


Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}

Output:
1
2
3

static method

If you apply static keyword with any method, it is known as static method.

 A static method belongs to the class rather than object of a class.


Page 78 of 90
Blue Java
 A static method can be invoked without the need for creating an instance of a class.
 Static method can access static data member and can change the value of it.

Example of static method


//Program of changing the common property of all objects(static field).

class Student9 {
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}

Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal calculation
//Program to get cube of a given number by static method

class Calculate {
static int cube(int x) {
return x*x*x;
}

public static void main(String args[]) {


int result=Calculate.cube(5);
System.out.println(result);
}
}

Output:
125
Restrictions for static method
There are two main restrictions for the static method. They are:

1. The static method cannot use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
Page 79 of 90
Blue Java
class A {
int a=40;//non static

public static void main(String args[]) {


System.out.println(a);
}
}

Output:
Compile Time Error
Why java main method is static?
Ans: -

Because object is not required to call static method if it were non-static method, jvm create object first then
call main() method that will lead the problem of extra memory allocation.

static block

 Is used to initialize the static data member.


 It is executed before main method at the time of class-loading.

Example of static block


class A2 {
static {
System.out.println("static block is invoked");
}
public static void main(String args[]) {
System.out.println("Hello main");
}
}

Output:
static block is invoked
Hello main
Can we execute a program without main() method?

Ans: -

Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.

class A3 {
static {
System.out.println("static block is invoked");
System.exit(0);
}
}

Output:
static block is invoked (if not JDK7)

In JDK7 and above, output will be:

Output:
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)

Page 80 of 90
Blue Java

this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Suggestion: If you are beginner to java, lookup only two usage of this keyword.

1) The this keyword can be used to refer current class instance variable.

If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of
ambiguity.

Understanding the problem without this keyword


Let's understand the problem if we don't use this keyword by the example given below:

class Student10 {
int id;
String name;

Student10(int id,String name) {


id = id;
name = name;
}
void display(){
System.out.println(id+" "+name);
}

public static void main(String args[]) {


Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();

Page 81 of 90
Blue Java
}
}
Test it Now
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is why we are
using this keyword to distinguish between local variable and instance variable.

Solution of the above problem by this keyword


//example of this keyword

class Student11 {
int id;
String name;

Student11(int id,String name) {


this.id = id;
this.name = name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Test it Now
Output111 Karan
222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword
like in the following program:

Program where this keyword is not required


class Student12 {
int id;
String name;

Student12(int i,String n) {
id = i;
Page 82 of 90
Blue Java
name = n;
}
void display() {
System.out.println(id+" "+name);
}
public static void main(String args[]) {
Student12 e1 = new Student12(111,"karan");
Student12 e2 = new Student12(222,"Aryan");
e1.display();
e2.display();
}
}
Test it Now
Output:111 Karan
222 Aryan
2) this() can be used to invoked current class constructor.

The this() constructor call can be used to invoke the current class constructor (constructor chaining).
This approach is better if you have many constructors in the class and want to reuse that constructor.

//Program of this() constructor call (constructor chaining)

class Student13 {
int id;
String name;

Student13() {
System.out.println("default constructor is invoked");
}

Student13(int id,String name) {


this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display() {
System.out.println(id+" "+name);
}

public static void main(String args[]) {


Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Test it Now
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
Where to use this() constructor call?
The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain
between the constructors i.e. it is used for constructor chaining. Let's see the example given below that
displays the actual use of this keyword.

class Student14{
int id;
String name;
String city;
Page 83 of 90
Blue Java

Student14(int id,String name) {


this.id = id;
this.name = name;
}
Student14(int id,String name,String city) {
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display() {
System.out.println(id+" "+name+" "+city);
}

public static void main(String args[]) {


Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
Test it Now
Output:111 Karan null
222 Aryan delhi
Rule: Call to this() must be the first statement in constructor.
class Student15 {
int id;
String name;

Student15() {
System.out.println("default constructor is invoked");
}

Student15(int id,String name) {


id = id;
name = name;
this ();//must be the first statement
}
void display() {
System.out.println(id+" "+name);
}

public static void main(String args[]) {


Student15 e1 = new Student15(111,"karan");
Student15 e2 = new Student15(222,"Aryan");
e1.display();
e2.display();
}
}
Test it Now
Output:Compile Time Error

3)The this keyword can be used to invoke current class method (implicitly).

You may invoke the method of the current class by using the this keyword. If you don't use the this keyword,
compiler automatically adds this keyword while invoking the method. Let's see the example

Page 84 of 90
Blue Java

class S {
void m() {
System.out.println("method is invoked");
}

void n() {
this.m();//no need because compiler does it for you.
}

void p() {
n();//complier will add this to invoke n() method as this.n()
}

public static void main(String args[]) {


S s1 = new S();
s1.p();
}
}
Test it Now
Output:method is invoked
4) this keyword can be passed as an argument in the method.

The this keyword can also be passed as an argument in the method. It is mainly used in the event handling.
Let's see the example:

class S2 {

void m(S2 obj) {


System.out.println("method is invoked");
}

void p() {
m(this);
}

public static void main(String args[]) {


S2 s1 = new S2();
s1.p();
}
}
Test it Now
Output:method is invoked

Page 85 of 90
Blue Java
Application of this that can be passed as an argument:
In event handling (or) in a situation where we have to provide reference of a class to another one.

5) The this keyword can be passed as argument in the constructor call.

We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple
classes. Let's see the example:

class B {
A4 obj;

B(A4 obj) {
this.obj=obj;
}

void display() {
System.out.println(obj.data);//using data member of A4 class
}
}

class A4 {
int data=10;

A4() {
B b=new B(this);
b.display();
}
public static void main(String args[]) {
A4 a=new A4();
}
}
Test it Now
Output:10
6) The this keyword can be used to return current class instance.

We can return the this keyword as an statement from the method. In such case, return type of the method
must be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


return_type method_name(){
return this;
}
Example of this keyword that you return as a statement from the method
class A {
A getA() {
return this;
}

void msg() {
System.out.println("Hello java");
}
}

class Test1 {
public static void main(String args[]) {
new A().getA().msg();
}
}

Page 86 of 90
Blue Java
Test it Now
Output:Hello java
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are printing
the reference variable and this, output of both variables are same.

class A5 {
void m() {
System.out.println(this);//prints same reference ID
}

public static void main(String args[]) {


A5 obj=new A5();
System.out.println(obj);//prints the reference ID

obj.m();
}
}
Test it Now
Output:A5@22b3ea59
A5@22b3ea59
Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object.

The idea behind inheritance in java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and
you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing class.

In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.

Page 87 of 90
Blue Java
Understanding the simple example of inheritance

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type
of Employee.

class Employee {
float salary=40000;
}

class Programmer extends Employee {


int bonus=10000;

public static void main(String args[]) {


Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

Page 88 of 90
Blue Java

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and
B classes have same method and you call it from child class object, there will be ambiguity to call
method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if you inherit
2 classes. So whether you have same method or different, there will be compile time error now.

class A {
void msg() {

Page 89 of 90
Blue Java
System.out.println("Hello");
}
}

class B {
void msg() {
System.out.println("Welcome");
}
}

class C extends A, B { //suppose if it were

Public Static void main(String args[]) {


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error

Page 90 of 90

Potrebbero piacerti anche