Java Material 1st Unit
Java Material 1st Unit
What is Java?
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
Object Oriented
In Java, everything is an Object. Java can be easily extended since it is based on the Object model.
Platform Independent
Unlike many other programming languages including C and C++, when Java is compiled, it is not
compiled into platform specific machine, rather into platform-independent byte code. This byte
code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever
platform it is being run on.
Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be
easy to master.
Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the compiled code
executable on many processors, with the presence of Java runtime system.
Portable
Being architecture-neutral and having no implementation dependent aspects of the specification
makes Java portable. The compiler in Java is written in ANSI C with a clean portability boundary,
which is a POSIX subset.
Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time
error checking and runtime checking.
Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that
can run smoothly.
Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
The development process is more rapid and analytical since the linking is an incremental and light-
weight process.
High Performance
With the use of Just-In-Time compilers, Java enables high performance.
Distributed
Java is designed for the distributed environment of the internet.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment. Java programs can carry an extensive amount of run-time information that can be
used to verify and resolve accesses to objects at run-time.
Java Syntax
In the previous chapter, we created a Java file called Main.java, and we used the following code to
print "Hello World" to the screen:
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Example explained
Every line of code that runs in Java must be inside a class. In our example, we named the class
Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
The name of the java file must match the class name. When saving the file, save it using the class
name and add ".java" to the end of the filename. To run the example above on your computer, make
sure that Java is properly installed: Go to the Get Started Chapter for how to install Java. The output
should be:
Hello World
Any code inside the main() method will be executed. Don't worry about the keywords before and
after main. You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename,
and that every program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
output :
Hello World
Java Output
You learned from the previous chapter that you can use the println() method to output values or
print text in Java:
Example
System.out.println("Hello World!");
You can add as many println() methods as you want. Note that it will add a new line for each
method:
Example
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
Example
System.out.println(3 + 3);
Note that we don't use double quotes ("") inside println() to output numbers.
Example
public class Main {
public static void main(String[] args) {
System.out.print("Hello World! ");
System.out.print("I will print on the same line.");
}
}
output :
Hello World! I will print on the same line.
Note that we add an extra space (after "Hello World!" in the example above), for better readability.
In this tutorial, we will only use println() as it makes it easier to read the output of code.
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by Java (will not be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World"); // This is a comment
Example
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Numbers
Primitive number types are divided into two groups:
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for whole
numbers) and double (for floating point numbers). However, we will describe them all as you
continue to read.
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or
other integer types to save memory when you are certain that the value will be within -128 and 127:
Example
byte myNum = 100;
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
short myNum = 5000;
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
Example
int myNum = 100000;
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the value. Note that you
should end the value with an "L":
Example
long myNum = 15000000000L;
System.out.println(myNum);
Float Example
float myNum = 5.75f;
System.out.println(myNum);
Double Example
double myNum = 19.99d;
System.out.println(myNum);
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Boolean Types
A boolean data type is declared with the boolean keyword and can only take the values true or false:
Example
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Characters
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);
Alternatively, if you are familiar with ASCII values, you can use those to display certain characters:
Example
char myVar1 = 65, myVar2 = 66, myVar3 = 67;
System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Tip: A list of all ASCII values can be found in our ASCII Table Reference.
Strings
The String data type is used to store a sequence of characters (text). String values must be
surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
Syntax
type variableName = value;
Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John":
String name = "John";
System.out.println(name);
To create a variable that should store a number, look at the following example:
Example
Create a variable called myNum of type int and assign it the value 15:
int myNum = 15;
System.out.println(myNum);
You can also declare a variable without assigning the value, and assign the value later:
Example
int myNum;
myNum = 15;
System.out.println(myNum);
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Example
Change the value of myNum from 15 to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will
declare the variable as "final" or "constant", which means unchangeable and read-only):
Example
final int myNum = 15;
myNum = 20; // will generate an error: cannot assign a value to a final variable
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
To declare an array, define the variable type with square brackets:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, we can use an
array literal - place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Example
cars[0] = "Opel";
Array Length
To find out how many elements an array has, use the length property:
Example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}
Output :
4
Multidimensional Arrays
A multidimensional array is an array of arrays.
To create a two-dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
Example
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}
}
Output :
7
We can also use a for loop inside another for loop to get the elements of a two-dimensional array
(we still have to point to the two indexes):
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}
Output
1
2
3
4
5
6
7
Java provides various datatypes to store various data values. It provides 7 primitive datatypes
(stores single values) as listed below −
boolean − Stores 1-bit value representing true or, false.
byte − Stores twos compliment integer up to 8 bits.
char − Stores a Unicode character value up to 16 bits.
short − Stores an integer value upto 16 bits.
int − Stores an integer value upto 32 bits.
long − Stores an integer value upto 64 bits.
float − Stores a floating point value upto 32bits.
double − Stores a floating point value up to 64 bits.
Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case
the casting/conversion is not done automatically, you need to convert explicitly using the cast
operator “( )” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes
need not be compatible with each other.
Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
Output
Enter an integer value:
67
Character value of the given integer: C
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition){
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multi-
ple blocks of code called cases and a single case is executed based on the variable which is being
switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Default statement is executed when any of the case doesn't match the value of expression. It
is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2
While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value. The switch permits only int, string, and
Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the con-
dition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
The flow chart for the for-loop is given below.
Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in
while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop
will be executed.
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Consider the following example.
Calculation .java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can
use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syn-
tax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are
two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks only
the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}
Output:
0
1
2
3
4
5
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
class <class_name>
{
field;
method;
}
Objects and Classes in Java
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical en-
tity only
What is an object in Java
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the
banking system.
An object has three characteristics:
o Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each
object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to
write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are cre-
ated. So, an object is the instance(result) of a class.
Object Definitions:
In this example, we have created a Student class which has two data members id and name. We are
creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
//Java Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
Test it Now
Output:
0
null
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be ac-
cessed from outside the package. If you do not specify any access level, it will be the de-
fault.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within
the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, tran-
sient, etc. Here, we are going to learn the access modifiers only.
1) Private
If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except nested class.
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility
than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the pack-
age.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class.
It provides more accessibility than the default modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is declared
as protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other modi-
fiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes several
statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method
with or without parameters, and apply method abstraction in the program design.
Creating Method
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
public static − modifier
int − return type
methodName − name of the method
a, b − formal parameters
int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown in the fol-
lowing syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
Example
Here is the source code of the above defined method called min(). This method takes two parame-
ters num1 and num2 and returns the maximum between the two −
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
Method Calling
For using a method, it should be called. There are two ways in which a method is called i.e., method
returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control
gets transferred to the called method. This called method then returns control to the caller in two
conditions, when −
Example
Live Demo
public class ExampleMinNumber {
return min;
}
}
This will produce the following result −
Output
Minimum value = 6
The void Keyword
The void keyword allows us to create methods which do not return a value. Here, in the following
example we're considering a void method methodRankPoints. This method is a void method, which
does not return any value. Call to a void method must be a statement
i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the
following example.
Example
Live Demo
public class ExampleVoid {
Output
Rank:A1
Passing Parameters by Value
While working under calling process, arguments is to be passed. These should be in the same order
as their respective parameters in the method specification. Parameters can be passed by value or by
reference.
Passing Parameters by Value means calling a method with a parameter. Through this, the argument
value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values of the argu-
ments remains the same even after the method invocation.
Live Demo
public class swappingExample {
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
This will produce the following result −
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
When a class has two or more methods by the same name but different parameters, it is known as
method overloading. It is different from overriding. In overriding, a method has the same method
name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s
say we want to find the minimum number of double type. Then the concept of overloading will be
introduced to create two or more methods with the same name but different parameters.
Example
Live Demo
public class ExampleOverloading {
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will produce the following result −
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the same name but
with different parameters. The minimum number from integer and double types is the result.
Class Design
Introduction
Consider a car manufacturing. A motor giant BMW does not make all parts for its new model of a
car. Various pieces (wheels, doors, seats, breaks, sparks...) come from different manufacturers. This
model keeps the cost down and let BMW response to the market needs in the most efficient way.
The main BMW's responsibility is to design a car, and then to assemble it from already existent
parts (a small amount of completely new details might be necessary). Object-oriented programming
(OOP) springs from the same idea of using preassembled modules. The OOP provides the program-
mer with a natural way to divide an application into small reusable pieces, called objects. At the
same time, the OOP provides an elegant way to construct applications in more efficient way by
building up from a collection of reusable components.
All software objects have state and behavior. For example, a student as an object has a name, ad-
dress, list of courses, and grades. All these are a state (or data). On the other hand, the student has
behaviors (or methods), such as adding a new course, changing the address. Therefore,each object is
a collection of data and methods (or algorithms) applied to its internal data.
An object should never allow an external manipulation (the client access) over the internal data or
expose data to other objects. Why not give the client direct access to the fileds? Because this will
create problems in the long run. For example, if you change the name of theat field, the client will
no longer work. Also, the object should never expose details of an algorithm implementation.
Clients need only know what your methods do, not how you implement them. In short,
Data is private
Implementation is hidden
Encapsulation is the idea of hiding data and methods implementations from the client. By encapsu-
lation you reduce data dependency and maximize reusability.
How do we describe the objects? By designing classes. Think of a class as a template for objects.
We can create several objects from one class. Such process is called an instantiation. An object, in
effect, is an ainstantiated class. There are three ways to design classes: by composition, via inheri-
tance, and via interface.
Composition (or aggregation) is achieved by using existing class as a part of a new class. For ex-
ample, the ArrayStack class includes an array of objects.
Inheritance allows you to define a new class in terms of an old class. The new class automatically
inherits all public members of the original class. Inheritance is useful for creating specialized ob-
jects that share comon behavior. We will see more on inheritance later in the course.
Interfaces act like inheritance in the way that they define a set of properties, methods,and events,
but unlike classes they do not provide implementation. A class that implements the interface muct
implement every method of that interface exactly as it is defined. We will see more on interfaces
later in the course.