Java Programming Basics
Java Programming Basics
1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)
Author
Liang, Y. Daniel
3
How Popular is the Java Programming Language, Source:
4
https://www.tiobe.com/tiobe-index/
Source: https://pypl.github.io/PYPL.html 5
What is Java?
6
The Inventor of Java
7
Why Java was created
8
Java and other Languages at the Time
▪ Usually, Code in other languages is first translated by a compiler into instructions for
a specific type of computer.
▪ The Java compiler instead turns code into something called Bytecode.
▪ The Bytecode is then interpreted by software called the Java Runtime Environment
(JRE), or the Java virtual machine (JVM).
▪ The JRE acts as a virtual computer that interprets Bytecode and translates it for the host
computer.
▪ Because of this, Java code can be written the same way for many platforms.
9
How Java got its name
10
What are the uses of Java?
12
Advantages of Java (1 of 2)
▪ Simple
▪ Java is straightforward to use, write, compile, debug, and learn than alternative
programming languages.
▪ Java is less complicated than C++;
▪ Java uses automatic memory allocation and garbage collection.
▪ Memory allocation
▪ In Java, memory is divided into two parts one is heap and another is stack.
▪ When a variable is declared, the JVM gives memory from either stack or heap space.
▪ It helps to keep the information and restore it easily.
13
Advantages of Java (2 of 2)
▪ Multithreaded
▪ It has the potential for a program to perform many tasks at the
same time.
▪ Useful in many gaming applications
▪ Platform-Independent
▪ Java code runs on any machine that doesn’t need any special
software to be installed, but the JVM needs to be present on the
machine.
▪ Write Once Run Anywhere (WORA) 14
Write Once Run Anywhere
15
Let’s now write our first Java program
16
Hands-on
▪ You can follow the first link that comes out as the result of
the following Google search: “intellij idea download”
17
HelloWorld.java
▪ Create a new project by going through File -> New -> Project
▪ or simply create a new project based on the prompt for a new
installation
▪ Select Java amongst the options that contain Java, JavaFX,
Android, …
▪ Check “Create project from template”
▪ Type in the name of the project, e.g. HelloWorldApp, finish/enter.
18
My First Java Program
(Main.java within HelloWorldApp)
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;
19
Running a Java Program on IntelliJ IDEA
20
The Basic Anatomy of a Java Program
▪ Class Definition
▪ Main Method
▪ Variables
▪ Java Statements
21
The Basic Anatomy of a Java Program
▪ Class Definition
▪ Java programs will always start with a class definition.
▪ Begin with the word "class" followed by the name of the program.
▪ Use curly braces to start and end the class definition.
22
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;
23
The Basic Anatomy of a Java Program
▪ Main Method
▪ In java there are many different kinds of classes.
▪ A class with a main method is a program.
▪ The main method is where program execution starts and stops.
▪ Although, the main method can call other classes, objects, methods or
parts of the java language
▪ This is the general structure of a main method in java.
24
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;
25
The Basic Anatomy of a Java Program
▪ Java Statements
▪ A statement represents an action to be carried out.
▪ Statements in java are similar to sentences in English
▪ Statements in java are terminated using a semicolon
▪ The same way that we end sentences in English using a period
26
/* This is a single line comment for a Hello World
program. It prints “Hello World” to the console
*/
package com.company;
27
Hands-on (2)
28
Hands-on (3)
29
Data Types and Control
Structures in Java
1
Data Types
4
Java Primitive Data types 5
Tokens
7
Identifier rules contd.
9
Operators
10
Arithmetic Operators 11
Precedence of Arithmetic Operators 12
Equality and Relational Operators 13
Expressions
▪ The data type of the value returned by an expression depends on the elements used
in the expression.
▪ The expression value = 0 returns an int because the assignment operator returns a value of the
same data type as its left-hand operand;
▪ in this case, value is an int.
▪ An expression can return other types of values as well, such as boolean or String.
▪ Java programming language allows for the construction of compound expressions
from various smaller expressions as long as the data type required by one part of the
expression matches the data type of the other.
15
Expression examples
▪ 3 * 4 * 5
▪ In this example, the order of evaluation of the expression is not important
because the result of multiplication is independent of order;
▪ the outcome is always the same, no matter the order the multiplications are
applied. However, this does not hold true for all expressions.
▪ a + b / 20
▪ the following expression is ambiguous and gives different results, depending on
whether the addition or the division operation executes first:
16
Expression Examples
▪ (a + b) / 20 // unambiguous, recommended
▪ If the order for the operations to be performed is not explicitly indicated, the order is
determined by the precedence assigned to the operators in use within the expression.
▪ Operators that have a higher precedence get evaluated first. For example, the division
operator has a higher precedence than does the addition operator.
▪ a + (b / 20) // unambiguous, recommended
▪ When writing compound expressions, it is better to be explicit and indicate with
parentheses which operators should be evaluated first.
▪ This practice makes codes easier to read and maintain.
17
Receiving Inputs with the Scanner class
18
import java.util.Scanner;
19
Converting Textual data to numeric data
20
import java.util.Scanner;
23
Classwork 3
▪ Write a program that reads in two numbers: an account
balance and an annual interest rate expressed as a
percentage.
▪ Your program should then display the new balance after a year.
There are no deposits or withdrawals—just the interest payment.
24
Control Statements
Control Statement
▪ Control statements are used to control the flow of execution of
the program.
▪ There are different types of control statements:
▪ Decision Making statements
▪ if-then, if-then-else and switch
▪ Looping statements
▪ while, do-while and for
▪ Branching statements
▪ break, continue and return
If Statement
▪ If n%2 evaluates to 0
then the "if" block is
executed.
▪ Here it evaluates to 0 so
the if block is executed.
▪ Hence "This is even
number" is printed on the
screen.
If-else Statement
31
Classwork 4
38
while, do…while, and for loop
▪ To print a
statement 100
times.
Explanation
▪ To print Welcome to
Java! a hundred
times:
Classwork 7
53
Classwork 9
56
Methods &
Exception Handling
in Java
What is a Method?
▪ The Method header specifies the modifier, return value type, method
name and its parameters.
▪ The return value type is the data type the methods would return. Such
methods are called value-returning methods.
▪ Not all methods return values. For a method that doesn’t return any value,
the keyword void is used in place of a return value type
What is a Method? (Cont’d)
▪ The variables in the header are parameters that would receive values
when the method is invoked or called. The value received is also called
an argument.
▪ The method name and parameters consist the method signature.
▪ A method may or may not have a parameter, parameters are optional.
E.g. Math.random()
▪ The method body contains the collection of statements that implement
the method
Types of Methods
▪ ClassNotFoundException
▪ Attempt to use a class that does not exist.
▪ IOException
▪ Related to input/output operations, such as invalid input, reading past the end of a file, and
opening a non-existent file.
▪ Runtime exceptions
▪ Represented in the RuntimeException class, which describes programming errors, such as
bad casting, accessing an out-of-bounds array, and numeric errors.
Definition of some Exception Types (2)
▪ ArithmeticException
▪ Dividing an integer by zero. Note that floating-point arithmetic does not throw
exceptions
▪ NullPointerException
▪ Attempt to access an object through a null reference variable.
▪ IndexOutOfBoundsException
▪ Index to an array is out of range.
▪ IllegalArgumentException
▪ A method is passed an argument that is illegal or inappropriate.
Exception Handling
try {
double result = number1 / number2;
System.out.println(number1 + " divided by " + number2 + " is equal to: " + result);
}
catch (ArithmeticException ex) {
System.out.println("Exception:" + "An Integer cannot be divided by zero");
System.out.println("Execution continues...");
}
}
If number2 is 0, the method throws an exception and the
catch block is used to handle exception with the
appropriate message.
▪ In this case, it is safe to use the general exception class Exception rather
than a specific type in the catch block.
▪ For example
▪ catch (Exception ex) instead of catch (ArithmeticException ex)
Exercises (1)
▪ (Display matrix of 0s and 1s) Write a method that displays an n-by-n matrix using
the following header:
▪ public static void printMatrix(int n)
▪ Each element is 0 or 1, which is generated randomly. Write a test program that
prompts the user to enter n and displays an n-by-n matrix. Here is a sample run:
Exercises (3)
▪ Write a test program that prompts the user to enter a string followed by a
character and displays the number of occurrences of the character in the
string.
Exercises (4)
1
Java Method overloading
2
Java Method overloading – Instead of
▪ static int plusMethodInt(int x, int y) {
▪ return x + y;
▪ }
▪ static double plusMethodDouble(double x, double y) {
▪ return x + y;
▪ }
▪ public static void main(String[] args) {
▪ int myNum1 = plusMethodInt(8, 5);
▪ double myNum2 = plusMethodDouble(4.3, 6.26);
▪ System.out.println("int: " + myNum1);
▪ System.out.println("double: " + myNum2); } 3
Java Method overloading – Better to
▪ static int plusMethod(int x, int y) {
▪ return x + y;
▪ }
▪ static double plusMethod(double x, double y) {
▪ return x + y;
▪ }
▪ public static void main(String[] args) {
▪ int myNum1 = plusMethod(8, 5);
▪ double myNum2 = plusMethod(4.3, 6.26);
▪ System.out.println("int: " + myNum1);
▪ System.out.println("double: " + myNum2); } 4
Java Method overloading
5
Method overloading by changing data type
of arguments
▪ class Calculate
▪ {
▪ void sum (int a, int b)
▪ {
▪ System.out.println("sum is"+(a+b)) ;
▪ }
▪ void sum (float a, float b)
▪ {
▪ System.out.println("sum is"+(a+b));
▪ }
▪ Public static void main (String[] args)
▪ {
▪ Calculate cal = new Calculate();
▪ cal.sum (8,5); //sum(int a, int b) is method is called.
▪ cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
▪ }
▪ }
6
Method overloading by changing number
of arguments
▪ class Demo
▪ {
▪ void multiply(int l, int b)
▪ {
▪ System.out.println("Result is"+(l*b)) ;
▪ }
▪ void multiply(int l, int b,int h)
▪ {
▪ System.out.println("Result is"+(l*b*h));
▪ }
▪ public static void main(String[] args)
▪ {
▪ Demo ar = new Demo();
▪ ar.multiply(8,5); //multiply(int l, int b) is method is called
▪ ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
▪ }
▪ }
7
Method overloading by changing sequence
of arguments
▪ class Demo{
▪ class MethodDemo8{
▪ public static void main (String[] args) {
▪ Demo obj = new Demo();
▪ obj.get("Cherry", 1);
▪ obj.get("Jhon", 2);
▪ }
▪ }
8
Classwork 1
▪ return (x + y + z); ▪ }
▪ }
▪ }
14
Assignment
16
▪ // Java Program to Illustrate Method Overloading ▪ // Class 2
▪ // Class 1 ▪ {
▪ // Helper class
▪ class Product { ▪ // Creating object of above class inside main()
▪ // method
▪ int prod = a * b;
▪ return prod; ▪ // Printing Product of 2 numbers
▪ } ▪ System.out.println(
▪ "Product of the two integer value :" + prod1);
▪ // Method 2
▪ // Multiplying three integer values ▪ // Calling method to multiply 3 numbers
▪ {
▪ int prod = a * b * c; ▪ // Printing product of 3 numbers
▪ } ▪ }
▪ }
17
▪ // Multiplying three double values.
▪ // Java Program to Illustrate Method Overloading ▪ public double Prod(double a, double b, double c)
▪ // Class 1
▪ class GFG {
▪ // Helper class
▪ public static void main(String[] args)
▪ class Product { ▪ {
▪ Product obj = new Product();
▪ // Multiplying three integer values
▪ public int Prod(int a, int b, int c) ▪ int prod1 = obj.Prod(1, 2, 3);
1
Java methods
3
Example
5
How to call a method
6
Example on how to call a method
▪ public class Main {
▪ static void myMethod() {
▪ System.out.println(“Ijust got executed”)
▪ }
9
Java method parameters - Example
▪ public class Main {
▪ static void myMethod(String firstName) {
▪ System.out.println(firstName + “Oyedepo”)
▪ }
11
Multiple parameters - example
▪ public class Main {
▪ static void myMethod(String firstName, int age) {
▪ System.out.println(firstName + “Oyedepo” + “is” + age + “years old”)
▪ }
13
Return value - example
▪ public class Main {
▪ static int myMethod(int age) {
▪ return age + 5
▪ }
1
Java Method overloading
▪ class Calculate ▪ }
▪ { ▪ Public static void main (String[] args)
▪ void sum (int a, int b) ▪ {
▪ { ▪ Calculate cal = new Calculate();
▪ System.out.println("sum is"+(a+b)) ; ▪ cal.sum (8,5); //sum(int a, int b) is
method is called.
▪ } ▪ cal.sum (4.6f, 3.8f); //sum(float a, float b) is
▪ void sum (float a, float b) called.
▪ { ▪ }
▪ System.out.println("sum is"+(a+b)); ▪ }
5
Method overloading by changing number
of arguments
▪ class Demo
▪ System.out.println("Result is"+(l*b*h));
▪ {
▪ }
▪ void multiply(int l, int b) ▪ public static void main(String[] args)
▪ { ▪ {
▪ System.out.println("Result is"+(l*b)) ; ▪ Demo ar = new Demo();
▪ } ▪ ar.multiply(8,5); //multiply(int l, int b) is method is
called
▪ void multiply(int l, int b,int h)
▪ ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
▪ {
▪ }
▪ System.out.println("Result ▪ }
is"+(l*b*h));
6
Method overloading by changing sequence
of arguments
▪ System.out.println("Company Name :"+
▪ class Demo{ name);
▪ }
▪ public void get(String name, int id) ▪ }
▪ {
▪ System.out.println("Company Name :"+ name); ▪ class MethodDemo8{
▪ System.out.println("Company Id :"+ id);
▪ public static void main (String[] args) {
▪ }
▪ Demo obj = new Demo();
▪ public void get(int id, String name) ▪ obj.get("Cherry", 1);
▪ { ▪ obj.get("Jhon", 2);
▪ System.out.println("Company Id :"+ id); ▪ }
▪ }
7
Classwork
1) Write a java class textMax that overloads a method max with int
and double types to return the largest of any three integer
numbers or any 3 floating point numbers.
2) Write a java class Sum. It has a method sum to return the sum
of two integers. Then call the method. Overload the sum method
to return the sum of 3 integers when called. Overload the sum
method to return the sum of 2 floating point numbers when
called
Assignment 1
▪ // Overloaded sum(). This sum takes two double
▪ // Java program to demonstrate working of method ▪ // parameters
▪ // overloading in Java ▪ public double sum(double x, double y)
▪ {
▪ public class Sum { ▪ return (x + y);
▪ }
▪ return (x + y + z); ▪ }
▪ }
▪ }
12
Array and Strings
1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)
Author
Liang, Y. Daniel
▪ Arrays
▪ One dimensional arrays
▪ Multi-dimensional arrays
▪ Strings processing
▪ ArrayLists
Arrays
▪ You can also place the brackets after the array name;
//this form is discouraged
float sampleArrayOfFloats[];
▪ However, it is not advisable due to the fact that brackets
identify the array type and should appear with the type
designation.
Creating and initializing an array
Example 2 - Code 16
Classwork 1
//Alternatively
int[][] sample = {{1, 3, 4, 5, 6}, {4, 9, 0, 2, 11}};
System.out.println("Your array elements include: ");
for(int i = 0; i < 2; i++){ //2 rows in the 2D array
for(int j = 0; j < 5; j++) { //5 columns in the 2D array
System.out.print(sample[i][j] + " ");
}
System.out.println();
}
21
Copying Arrays
Example 5
Concatenating Strings
▪ To get more than one consecutive characters from a string, you can use
the substring method.
▪ The following codes gets from “Testing the usefulness of Java!”, the
substring that extends from index 12 up to index 22, which is the word
“usefulness”.
▪ Given String theme = “My future is bright”; what will be the value
returned from the following:
▪ theme.substring(10, 15);
▪ theme.indexOf(“o”);
▪ theme.lastIndexOf(“e”, 6);
▪ theme.contains(‘!’);
Classwork 4
▪ (Student major and status) Write a program that prompts the user to enter
two characters and displays the major and status represented in the
characters.
▪ The first character indicates the major and the second is number
character 1, 2, 3, 4, which indicates whether a student is a freshman,
sophomore, junior, or senior.
40
Classwork 6 cont’d
41
More Exercises – Main Text
▪ Exercise 7.8
▪ Exercise 7.10
▪ Exercise 8.10
▪ Exercise 8.11
▪ Exercise 8.17
42
Objects & Classes
1
Main Text for this Course
Title
Introduction To Java Programming,
Comprehensive Version (2015, 7th Edition)
Author
Liang, Y. Daniel
5
Class as a concept in OOP
6
A simple example – Circle class
7
Steps
Inside Circle.java 9
Creating Objects of a class
When the area of both objects are printed, the same value is
outputted since c1 and c2 both reference the same memory location 15
The ArrayList Class
(Automatic shrinking and expansion of arrays)
16
More on the ArrayList class
17
Example 1
System.out.println();
System.out.println(bucket.isEmpty());
System.out.println(bucket.contains(18));
}
19
Explanation of Example 1 code
▪ The line:
▪ ArrayList<Integer> bucket = new ArrayList<>();
▪ simply creates a new ArrayList object (bucket) whose elements are
Integers. Notice that “Integer” is used rather than “int”
▪ The expression bucket.add(randNum); adds a new member
(the value of the variable randNum) to the arraylist
20
Explanation of Example 1 code (Cont’d)
▪ Our very first example, the Circle class has a data member
called radius.
▪ While using the object of a class, a user may inadvertently
change the value of radius.
▪ One way to protect the radius instance variable from such is
to declare it private.
22
Protecting Data Members (2)
▪ Our first version of the Circle class, one could directly refer to
the member variable radius by doing the following:
▪ c1.radius() or
▪ c2.radius()
▪ This is an undesirable property as the essence of creating a
class in the first place is to facilitate Data Encapsulation
23
public class Circle {
private double radius; //now a private member
public Circle(){ radius = 1; }
public Circle(double newRadius){ radius = newRadius; }
double getArea() {
return radius * radius * Math.PI;
}
double getPerimeter() {
return 2 * Math.PI * radius;
}
void setRadius(double newRadius) { radius = newRadius; }
}
24
Array of Objects
▪ Mind you, the expression above just creates five spaces large
enough to store five Circle objects, it has not instantiated them.
26
Example 2
29
The This Reference
32
Class Activity 2 (Cont’d)
2. Private member function that returns the win percentage of the team.
This can be calculated by the following formula:
𝑤𝑖𝑛_𝑟𝑒𝑐𝑜𝑟𝑑
𝑤𝑖𝑛_𝑝𝑐𝑡 =
𝑤𝑖𝑛_𝑟𝑒𝑐𝑜𝑟𝑑 + 𝑙𝑜𝑠𝑠_𝑟𝑒𝑐𝑜𝑟𝑑
34
Class Activity 2 (Cont’d)
3. A method that prints a message about the best player (it does not
return any value) based on the following rules, where player_name
represents the name of the team’s best player:
a) Print “Trade player_name” if the team did not make the playoffs and the
win percentage is less than 0.5
b) Print “Keep player_name” if the team made the playoffs and had at least a
win percentage of 0.60
35
Class Activity 2 (Cont’d)
c) Print “Find a co-star for player_name” if the team made the playoffs but
had a win percentage of at least 0.45 but below 0.5.
d) Otherwise print “Let’s run with player_name next season”.
▪ Do the following in the main program:
▪ Instantiate an object of the NBATeam class with the non-default
constructor
▪ Print an information about the best player
36
Extra Study
▪ Static Variables
▪ Study more examples
▪ Solve more exercises
▪ Inheritance and Polymorphism
37