JAVA Chapter3 Lecture Notes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

CSC 2302: COMPUTER PROGRAMMING II

CHAPTER 3: PROGRAMMING WITH JAVA


COURSE TUTOR:
BASHIR ABDU MUZAKKARI, Ph.D.

DEPARTMENT OF COMPUTER SCIENCE


YUSUF MAITAMA SULE UNIVERSITY, KANO
DISCLAIMER

This document does not claim any originality and cannot be used as
substitute for prescribed textbooks. The information presented here is
purely a collection by the course lecturer for teaching assignments.
Various textbooks as well as freely available materials from the internet
were consulted for preparing this document. The ownership of the
information lies with the respective authors or institutions.
Java
Java programming language was
originally developed by Sun
Microsystems which was initiated
by James Gosling and released in
1995 as core component of Sun
Microsystems' Java platform (Java
1.0 [J2SE]).

Java program can be defined as a


collection of objects that
communicates via invoking each
other’s methods.
Java Development Kit (JDK)
A JDK is simply an environment that
gives us everything that we need to
develop java applications.

The JDK comprises of the:

Java Runtime Environment (JRE)


which contains all the libraries and Java Virtual Machine JVM
classes of java. Java Runtime Environment JRE Libraries & Classes

Java Virtual Machine (JVM) which is Java Development Environment JDK Development Tools

responsible for executing the java


programs.
Java Syntax

public class Main {


public static void main(String[] args) {
//Code goes here
}
}
Java Syntax
public: Java public keyword is an access modifier. It
Class is used to indicate that an item is accessible
anywhere. It has the widest scope among all other
modifiers.
class: Java class keyword is used to declare a
public class Java { class.
Java: Is the name of the class. Always starts
with uppercase

}
Every line of code that runs in Java must be inside a class. In the
above example, we named the class as Java. A class should always
start with an uppercase first letter.

NB: Java is a case-sensitive language. Example, "MyJava" and


"myjava" has different meaning.
Java Syntax
The Main Method
The main() method is mandatory in every Java program, it is the entry
point in java program where the execution begins. Without the main()
method, JVM will not execute the program. Access Specifier: a public keyword is used
before the main() method so that JVM can
identify the execution point of the
program. If we use private, protected, and
default before the main() method, it will
not be visible to JVM.
public static void main(String[] args) static: Java static keyword is used to
indicate that a variable or method is a
main(): It is a default signature which is predefined class method. The static keyword in Java is
in the JVM. It is called by JVM to execute a program used mainly for memory management.
line by line and end the execution after completion void: Java void keyword is used to specify
of this method. that a method does not have a return
value.
String args[]: The main() method also accepts some data from the user.
It accepts a group of strings, which is called a string array. It is used to
hold the command line arguments in the form of string values.
Java Syntax
The Print Method
System: It is a final class defined in the
java.lang package.
System.out.println("Hello World"); out: This is an instance of PrintStream
type, which is a public and static member
field of the System class.

println(): As all instances of PrintStream


class have a public method println(),
hence we can invoke the same on out as
Java System.out.println() is used to print an well. This is an upgraded version of print().
It prints any argument passed to it and
argument that is passed to it. The statement can adds a new line to the output.

be broken into 3 parts which can be understood


separately as:
Java Single-line 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
// This is a comment
alternative code.
System.out.println(“Test");
Single-line comments start with two
System.out.println(“Test"); // A comment too
forward slashes (//). Any text
between // and the end of the line is
ignored by Java (will not be
executed).

These examples uses a single-line


comment before a line of code:
Java Multi-line Comments

Multi-line comments start with /*


and ends with */.
/* The code below will print the
Any text between /* and */ will be words Amazing to the screen, and
ignored by Java. it is amazing */
System.out.println(“Amazing");
This example uses a multi-line
comment (a comment block) to
explain the code:
Java Keywords
Assignment II

List and explain all the available Java Keywords.

Typeface: Times New Roman 12 points.

Include a cover page with your Name, Registration Number and Programme of
Study.

To be Submitted during the next Class.

This is an individual assignment, plagiarism and similar work will be marked


ZERO.
Java Variables

Variables are memory locations that stores and access data while a program
is in execution.

Each variable in java has a specific data type, which determines the size,
layout and range of values that can be stored within that memory location.
Java Variables
Variable Declaration
To declare a variable we follow this syntax: data_type variable_name = value;

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
Java Variables
Java Variables

Local Variable
A variable declared inside the body of the method is called local variable. You
can use this variable only within that method.
A local variable cannot be defined with "static" keyword.
Java Variables
Instance Variable
A variable declared inside the class but outside the body of the method, is
called instance variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not
shared among instances.
Java Variables
Static Variable
Static variables are also known as class variable because they are associated
with the class and common for all the instances of the class.

For example, if we create three objects of a class and access this static variable,
it would be common for all, the changes made to the variable using one of the
object would reflect when you access it through other objects.
Java Variables
Example

public class Variables {


static int c = 30 //Static variable
int a = 10; //Instance variable
public static void main(String [] args) {
int b = 20; //Local variable
System.out.println(c); //prints 30
System.out.println(b); //prints 20;
Variables obj = new Variables(); //Object creation
System.out.println(obj.a); //prints a
}
}
Data Types
A variable is assigned with a data type. There are two types of data types in
Java: primitive and non-primitive.
Type Casting
In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.

The automatic conversion is done by the compiler and manual conversion


performed by the programmer.
Narrowing Casting (Manually)

Widening Casting (Automatically)


Type Casting
Examples
Narrowing Casting (Manually) Widening Casting (Automatically)
 Narrowing casting must be done manually  Widening casting is done automatically when
by placing the type in parentheses in front passing a smaller size type to a larger size
of the value. type.

public class Main { public class Main {


public static void main(String[] args) { public static void main(String[] args) {
double myDouble = 2.58; int myInt = 4;
int myInt = (int) myDouble; // Manual casting: double myDouble = myInt; // Automatic casting:
double to int int to double

System.out.println(myDouble); // Outputs 2.58 System.out.println(myInt); // Outputs 4


System.out.println(myInt); // Outputs 2 System.out.println(myDouble); // Outputs 4.0
} }
} }
Java Operators
An operator is a character that represents an action, for example + is an
arithmetic operator that represents addition.

 Arithmetic operators (+, -, *, /, %)


 Assignment operators (=, +=, -=, *=, /=, %=, &=, |=, =, >>=, <<=)

 Comparison operators (==, !=, >, <, >=, <=)

 Logical operators (&&, ||, !)

 Unary operators (++, --)

 Bitwise operators (&, |, ^, ~, <<, >>)


Java Operators
Example of Arithmetic Operators
public class Arithmetic {
public static void main(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Java Operators
Example of Assignment Operators
public class Assignment {
public static void main(String[] args) {

// create variables
int a = 4;
int var;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}
Java Operators
Example of Comparison Operators
public class Comparison {
public static void main(String[] args) {

int a = 7, b = 11; // create variables

System.out.println("a is " + a + " and b is " + b); // value of a and b

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}
Java Operators
Example of Logical Operators
public class Logical {
public static void main(String[] args) {

// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false

// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Operators
Example of Unary Operators
public class Unary {
public static void main(String[] args) {

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);

System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
Java Operators
Example of Bitwise Operators
public class Bitwise {
public static void main(String[] args) {

// declare variables
int x = 9, y = 8;
// bitwise and
// 1001 & 1000 = 1000 = 8
System.out.println("x & y = " + (x & y));

// bitwise XOR
// 1001 ^ 1000 = 0001 = 1
System.out.println("x ^ y = " + (x ^ y));

// bitwise inclusive OR
// 1001 | 1000 = 1001 = 9
System.out.println("x | y = " + (x | y));

// bitwise compliment
// ~0010= 1101 = -3
System.out.println("~x = " + (~x));
}
}
Java Conditions and If Statements
Java supports the usual logical conditions from mathematics such as:
 Less than: <
 Less than or equal to: <=
 Greater than: >
 Greater than or equal to: >=
 Equal to: ==
 Not Equal to: !=

Java supports the following conditional statements


 Use if to specify a block of code to be executed, if a specified condition is true
 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed
Java If Statement
Java uses the if statement to specify a block of Java code to be executed if
a given condition is true.

if (condition) {
// block of code to be executed if the condition is true
}

if (20 > 18) {


System.out.println("20 is greater than 18");
}
Java If Statement
Java else Statement
Java uses the else statement to specify a block of code to be executed if
the given condition is false.

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
int time = 20;
if (time < 15) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Java else Statement
Java Ternary Operator
int time = 20;
Java has a short-hand if else, if (time < 15) {
which is known as the ternary System.out.println("Good day.");
operator, it consists of three } else {
System.out.println("Good evening.");
operands.
}
// Outputs "Good evening."
It can be used to replace
multiple lines of code with a int time = 20;
single line. It is often used to String result = (time < 18) ? "Good day." : "Good
evening.";
replace simple if else System.out.println(result);
statements
variable = (condition) ? expressionTrue : expressionFalse;
Java else if Statement
Java uses the else statement to specify a block of code to be executed if
the given condition is false.

if (condition1) {
// block of code to be executed if the condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false
and condition2 is true
}
else{
// block of code to be executed if the condition1 and
condition2 are false
}
Java else if Statement

int time = 22;


if (time < 12) {
System.out.println("Good morning.");
} else if (time < 15) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Java else if Statement
Java Loop Control Statements
Loops can execute a block of code as long as a specified condition is
reached.

Loops are handy because they save time, reduce errors, they enhance the
readability of the code.

There are 3 types of loops in Java:


 For Loop
 While Loop
 Do While Loop
Java For Loop
For loop is also known as count-controlled loop.

We use for loop when we know exactly how many times we want to loop
through a block of code.

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

Statement 1 is executed once before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the execution of the code block.
Java For Loop

for (int i = 0; i < 10; i++) {


System.out.println(i);
}

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 10). If
the condition is true, the loop will start over again, if it is false, the loop will end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Java For Loop

for (int i = 0; i <= 10; i = i + 2) {


System.out.println(i);
}
Java While Loop
The while loop, also known as  In the given example, the code in the
condition-controlled loop, loops loop will run, over and over again, as
through a block of code as long as long as the variable (i) is less than 10.
a specified condition is true.
int i = 0;
while (i < 5) {
while (condition) { System.out.println(i);
i++;
// code block to be executed
}
}
Java do While Loop
The do/while loop is a variant of  In the given example, the loop will
the while loop. This loop will always be executed at least once,
execute the code block once, even if the condition is false, because
before checking if the condition is the code block is executed before the
true, then it will repeat the loop condition is tested
as long as the condition is true.
int i = 0;
do {
do { System.out.println(i);
// code block to be executed i++;
} }
while (condition); while (i < 5);
Java While vs do While Loops
Java Methods
A 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.

We use methods to reuse code (define the code once, and use it many
times).

When we call the System.out.println() method, it executes several


statements in order to display a message on the console.
Creating Methods
A method must be declared within a class.

It is defined with the name of the method, followed by parentheses ().

modifier returnType nameOfMethod (Parameter List)


{
// method body
}

Java provides some pre-defined methods, such as System.out.println(),


but you can also create your own methods to perform certain actions.
Creating Methods
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.
Method Calling
To call a method in Java, we write the method's name followed by two
parentheses () and a semicolon ( ; ).

public class Main {


static void myMethod() {
System.out.println(“This is my first Method");
}

public static void main(String[] args) {


myMethod();
}
}

A method can also be called many times.


Method Calling
Example

public class Main {


static void myMethod() {
System.out.println(“This is my first Method");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}
Java Method Parameters
public class Main {
Information can be passed to static void myMethod(String text) {
methods as parameter. Parameters System.out.println(text + " YUMSUK");
act as variables inside the method. }

public static void main(String[] args) {


Parameters are specified after the myMethod(“Science");
method name, inside the myMethod(“Education");
myMethod(“Humanities");
parentheses. You can add as many myMethod(“SMS");
parameters as you want, just
separate them with a comma. }
}

When a parameter is passed to the method, it is called an argument. So,


from the example above: text is a parameter, while Science, Education,
Humanities and SMS are arguments.
Java Method Parameters

public class Main {


static int myMethod(int x) {
return 10 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(5));
}
}
// Outputs 15 (10 + 5)
Java Method Parameters

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(10, 5));
}
}
// Outputs 15 (10 + 5)
Java Method Parameters

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(10,5);
System.out.println(z);
}
}
// Outputs 15 (10 + 5)
Java Method Parameters
public class Main {

// Create a checkAge() method with an integer variable 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!");

// If age is greater than, or equal to, 18, print "access granted"


} else {
System.out.println("Access granted - You are old enough!");
}

public static void main(String[] args) {


// Call the checkAge method and pass along an age of 20
checkAge(20);
}
}

// Outputs "Access granted - You are old enough!"


Java Method Overloading
static int myMethodInt(int x, int y) {
With method overloading, multiple return x + y;
}
methods can have the same name
with different parameters. static double myMethodDouble(double x, double y) {
return x + y;
}

public static void main(String[] args) {


int myMethod(int x)
int myNum1 = myMethodInt(2, 8);
float myMethod(float x) double myNum2 = myMethodDouble(5.5, 3.8);
double myMethod(double x, double y) System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}

Instead of defining two methods that should do the same thing, it is better to
overload one. In the example above, we overload the myMethod method to work
for both int and double.

You might also like