Call A Method
Call A Method
Call A Method
Class: XII
Topic: Unit-3:
Subject: Information Technology (802) Fundamentals of Java Programming (Contd..)
Call a Method
Given the length and breadth of a rectangle as parameters returns the area of the rectangle.
static double rectangle_area (double length, double breadth)
{
return (length * breadth);
When the length and breadth of the rectangle as arguments in the method call. The arguments with which the
rectangle_area method is called are copied into its parameters. In this case, 45.5 is copied into the parameter
length and 78.5 is copied into the parameter breadth.
Multiple Parameters
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod(“Thomas", 10);
myMethod("Jenny", 18);
myMethod(“Raju", 38);
}
Note: When you are working with multiple parameters, the method call must have the same number of
arguments as there are parameters, and the arguments must be passed in the same order.
Return Values:
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of
void, and use the return keyword inside the method:
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
}
A Method with If...Else
public class Main {
// Create a checkAge() method with an integer parameter called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");
A class is a physical or logical entity that has certain attributes. The title, author, publisher, genre and price
are the data members of the class Book. Displaying book details and getting its price are method members
of the class Book. Method members can get, set or update the class data members.
Class - Book
Data Members – Title, Author, Publisher, Genre, Price
Method Members - display(), getPrice()
For example one book in the library would be an object populated with the following data members:
Book: book1, Title: Game of Thrones, Author: George R Martin, Publisher: Harper Collins
Genre: Fiction, Price: 450
Another book would be another object populated with the following data members:
Book: book2, Title: Fundamentals of Database Systems, Author: Shamkant Navathe
Publisher: Pearson, Genre: Educational, Price: 400
All objects of the same class have the same type of data members.
Class Design
A class in Java begins with the keyword class followed by the name of the class. The body of the class is
enclosed within curly braces. The body contains the definitions of the data and method members of the class.
The data members are defined by specifying their type. The method members of the class are defined just
like the user defined methods we saw earlier. The method members have access to all the data members of
the class and can use them in their body. The data members of a class are like global variables – they can be
accessed by all the method members of the class.
Constructors
A special method member called the constructor method is used to initialize the data members of the class
(or any other initialization is to be done at time of object creation).
The constructor has the same name as the class, has no return type, and may or may not have a parameter
list. Whenever a new object of a class is created, the constructor of the class is invoked automatically.
Access Modifiers
Data members of a class can be accessed from outside the class by default. However, it is generally not good
programming practice to allow data members to be accessed outside the class. By allowing objects to change
their data members arbitrarily, we lose control over the values being held in them. This makes debugging
code harder and our code vulnerable to security issues. To make a data member or a method member of a
class visible only within the class, we add the keyword private before its declaration. Private members of a
class cannot be accessed outside the class. Declaring the data members of the Book class private, we won't
be allowed access to them in the class
Similarly, we define a setter method but control how the price is set. We do not allow a book price to
become lower than 100.00.
void setPrice(double newprice) {
if (newprice < 100)
System.out.println("Price cannot be set lower than 100!");
else
price = newprice;
}
Java Libraries
The power of Java comes from the hundreds of Java classes that are already prebuilt and can be used in your
programs. To use a prebuilt class and associated methods in those class, all you have to do is to use the
keyword import to import the class from the package in which it is contained into your space. The import
statements must appear before any class definitions in the file.
Data Input
A program is interactive if it is able to take input from the user and respond accordingly.
Write a program to take user input. To take user input we use the prebuilt Scanner class. This class is
available in the java.util package. First we import this class,
import java.util.Scanner;
Now we create an object of the class Scanner. The constructor of this class requires the source from which
input is to be taken. Since we will take input from the console, we use the System.in object.
Scanner user_input = new Scanner(System.in);
Then, we invoke the next() method of the Scanner class that returns the token read from the input stream as a
String object.
String name = user_input.next();
System.out.println("Hello "+ name);
To read numeric data input, again a Java prebuilt class comes to our rescue. This time we use the Integer
class. The class has a static method parseInt() that takes a String as parameter and returns the equivalent
integer.
String age_string = user_input.next( );
int age = Integer.parseInt(age_string);
System.out.print("In 5 years you will be "+ (age +5));
System.out.println(" years old.");
Array Manipulation
The Arrays class has a number of useful methods. Let us start by using the sort()method to sort an array of
integers in ascending order.
import java.util.Arrays class. Then in the main() method, we invoke the Arrays.sort() method on the array
we need to sort.
double[ ] marks = {103, 144, 256.5,346, 387.5};
Arrays.sort(marks);
String Manipulation
The first method we will use from the String class is the toUpperCase() method. This method converts a
string to all uppercase letters.
String myString = "Hello World";
System.out.println("UpperCase: " + myString.toUpperCase());
Assertions: An assertion is a useful mechanism for effectively identifying/detecting and correcting logical
errors in a program. An assert statement states a condition that should be true at a particular point during the
execution of the program.
There are two ways to write an assertion
assert expression;
assert expression1 : expression2
The first statement evaluates expression and throws an AssertionError if expression is false. The second
statement evaluates expression1 and throws an AssertionError with expression2 as the error message if
expression1is false.
Threads: Threads allows a program to operate more efficiently by doing multiple things at the same
time. Threads can be used to perform complicated tasks in the background without interrupting the main
program.
In Java, threads can be created in two ways
1. By extending the Thread class
2. By implementing the Runnable interface
The first method to create a thread is to create a class that extends the Thread class from the java.lang
package and override the run() method. The run() method is the entry point for every new thread that is
instantiated from the class.
public class ExtendThread extends Thread {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}
Wrapper Classes: Sometimes, you may need to pass the primitive datatypes by reference. That is when you
can use wrapper classes provided by Java. These classes wrap the primitive datatype into an object of that
class. For example, the Integer wrapper class holds an int variable.
Consider the following two declarations:
int a = 50;
Integer b = new Integer(50);
In the first declaration, an int variable is declared and initialized with the value 50. In the second declaration,
an object of the class Integer is instantiated and initialized with the value 50. The variable a is a memory
location and the variable b is a reference to a memory location that holds an object of the class Integer.
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}
Another useful method is the toString() method, which is used to convert wrapper objects to strings.
In the following example, we convert an Integer to a String, and use the length() method of the String class
to output the length of the "string":
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}
The while statement evaluates the test before executing the body of a loop. A while loop is an entry
controlled loop. The structure of the Java while statement is as shown:
The While Statement
while (expression)
{
statements
}
Exception Handling
Some of your programs when executed may have terminated unexpectedly with runtime errors. The errors
could have occurred because an array index reference was out of range, or an attempt was made to divide an
integer by zero, or there was insufficient computer memory and so on. Such an error situation that is
unexpected in the program execution and causes it to terminate unexpectedly is called an exception. As a
programmer, you should anticipate exceptions in your program that could lead to unpredictable results and
handle the exceptions.
Java provides an exception handling mechanism so that a program is able to deal with exceptions, and
continue executing or terminate gracefully. The basic idea in exception handling is to
Denote an exception block - Identify areas in the code where errors can occur
Catch the exception - Receive the error information
Handle the exception - Take corrective action to recover from the error
Java provides the following keywords to handle an exception:
try - A try block surrounds the part of the code that can generate exception(s).
catch – The catch blocks follow a try block. A catch block contains the exception
handler - specific code that is executed when the exception occurs. Multiple catch
blocks following a try block can handle different types of exceptions.
The structure of a try-catch statement block for exception handling is as below:
try {
// Part of the program where an exception might occur
}
catch (exceptiontype1 argument1) {
// Handle exception of the exceptiontype1
}
catch (exceptiontype2 argument2) {
// Handle exception of the exceptiontype2
}
finally {
//Code to be executed when the try block exits
}
The try block is examined during execution to detect any exceptions that may be thrown by any
statements or any calls to methods within the block. If an exception is thrown, an exception object is created
and thrown. The program execution stops at that point and control enters the catch block whose argument
matches the type of the exception object thrown. If a match is found the statements in that catch block are
executed for handling the exception. If no exception is thrown during execution of the statements in the try
block, the catch clauses that follow the try block are not executed. Execution continues at the statement after
the last catch clause. The optional finally block is always executed when the try block exits. This means
the finally block is executed whether an exception occurs or not.
Database Connectivity
Connecting a database to a Java program is easy with NetBeans since it allows us to connect directly to a
MySQL server.
Connecting to the MySQL Server in NetBeans
Step 1: Click on the Services tab located on the left side of the NetBeans IDE. Right click the Databases
node and select Register MySQl Server
Step 2: In the MySQL Server Properties Dialog Box that opens up, type in the Administrator User Name
(if not displayed). Also type in the Administrator Password for your MySQl Server. Check the Remember
Password checkbox and click on OK
Step 3: In the same MySQL Server Properties Dialog Box, click on the Admin In the Path/URL to admin
tool field, type or browse to the location of your MySQL Administration application mysqladmin (you will
find it in the bin folder of your MySQL installation directory).
In the Path to start command, type or browse to the location of the MySQL start command mysqld (you
will find it in the bin folder of your MySQL installation directory).
In the Path to stop command field, type or browse to the location of the MySQL stop command
mysqladmin (you will find it in the bin folder of your MySQL installation directory). In the Arguments
field, type -u root stop to grant root permissions for stopping the server. When finished, the Admin
Properties tab should appear similar to Figure 3.11(c). Click on OK.
The MySQL Server should now appear under the Database node in the Services tab in the NetBeans IDE
Step 4:To connect the MySQL Server to NetBeans, under the Databases node, right click the MySQL
Server at localhost:3306 [root] (disconnected) and select Connect
Step5: When the server is connected you should see the [disconnected] removed from the MySQL Server
at localhost:3306 [root] database. You should also be able to expand the MySQL Server node by Clicking
on the + sign to view all the available MySQL databases
Step1: Under the Projects tab, right click on the Libraries node and select ADD JAR/Folder…
Step 2: In the Add JAR/Folder dialog box that appears, navigate to the your NetBeans Installation
Folder. Then navigate to the /ide/modules/ext folder and select the mysql-connector-java-5.1.23-bin.jar
file. Click on Open
Each database driver has a different syntax for the URL. The MySQl URL has a hostname, the port, and the
database name. In our program we construct a String with hostname as localhost, port number as 3306, and
the database name as bookstore.
String dbURL = "jdbc:mysql://localhost:3306/bookstore";
We also assign the username and password, this has to be the same username and password that is used for
starting the MySQL Server.
String username ="root";
String password = "password";
Next, we invoke the getconnection() method using the URL, username, and password:
Connection dbCon =DriverManager.getConnection(dbURL, username, password);
Next, we use the Connection object returned by the getconnection() method and invoke the
createStatement() method. This method returns a Statement object for sending SQL statements to the
database.
Statement stmt = dbCon.createStatement();
Next, we invoke the executeQuery() method of the Statement object to execute an SQL query. This method
returns a single ResultSet object. The ResultSet is a table of data returned by a specific SQL statement.
String query ="select * from book";
ResultSet rs = stmt.executeQuery(query);
Finally, we use the next() method of the ResultSet object to iterate through all the rows of data returned by
the query. When there are no more rows left, the next() method will return false. Since we know there are 5
columns in the book table.
we use a for loop and the getString() method of the ResultSet object to print all the five columns.
while(rs.next()){
for (int i = 1; i <=5; i++) {
System.out.print(rs.getString(i));
System.out.print("|");
}
System.out.println();
}
All the statements described above have to be put in a try catch block to catch Exceptions (of the Exception
type SQL Exception) that can occur while connecting or fetching data from the database.
Assignment:
1. Write a program in Java to print the square of every alternate number of an array.