Advanced Java(Update)
Advanced Java(Update)
By Anderson
Java Methods
method is a block of code which only runs when it is called.
Methods are used to perform certain actions, and they are also known as functions.
1.To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods to perform
certain actions:
Example
// code to be executed
Example Explained
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a
semicolon;
In the following example, myMethod() is used to print a text (the action), when it is
called:
Example
myMethod();
Example
myMethod();
myMethod();
myMethod();
Output:
Parameters are specified after the method name, inside the parentheses. You can add
as many parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter.
When the method is called, we pass along a first name, which is used inside the method
to print the full name:
Example:
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Return Values
In the previous page, we used the void keyword in all examples, which indicates that
the method should not return a value.
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:
Example:
return 5 + x;
System.out.println(myMethod(3));
// Outputs 8
This example returns the sum of a method's two parameters:
Example
return x + y;
System.out.println(myMethod(5, 3));
// Outputs 8
You can also store the result in a variable (recommended, as it is easier to read
and maintain):
Example
return x + y;
Java Classes
Java OOP
Object-oriented programming is about creating objects that contain both data and methods.
Answer:
Look at the following illustration to see the difference between class and objects:
Answer:
Principles of OOP
OOP allows objects to interact with each other using four basic principles: encapsulation,
inheritance, polymorphism, and abstraction.
1.Java Abstraction
Data abstraction is the process of hiding certain details and showing only essential information
to the user.
2.Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
● provide public get and set methods to access and update the value of a private
variable
The get method returns the variable value, and the set method sets the value.Syntax
for both is that they start with either get or set, followed by the name of the variable,
with the first letter in upper case:
Why Encapsulation?
● Better control of class attributes and methods
● Class attributes can be made read-only (if you only use the get method), or write-only
(if you only use the set method)
● Flexible: the programmer can change one part of the code without affecting other parts
● Increased security of data
Like we specified in the previous chapter; Inheritance lets us inherit attributes and methods
from another class. Polymorphism uses those methods to perform different tasks. This allows
us to perform a single action in different ways.
Everything in Java is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.
Create a Class
To create a class, use the keyword class:
Main.java
Create an Object
In Java, an object is created from a class. We have already created the class named Main, so
now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use the
keyword new
Multiple Objects
You can create multiple objects of one class:
Remember that the name of the java file should match the class name. In this example,
we have created two files in the same directory/folder:
● Main.java
● Second.java
Java Class Attributes
In the previous chapter, we used the term "variable" for x in the example (as shown
below). It is actually an attribute of the class. Or you could say that class attributes are
variables within a class:
Accessing Attributes
You can access attributes by creating an object of the class, and by using the dot syntax
(.):
The following example will create an object of the Main class, with the name myObj.
We use the x attribute on the object to print its value:
Modify Attributes
You can also modify attribute values:
If you don't want the ability to override existing values, declare the attribute as final:
The final keyword is useful when you want a variable to always store the same value,
like PI (3.14159...)
In the example above, we created a static method, which means that it can be
accessed without creating an object of the class, unlike public, which can only be
accessed by objects:
Access Methods With an Object
Example explained
3) The fullThrottle() method and the speed() method will print out some text, when they
are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this in 8).
5) In order to use the Main class and its methods, we need to create an object of the Main
Class.
6) Then, go to the main() method, which you know by now is a built-in Java method that runs
your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run
the program using the name of the object (myCar), followed by a dot (.), followed by the name
of the method (fullThrottle(); and speed(200);). Notice that we add an int parameter
of 200 inside the speed() method.
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes:
Note that the constructor name must match the class name, and it cannot have a
return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial values
for object attributes.
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our
examples:
The public keyword is an access modifier, meaning that it is used to set the access level for
classes, attributes, methods and constructors.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI components that
simplify desktop Applications. Many programmers think that JFC and Swing are one
and the same thing, but that is not so. JFC contains Swing [A UI component package]
and quite a number of other items:
STEP 1: Install MySQL JDBC DRIVER (IMPORTANT - Don't MISS This Step!)
You need to install an appropriate JDBC (Java Database Connectivity) driver to run your
Java database programs. The MySQL's JDBC driver is called "MySQL Connector/J"
and is available at MySQL mother site.
For Windows
On your current project ,navigate to a File named Project Files ,inside it we can see a
pom.xml file:
And open the pom.xml file,
In the project structure ,you will open the File Dependencies and confirm that the
dependencies have been added.
We have to set up a database before embarking on our database programming. We shall call
our database "university" which contains a table called "students", with 5 columns, as
below:
STEP 3.Start a MySQL client: I shall also assume that there is an authorized
user called "root" with password "xxxx".
STEP 4: TEST IF THE CONNECTION WORKS
Try out the following JDBC program, which issues an SQL SELECT to
MySQL from a Java Program.
1. The JDBC operations are carried out through the "Connection", "Statement"
and "ResultSet" objects (defined in package java.sql). However, you need
not know the details, but merely the public methods defined in the API
(Application Program Interface). You also need not re-invent the wheels by
creating these classes yourself (which will take you many years?!). "Re-using"
software component is a main strength of OOP.
2. Notice that there is little programming involved in using JDBC programming. You
only have to specify the database-URL, write the SQL query, and process the
query result. The rest of the codes are kind of "standard JDBC program
template". Again, this is because the wheels have been invented.
3. In Line 7, we allocate a Connection object (called conn) via
DriverManager.getConnection(database-url, db-user, password).
The Java program uses a so-called database-URL to connect to the server:
For MySQL:
// Syntax
Connection conn =
DriverManager.getConnection("jdbc:mysql://{host}:{port}/{database-name}", "{user}",
"{password}");
// Example
○ Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/students",
"root", "xxxx");
The database-url is in the form of
"jdbc:mysql://{host}:{port}/{database-name}", with protocol
jdbc and sub-protocol mysql. The port specifies the MySQL server's
TCP port number; user/password is an authorized MySQL user. In our
example, "localhost" (with a special IP address of 127.0.0.1) is the
hostname for local loop-back testing; "3306" is the server's TCP port
number, and students is the database name.
4. In Line 13, we allocate a Statement object (called pstmt) inside the
Connection created in the previous step via conn.createStatement().
5. In Line 16, we write a SQL SELECT command string (called strSelect).
6. To execute the SQL command, we invoke method
stmt.executeQuery(strSelect). It returns the query result in a
ResultSet object (called rs).
7. The ResultSet models the returned table, which can be access via a row
cursor. The cursor is initially positioned before the first row in the ResultSet.
The method rs.next() moves the cursor to the first row. You can then use
rs.getXxx(columnName) to retrieve the value of the column for that row,
where Xxx corresponds to the type of the column, such as int, float, double
and String.
8. The while-loop issue rset.next() repeatedly to move the cursor to the next
row, and processes row-by-row.
9. The rset.next() returns false at the last row of the ResultSet, which
terminates the while-loop.
10.You could use rset.getString(columnName) to retrieve all types (int,
double, etc).
11.For maximum portability, ResultSet columns within each row should be read in
left-to-right order, and each column should be read only once via the getXxx()
methods. Issue getXxx() to a cell more than once may trigger a strange error.
Example 2: SQL INSERT