[go: up one dir, main page]

0% found this document useful (0 votes)
1 views35 pages

Advanced Java(Update)

The document provides an overview of advanced Java concepts, focusing on methods, classes, and object-oriented programming principles such as encapsulation, inheritance, and polymorphism. It explains how to create and call methods, use parameters and return values, and introduces Java Swing for GUI development. Additionally, it covers connecting Java applications to MySQL databases using JDBC, including installation steps for the MySQL JDBC driver.

Uploaded by

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

Advanced Java(Update)

The document provides an overview of advanced Java concepts, focusing on methods, classes, and object-oriented programming principles such as encapsulation, inheritance, and polymorphism. It explains how to create and call methods, use parameters and return values, and introduces Java Swing for GUI development. Additionally, it covers connecting Java applications to MySQL databases using JDBC, including installation steps for the MySQL JDBC driver.

Uploaded by

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

ADVANCED JAVA

By Anderson
Java Methods
method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods?

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

Create a method inside Main:

public class Main {

static void myMethod() {

// code to be executed

Example Explained

●​ myMethod() is the name of the method


●​ static means that the method belongs to the Main class and not an object of the Main
class. You will learn more about objects and how to access methods through objects
later in this tutorial.
●​ void means that this method does not have a return value. You will learn more about
return values later in this chapter

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

Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();
myMethod();

Output:

// I just got executed!

// I just got executed!

// I just got executed!

Parameters and Arguments


Information can be passed to methods as a parameter. Parameters act as variables
inside the method.

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:

public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

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:

public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

System.out.println(myMethod(3));

// Outputs 8
This example returns the sum of a method's two parameters:

Example

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

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

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);


System.out.println(z);

Java Classes
Java OOP

Java - What is OOP?


OOP stands for Object-Oriented Programming.

Object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

●​ OOP is faster and easier to execute


●​ OOP provides a clear structure for the programs
●​ OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
●​ OOP makes it possible to create full reusable applications with less code and shorter
development time

Qn. What does OOP stand for? (1 mk)

Answer: OOP stands for Object-Oriented Programming.

Qn. List 2 advantages of OOP(2 mks)

Answer:

●​ OOP is faster and easier to execute


●​ OOP makes it possible to create full reusable applications with less code and shorter
development time
Java - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and objects:

So, a class is a template for objects, and an object is an instance of a class.

Qn.What is the difference between a class and an object(4mks)

Answer:

So, a class is a template for objects, and an object is an instance of a class.


Java Classes/Objects
Java is an object-oriented programming language.

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.

Abstraction can be achieved with either abstract classes or interfaces

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

Get and Set

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

3.Java Inheritance (Subclass and Superclass)


In Java, it is possible to inherit attributes and methods from one class to another. We group the
"inheritance concept" into two categories:

●​ subclass (child) - the class that inherits from another class


●​ superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.


4.Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes that are related
to each other by inheritance.

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.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class
To create a class, use the keyword class:

Main.java

Create a class named "Main" with a variable x:

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:

Using Multiple Classes


You can also create an object of a class and access it in another class. This is often
used for better organization of classes (one class has all the attributes and methods,
while the other class holds the main() method (code to be executed)).

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

Java Class Methods


You learned from the Java Methods chapter that methods are declared within a class,
and that they are used to perform certain actions:
Static vs. Public
You will often see Java programs that have either static or public attributes and
methods.

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

1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

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.

We divide modifiers into two groups:

●​ Access Modifiers - controls the access level


●​ Non-Access Modifiers - do not control access level, but provides other functionality
Introduction to Java Swing
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract
Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new
components, expanded components features, and excellent event handling with
drag-and-drop support.

●​ Swing is a Set of API (API- Set of Classes and Interfaces)


●​ Swing is Provided to Design Graphical User Interfaces
●​ Swing is an Extension library to the AWT (Abstract Window Toolkit)
●​ Includes New and improved Components that have been enhancing the looks
and Functionality of GUIs’
●​ Swing can be used to build (Develop) The Standalone swing GUI Apps as
Servlets and Applets
●​ It Employs model/view design architecture.
●​ Swing is more portable and more flexible than AWT, the Swing is built on top of
the AWT.
●​ Swing is Entirely written in Java.
●​ Java Swing Components are Platform-independent, and The Swing Components
are lightweight.

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:

●​ Cut and paste: Clipboard support.


●​ Accessibility features: Aimed at developing GUIs for users with disabilities.
●​ The Desktop Colors Features were first introduced in Java 1.1
●​ Java 2D: it has Improved colors, images, and text support.

Features Of Swing Class


●​ Pluggable look and feel.
●​ Uses MVC architecture.
●​ Lightweight Components
●​ Platform Independent
●​ Advanced features such as JTable, JTabbedPane, JScollPane, etc.
●​ Java is a platform-independent language and runs on any client machine, the
GUI look and feel, owned and delivered by a platform-specific O/S, simply does
not affect an application’s GUI constructed using Swing components.
●​ Lightweight Components: Starting with the JDK 1.1, its AWT-supported
lightweight component development. For a component to qualify as lightweight, it
must not depend on any non-Java [O/s based) system classes. Swing
components have their own view supported by Java’s look and feel classes.
●​ Pluggable Look and Feel: This feature enable the user to switch the look and
feel of Swing components without restarting an application. The Swing library
supports components’ look and feels that remain the same across all platforms
wherever the program runs. The Swing library provides an API that gives real
flexibility in determining the look and feel of the GUI of an application
●​ Highly customizable – Swing controls can be customized in a very easy way as
visual appearance is independent of internal representation.
●​ Rich controls– Swing provides a rich set of advanced controls like Tree
TabbedPane, slider, colorpicker, and table controls.
Example of Java Swing Programs
Example 1: Develop a program using label (swing) to display the message “East Africa
University WEB Site”
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.
CONNECTING A JAVA SYSTEM TO MYSQL(JDBC CONNECTOR)

In older versions of Java:

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

1.​ Download the "latest" MySQL JDBC driver from http://dev.mysql.com/downloads


⇒ "Connector/J" ⇒ Connector/J 8.03.{xx}, where {xx} is the latest update
number ⇒ In "Select Operating System", choose "Platform Independent" ⇒ ZIP
Archive (e.g., "mysql-connector-j-8.3.{xx}.zip" ⇒ "No thanks, just start
my download".
2.​ UNZIP (right-click and extract all) the download file into your project directory
"C:\myWebProject".
3.​ Open the unzipped folder. Look for the JAR file
"mysql-connector-j-8.3.{xx}.jar".​
The Absolute Full-path Filename for this JAR file is
"C:\myWebProject\mysql-connector-j-3.0.{xx}\mysql-connector
-j-8.3.{xx}.jar". Take note of this super-long filename that you will need
later. COPY and SAVE in a scratch pad so that you can retrieve later.
In Java Version 22:

We add the mysql connector by adding it as a dependency inside our project.

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,

Add the dependency for mysql connector java:


NOTE BETTER: AFTER ADDING THE DEPENDENCY DO A CTRL+S TO SAVE THE
FILE

In the project structure ,you will open the File Dependencies and confirm that the
dependencies have been added.

Then you are good to go!.

STEP 2: Setup Database

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

Introduction to JDBC Programming by Examples


A JDBC program comprises the following 5 steps:

●​ STEP 1: Connect to the database via a Connection object.


●​ STEP 2: Allocate a Statement object, under the Connection created
earlier, for holding a SQL command.
●​ STEP 3: Write a SQL query and execute the query via the
Statement.executeQuery()|executeUpdate().
●​ STEP 4: Process the query result.
●​ STEP 5: Close the Statement and Connection to free up the
resources.
Example 1: SQL SELECT

Try out the following JDBC program, which issues an SQL SELECT to
MySQL from a Java Program.

Dissecting the 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

You might also like