[go: up one dir, main page]

100% found this document useful (1 vote)
39 views45 pages

Jp1 Mar2023 Lecture Notes

This document provides a course outline for Java Programming 1. It outlines the course name and code, lecturer details, credit value, contact hours, learning outcomes, assessment structure, and references. The course aims to describe programming language concepts, apply Java programming constructs like variables and operators, and demonstrate Java programming knowledge. Assessment includes coursework tests, a midterm, and final exam. References provided are Java programming textbooks. The document also includes a table of contents outlining topics to be covered like data types, control structures, and iteration.

Uploaded by

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

Jp1 Mar2023 Lecture Notes

This document provides a course outline for Java Programming 1. It outlines the course name and code, lecturer details, credit value, contact hours, learning outcomes, assessment structure, and references. The course aims to describe programming language concepts, apply Java programming constructs like variables and operators, and demonstrate Java programming knowledge. Assessment includes coursework tests, a midterm, and final exam. References provided are Java programming textbooks. The document also includes a table of contents outlining topics to be covered like data types, control structures, and iteration.

Uploaded by

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

Diploma in Information Technology

Java Programming 1
(CTD 1201)

1
COURSE OUTLINE

1 Course Name Java Programming 1


2 Course Code CTD 1201
3 Lecturer Name Ms Mangair Karasi Manickam
4 Credit Value 4
5 Contact Hours 4.5 X 14 weeks
6 Learning outcome 1. Describe the concepts of programming language.
2. Apply various types of data, variables, operators,
string manipulation and programming constructs in
Java programming.
3. Demonstrate the knowledge of writing programming
using Java programming language.
7 Assessment Coursework – 60%
Test1: 30%
Test2: 30%
Final Examination – 40%
8 Reference(s) Gaddis, T., (2019), Starting out with Java: from control
structures through objects, 7th Edition, Pearson Addison

Liang, D.Y., (2018), Introduction to JAVA Programming,


11th Edition, Pearson

Acknowledgement

Version no Version date Prepared by / Updated by Teaching Team


1 28 Feb 2023 Ms Mangair Karasi Ms Mangair Karasi Manickam
Manickam
2 1 August 2022 Ms Mangair Karasi Ms Mangair Karasi Manickam
Manickam

No part of this guide can be reproduced without written permission of the college

2
TABLE OF CONTENTS

Chapter 1: Introduction to Programming and Java


1.1 Introduction to Programming Languages 1
1.2 Levels of Programming Languages 1
1.3 Pseudocode and Source Code 2
1.4 The Origin of JAVA 2
1.5 Characteristics of JAVA 3
1.6 Java Language Specification, API, JDK and IDE 4
1.7 The Compiler and the JVM 4
1.8 A Simple Java Program 5
1.9 Anatomy of the Java Program 5
1.10 Programming Errors 6

Chapter 2: Java Fundamentals


2.1 Java Keywords 8
2.2 Primitive Data Types 8
2.3 Characters 9
2.4 Boolean 9
2.5 Variables 10
2.6 Constants 11
2.7 Escape Sequence 13
2.8 Arithmetic Expressions 13
2.9 Boolean Data Type & Operations 15
2.10 Formatting Output 16
2.11 Increment and Decrement Operators 17
2.12 Naming Conventions 18

Chapter 3: Keyboard Input


3.1 Keyboard Input 19

Chapter 4: Java Classes


4.1 String Class 22
4.2 Random Class 25
4.3 Math Class 27

Chapter 5: Date & Decimal Format


5.1 Date Format 31
5.2 Decimal Format 32

Chapter 6: Control Structures


6.1 if statement 34
6.2 switch…case 38

Chapter 7: Iteration/Repetition
7.1 while loop 40
7.2 do-while loop 41
7.3 for loop 42

References 45

3
Chapter 1: Introduction to Programming and Java

1.1 Introduction to Programming Languages

A Programming language is a set of rules that provides a way of telling a computer what
operations to perform. Computers are designed to follow these instructions to perform task or
solve a problem. These instructions are called an algorithm.

Programming languages are written in English, which use words, symbols and rules of
grammar. The grammatical rules are called syntax. Each programming language has a different
set of syntax rules.

1.2 Levels of Programming Languages

Machine Language

All programs are converted into machine language before they can be executed. It consists of
combination of 0’s and 1’s that represent high and low electrical voltage. Machine language
programs are executable, meaning that they can be run directly. Programming in machine
language requires memorization of the binary codes and can be difficult for the human
programmer. For example, to add two numbers, you might have to write an instruction in binary
code, like this:

BINARY : 1101101010011010

Assembly Language

Assembly language was created in the early days of computing as an alternative to machine
languages. It uses a short descriptive word, known as a mnemonic, to represent each of the
machine-language instructions. For example, the mnemonic add typically means to add
numbers and sub means to subtract numbers. For example, to add the numbers 2 and 3 and
get the result:

add 2, 3, result

4
High Level Language

New generation of programming languages known as high-level languages. They are platform
independent, which means that you can write a program in a high level language and run it in
different types of machines. High-level languages are English-like and easy to learn and use.
For example, is a high-level language statement that computes the area of a circle with a radius
of 5:

area = 5 * 5 * 3.14159;

Popular High-Level Programming Languages: C, C++, Java, Visual Basic, Pascal, Fortran and
…....

1.3 Pseudocode and Source Code

Pseudocode is a natural language mixed with some programming code. It uses English words
and has no formal syntactical rules.

Example:
Determine the average grade of a class:

Do while there are more data


Get the next Grade
Add the Grade to the Sum
Increment the Counter
Loop
Compute average = Sum / Counter
Display average

Once your pseudocode ready, you translate them into a high-level language called source
program or source code. Because a computer cannot execute a source program, a source
program must be translated into machine code for execution. The translation can be done using
another programming tool called an interpreter or a compiler.
 An interpreter reads one statement from the source code, translates it to the machine
code or virtual machine code, and then executes it right away
 A compiler translates the entire source code into a machine-code file, and the
machine-code file is then executed

1.4 The Origin of JAVA

Was developed by a team led by James Gosling at Sun Microsystems in year 1991.

Originally called “Oak” but was renamed as JAVA in year 1995. Is based on C and C++. Often
described as Web programming language.

Today, it is used not only for Web programming, but also for developing standalone applications
across platforms on servers, desktops, and mobile devices (Palm PDA).

5
The primary authoring language is for the Web is HTML
(……………………………………………..) . Is a simple language for laying out documents,
linking documents on the Internet, and bringing images, sound, and video alive on the Web.
However, it cannot interact with the user except through simple forms. Web pages in HTML are
essentially static and flat.

Java initially became attractive because Java programs can be run from a Web browser. Java
programs uses modern graphical user interface with buttons, text fields, text areas, radio
buttons, and so on.

1.5 Characteristics of JAVA

1. Java Is Simple
Java is easier than the popular object-oriented language C++, which was dominant
software-development language before Java. The clean syntax makes Java programs
easy to write and read.

2. Java Is Object-Oriented
OOP …………………………………….. is a popular programming approach that is
replacing traditional procedural programming techniques. OOP provides great flexibility,
modularity, clarity, and reusability of the code.

3. Java Is Distributed
Distributed computing involves several computers working together on network. Java is
designed to make distributed computing easy.

4. Java Is Interpreted
You need an interpreter to run Java programs. The programs are compiled into Java
Virtual Machine code called bytecode. Most compilers, translate program in high-level
language to machine code. Java interpreter translates the bytecode into the machine
language of the target machine.

5. Java Is Robust
Robust means reliable. Java puts a lot of emphasis on early checking for possible errors,
because Java compilers can detect many problems that would first show up at execution
time.

6. Java Is Secure
If you download a Java applet (a web program) and run it on your computer, it will not
damage your system because Java implements several security mechanisms to protect
your system.

7. Java Is Architectural-Neutral
Java is an architectural-neutral or platform-independent. Using Java, developers need to
write only one version that can run on every platform (Windows, OS/2, Macintosh, and
various UNIX).
8. Java Is Portable
They can be run on any platforms without being recompiled. Moreover, there are no

6
platform-specific features. It is portable to new hardware and operating system.

9. Java’s Performance
The new JVM is significantly faster. The new JVM uses the technology known as just-in-
compilation.

10. Java Is Multithreaded


Multithreading is program’s capability to perform several task simultaneously. For
example, downloading a video file while playing the video.

11. Java Is Dynamic


Java is designed to adapt to an evolving environment.

1.6 The Java Language Specification, API, JDK and IDE

Java syntax is defined in the Java language specification, and the Java library is defined in the
Java API. The application program interface (API), also known as library, contains predefined
classes and interfaces for developing Java programs.

Java Development Toolkit (JDK) is the software for developing and running Java programs. An
IDE is an integrated development environment for rapidly developing programs. Java
development tool (e.g., NetBeans, Eclipse, and TextPad) software that provides an integrated
development environment (IDE) for developing Java programs quickly. Editing, compiling,
building, debugging, and online help are integrated in one graphical user interface.

1.7 The Compiler and the JVM

The Java programming files which consist of source code, are known as source file. Java
source files end with .java extension.

A compiler is a program that translates source code into an executable form. The Java compiler,
however, translates a Java source file into a file that contains byte code instructions. Byte code
instructions are not machine language, and therefore cannot be directly executed by the CPU.
Instead, they are executed by the Java Virtual Machine. The bytecode is similar to machine
instructions but is architecture neutral and can run on any platform that has a JVM.

The Java Virtual Machine(JVM) is a program that reads Java byte code instructions and
executes them as they read. For this reason, the JVM is often called an interpreter, and Java is
often referred to as an interpreted language.

7
1.8 A Simple Java Program

Example : A Simple Application

Problem:
Write a program that displays the message “Welcome to Java!” on the console.

Solution:
//this application program prints Welcome to Java

Example:
package welcome;
public class Welcome //class name
{
public static void main(String[ ] args)
{
System.out.println("Welcome to Java!");
}
}
Output:
______________________________________________________________________

Review:
Every Java program must have at least one class. In this example, the class name is welcome.
The class contains a method named main.

1.9 Anatomy of the Java Program

1. Comments
Comments help programmers and user to communicate and understand the program.
Comments are not programming statements and are ignored by the compiler.
Comments preceded by two slashes // on a line, called a line comment, or enclosed
between /* and */ one or several lines, called paragraph comment.

2. Reserved Words
Reserved words, keywords, are words that have a specific meaning to the compiler and
cannot be used for other purposes in the program. When the compiler sees the word

8
after the class, it will understand that it is the name of the class. Other reserved words
are public, static, and void.

3. Modifiers
Java uses modifiers that specify the properties of the data, methods, and classes and
how they can be used. Examples of modifiers are public, static, and private,

4. Statements
A statement represents an action that sequence of actions. The statement
System.out.println(“Welcome to Java!”) in the program above is a statement to display
the greeting “Welcome to Java!” Every statement in Java ends with a semicolon(;).

5. Blocks
The braces in the program form a block that groups the components of the program. In
Java, block begins with an opening braces, { and ends with a closing braces, }.

6. Classes
A program is identified by using one or more classes.

7. Methods
System.out is known as the standard output object. println is a method in the object,
which consists of a collection of statements that perform a sequence of operations to
display a message to the standard output device.

8. The main Method


The main method defines where the program begins. It provides the control of program
flow.

Example:
package welcome1;
//Welcome1.java
//printing a line of text with multiple statements
public class Welcome1
{
//main method begins execution of java application
public static void main(String args[])
{
System.out.print("Welcome to ");
System.out.print("\nJava\nPrograming!");// \n to start into a newline

}//end method main

}//end class welcome1


Output:
____________________________________________________________________________
____________________________________________________________________________

1.10 Programming Errors

1. Syntax Errors

9
It occurs during compilation. Syntax errors result from errors in code construction, such
as mistyping a keyword, omitting some necessary punctuation, or using an opening
braces without a corresponding closing braces.

2. Runtime Errors
Runtime errors are errors that cause a program to terminate abnormally. It occurs when
an application impossible to carry out the certain operation. An input error occurs when
the user enters an unexpected input value that the program cannot handle. For instance,
instead of a number, the user enters a string.

3. Logic Errors
It occurs when a program does not perform the way it was intended to.

Debugging

Logic errors are called bugs. The process of finding and correcting errors is called debugging.

10
Chapter 2: Java Fundamentals

2.1 Java Keywords

These words that have a special meaning in the programming language. They may be used for
their intended purpose only. Keywords are also known as reserved words. Keywords are
reserved, and cannot be used for anything other than their designated purpose.

Java Keywords

abstract do implement private throw


boolean double import protected throws
break else instanceof public transient
byte extends int return true
case false interface short try
catch final long static void
char finally native super volatile
class float new switch while
continue for null synchronized this
default if package

2.2 Primitive Data Types

A data type is defined by a set of values and the operators you can perform on them. Each
value stored in memory is associated with a particular data type. The Java language has
several predefined types, called primitive data types.

The following reserved words represent eight different primitive types:

 byte, short, int, long, float, double, boolean, char

Java numerical data types and their precisions

Data Types Storage Minimum Value Maximum Value

byte 8 bits -128 127


byte(s)
short 16 bits -32768 32767
byte(s)
int 32 bits -2147483648 2147483647
byte(s)

11
long 64 bits -9223372036854775808 9223372036854775807
byte(s)
float 32 bits -3.4 * 10-38 3.4 * 1038
byte(s)
double 64 bits -1.7 * 10-308 1.7 * 10308
byte(s)

2.3 Characters

A char value stores a single character from the Unicode character set. A character set is an
ordered list of characters. The Unicode character set uses sixteen bits per character, allowing
for 65,536 unique characters. It is an international character set, containing symbols and
characters from many world languages.

The char Data Type

Character literals are enclosed in single quotation marks (‘A’).

Example:
package letters;
//This program demonstrate the char data type

public class Letters


{
public static void main(String[] args)
{
char letter;

letter = 'A';
System.out.println(letter);
letter = 'B';
System.out.println(letter);
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

2.4 Boolean

12
A boolean value represents a true or false condition. They can also be used to represent any
two states, such as a light bulb being on or off. The reserved words true and false are the only
valid values for a boolean type.

The boolean Data Type

Example:
package truefalse;
//A program for demonstrating boolean variables

public class TrueFalse


{
public static void main(String[] args)
{
boolean bool;
bool = true;
System.out.println(bool);
bool = false;
System.out.println(bool);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

2.5 Variables

Variables are used store data in a program.

The following program shows an example on variables.

Example:
package computearea;
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;

//assign a radius
radius=20;

//compute area
area=radius*radius*3.14159;

//display results
System.out.println("The area for the circle of radius "+radius + " is " +area);

13
/*(+) is called a string concatenation operator. Is used
concatenate strings into a longer string.*/
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Declaring a Variable

In the program, radius and area are variables.


Here is the syntax for declaring a variable:
datatype variableName;

Here are some examples of variable declarations:


int x ; //declare x to be an integer variable;
double radius ; //declare radius to be a double variable;
double interestRate ; //declare interestRate to be a double variable;
char a ; //declare a to be a character variable;

If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2,….. ;

The variables are separated by commas.

Assignment Statements & Expressions

The equal sign (=) is used as the assignment operator. The syntax is as follows:
variable = expression;

An expression represents a computation involving values, variables, and operators that


evaluates to a value. For example:
int x = 1; // assign 1 to a variable x;
a = A; // assign ‘A’ to variable a;
x = y +1; // assign the addition of y and 1 to x;

You can also use a shorthand form to declare and initialize variables of the same type together
as:
int i = 1, j = 2;

2.6 Constants

Constants represent a permanent data that never changes. You can define …. as a constant.
The syntax :
final datatype CONSTANTNAME = VALUE;

You could define ……… as a constant and rewrite the program as follows:

14
Example:
package computearea;
// computeArea.java
public class ComputeArea
{

public static void main(String[] args)


{
//declare a constant
final double PI = 3.14159;

//assign a radius
double radius=20;

//compute area
double area=radius*radius*PI;

//display results
System.out.println("The area for the circle of radius "+radius + " is " +area);

}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

Constant are named in uppercase: PI, not pi or Pi.

There are three benefits of using constants:


 You don’t have to repeatedly type the same value
 The value can be changed in a single location, if necessary
 The program is easy to read

Example:
package eg;
//the program shows that how to read the different type of data types
public class eg
{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";

System.out.println(myInteger);
System.out.println(myString);
}

15
}
Output:
____________________________________________________________________________
____________________________________________________________________________

2.7 Escape Sequences

An escape sequence is a special sequence of characters preceded by a backslash (\)


They indicate some special purpose, such as:

Escape Name Meaning


Sequence
\n Newline Advances the cursor to the next line for
subsequent printing
\t Tab Causes the cursor to skip over to the next tab
stop
\b Backspace Causes the cursor to back up, or move left, one
position
\r Return Causes the cursor to go to the beginning of the
current line, not the next line
\’ Single quote Cause a single quotation mark to be print
\” Double quote Cause a double quotation mark to be print
\\ Backslash Causes a backslash to be printed

Example:
package escsequence;
public class EscSequence {
public static void main(String args[]) {
System.out.println(“He said \”Hello!\” to me”);
System.out.print(“and I said \nHello \nHow are you \t Fine thank you \\”);
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

2.8 Arithmetic Expressions

An expression is a combination of operators and operands. Operands can be literal values,


variables, or other sources of data

Java Operation Expression


Addition +
Subtraction -
Multiplication *
Division /
Remainder %

16
 If the operands of the / operator are both integers, the result is an integer (the fractional
part is truncated)
 If one or more operands to the / operator are floating point values, the result is a floating
point value
 The remainder operator (%) returns the integer remainder after dividing the first operand
by the second

Expression Result
17 / 5 3
17.0 / 5 3.4
17 / 5.0 3.4
9 / 12 0
9.0 / 12.0 0.75
6%2 0
14 % 5 4
-14 % 5 -4

Example:
package modulusdemo;
//Demostrate the % operator
public class ModulusDemo{
public static void main(String args[ ])
{
int iresult,irem;
double dresult,drem;

iresult = 10/3;
irem = 10%3;

dresult = 10.0/3.0;
drem = 10.0 % 3.0;

System.out.println("Result and remainder of 10/3: " +iresult);


System.out.println("Result and remainder of 10.0/3.0: " +dresult);
System.out.println("Result and remainder of 10%3: " +irem);
System.out.println("Result and remainder of 10.0%3.0: " +drem);
System.out.println("Result and remainder of 10/3: " +iresult+ " " +irem);
System.out.println("Result and remainder of 10.0/3.0: " +dresult+ " " +drem);

}
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

17
____________________________________________________________________________
____________________________________________________________________________

Shortcut Operators

Operator Name Example Equivalent


+= Addition assignment i += 8 i=i+8
-= Subtraction assignment f -= 8.0 f = f – 8.0
*= Multiplication assignment i *= 8 i=i*8
/= Division assignment i /= 8 i=i/8
%= Remainder assignment i %= 8 i=i%8

2.9 Boolean Data Type & Operations

Comparison Operators

Operator Name
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Equal to
!= Not equal to

Boolean Operators

Operator Name
! Not
&& And
|| Or
^ Exclusive or

Example:
package comparison;
public class Comparison {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output:
____________________________________________________________________________

18
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Example:
package logicaloperator;
public class LogicalOperator {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b) );
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b) );
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.10 Formatting Output

You already know how to display console output using the print or println methods. A new printf
method enables you to format output. The syntax to invoke this method is:
System.out.printf (format, items)
where format is a string that may consist of substrings and format specifiers. A format specifier
specifies how an item should be displayed.

Frequently Used Specifiers


Specifiers Output Example
%b A Boolean value true or false
%c A character ‘a’
%d A decimal integer 200
%f A floating-point number 45.460000
%e A number in standard 4.556000e+01
scientific notation
%s A string “Java is cool”

Example:
int count = 5;
double amount = 45.56;
System.out.printf (“count is %d and amount is %f”, count, amount);

The display:
count is 5 and amount is 45.560000

19
By default, a floating-point value is displayed with six digits after the decimal point.

Example:
package addition;
//displays the sum of two numbers.
import java.util.Scanner;

public class Addition


{
public static void main(String args[])
{
//create scanner to obtain input from command window
Scanner input = new Scanner(System.in);

int number1; //first number to add


int number2; //second number to add
int sum; //sum of number1 and number2

System.out.print("Enter first integer: "); //prompt


number1 = input.nextInt(); // read first number from user

System.out.print("Enter second integer: "); //prompt


number2 = input.nextInt(); // read second number from user

sum = number1 + number2; // add numbers

System.out.printf("Sum is %d \n", sum); //display sum


// \n is called as line feed, add an empty line after the string

} //end of main method


} //end of class Addition

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.11 Increment and Decrement Operators

Increment Operator: used to increment the value of a variable by 1. This is denoted by the
symbol “++”. This can be used in two ways.
 Pre-increment, e.g. ++x;
 Post-increment, e.g. x++;

20
Decrement Operator: used to decrement the value of a variable by 1. This is denoted by the
symbol “--”. This can be used in two ways.
 Pre-decrement, e.g. - - x;
 Post-decrement, e.g. x - -;

Example:

package incredecre
public class IncreDecre {
public static void main(String args[]) {
int a = 5;
System.out.println(a);
System.out.println(++a);
System.out.println(a++);
System.out.println(a--);
System.out.println(--a);
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

2.12 Naming Conventions

Below are the conventions for naming variables, methods, and classes:

 Use lowercase for variables and methods. If a name consists of several words,
concatenate them into one, making the first word lowercase and capitalizing the first
letter of each subsequent word; for example, the variables radius and area and the
method showInputDialog.

 Capitalize the first letter of each word in a class name; for example, the Addition.

 Capitalize every letter in a constant, and use underscores between words, for example,
the constant PI and MAX_VALUE.

Understanding them will help you to understand the Java programs.

21
Chapter 3: Keyboard Input

3.1 Keyboard Input

Reading Keyboard Input

The Scanner class is designed to read input from a source (System.in).

First you create a Scanner object and connect it to the System.in object.
Example:
Scanner keyboard = new Scanner (System.in);

The parts of the statement:

Scanner keyboard
Declares a variable named keyboard. The data type of the variable is Scanner. Because
Scanner is a class, the keyboard variable is a class type variable.

= new Scanner (System.in);


The assignment operator (=) will assign something to the keyboard variable.
The new key word is to create an object in memory.
The Scanner (System.in) specifies that a Scanner object should be created, and should be
connected to the System.in object.

Some of the Scanner class methods

Method Example and Description


nextByte byte x;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a byte value: “);
x = keyboard.nextByte( );
Returns input as a byte.
nextDouble double number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a double value:”);
number = keyboard.nextDouble( );
Returns input as a double.
nextFloat float number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a float value:”);
number = keyboard.nextFloat( );
Returns input as a float.
nextInt int number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a integer value: ”);
number = keyboard.nextInt( );
Returns input as a an int.
nextLine String name ;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter your name:”);

22
name = keyboard.nextLine( );
Returns input as a string.
nextLong long number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a long value:”);
number = keyboard.nextLong( );
Returns input as a long.
nextShort short number;
Scanner keyboard = new Scanner(System.in);
System.out.print (“Enter a short value: “);
number = keyboard.nextShort( );
Returns input as a short.

Any program that uses the Scanner class should have the following statement:

import java.util.Scanner;
OR
import java.util.*;

It tells the Java compiler where in the Java library to find the Scanner class, and makes it
available to your program.

package payroll;
//This program demonstrates the Scanner class
import java.util.Scanner;
public class Payroll
{
public static void main(String[] args)
{
String name; //to hold name
int hours; //hours worked
double payRate; //hourly pay rate
double grossPay; //Gross pay

//create a scanner object to read input


Scanner keyboard = new Scanner(System.in);

//Get the user's name


System.out.print("What is your name? ");
name = keyboard.nextLine();

//get the number of hours worked this week


System.out.print("How many hours did you work this week? ");
hours = keyboard.nextInt();

//get the user's hourly pay rate


System.out.print("What is your hourly pay rate? ");
payRate = keyboard.nextDouble();

23
//calculate the gross pay
grossPay = hours * payRate;

//display the resulting information.


System.out.println("Hello " +name);
System.out.println("Your gross pay is $" +grossPay);
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

24
Chapter 4: Java Classes

4.1 String Class

The String class allows you to create objects for holding strings. It also has various methods
that allow you to work with strings.

The String class is provided by the JAVA API for handling strings is named String.

The following program shows String variables being declared, initialized, and then used in a
println statement.

package stringdemo;
// A simple program demonstrating string objects
public class StringDemo
{
public static void main(String[] args)
{
//The greeting & name variable holds the address of a String object
//A String object here is "Good day" & "John"
String greeting = "Good day ";
String name = "John";

System.out.println(greeting + name);
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

Because the String type is a class instead of a primitive data type, it provides numerous
methods for working with strings. For example, the String class has a method named length that
returns the length of the string stored in an object.

package stringlength;
// This program demonsrates the String class's length method

public class StringLength


{
public static void main(String[] args)
{
String name = "Jimmy";
int stringSize;

/*The String class's length method returns the number of


*characters in the string, including spaces */

25
stringSize = name.length();
System.out.println(name + " has " + stringSize + " characters.");
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

A few String class methods

Method Description & Example


charAt(index) The argument index is an int value & specifies a character
position in the string. The first character is at position 0, the
second character is at position 1, and so forth. The method
returns the character at the specified position. The return
value is of the type char.
Example:
char letter;
String name = “Ronaldo”;
letter = name.charAt(3);
Output:
a
length() This method returns the number of characters in the string.
The return value is of the type int.
Example:
int stringSize;
String name = “Ronaldo”;
stringSize = name.length( );
Output:
7
toLowerCase( ) This method returns a new string that is the lowercase
equivalent of the string contained in the calling object.
Example:
String bigName = “Ronaldo”;
String littleName = bigName.toLowerCase( );
Output:
ronaldo
toUpperCase This method returns a new string that is the uppercase
equivalent of the string contained in the calling object.
Example:
String littleName = “ronaldo”;
String bigName = littleName.toUpperCase( );
Output:
RONALDO

26
The following program demonstrates these methods:

package stringmethods;
//This program demonstrates a few of the String methods

public class StringMethods


{
public static void main(String[] args)
{
String message = "Java is Great Fun!";
String upper = message.toUpperCase();
String lower = message.toLowerCase();
char letter = message.charAt(2);
int stringSize = message.length();

System.out.println(message);
System.out.println(upper);
System.out.println(lower);
System.out.println(letter);
System.out.println(stringSize);

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

Comparing Strings

1. Use equals() method


 Compares the characters in both strings
Example 1
package equals;
public class Equals {
public static void main(String args[]) {
String message1 = “Hello”;
String message2 = “hello”;
if(message1.equals(message2))
System.out.println(“They are the same”);
else
System.out.println(“They are different”);
}
}

27
Output:
____________________________________________________________________________
____________________________________________________________________________

Example 2
package equalsignorecase;
public class EqualsIgnoreCase {
public static void main(String args []) {
String m1 = “Bye”;
String m2 = “bye”;
if(m1.equalsIgnoreCase(m2)) {
System.out.print(“They are equal”);
}
else {
System.out.print(“They are not equal”);
}
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

2. Use = = operator
 Compares 2 object references to see if they refer to the same object
package comparison;
public class Comparison {
public static void main ( String args [ ] ) {
String code1 = “Joker”;
String code2 = new String(code1);
System.out.println(code1.equals(code2));
System.out.println(code1 == code2 );
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

4.2 Random Class

A Random object generates pseudo-random numbers. Random Class is found in the java.util
package.

import java.util.*;

Method Name Description


nextInt( ) returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble( ) returns a random real number in the range [0.0, 1.0)

28
Example:
Random rand = new Random ( );
int randomNumber = rand.nextInt(10); // 0 to 9

Generating random numbers

1. Common usage: to get a random number from 1 to N

int n = rand.nextInt(20) + 1; // 1 to 20 inclusive

2. To get a number in arbitrary range [min, max] inclusive:

int n = rand.nextInt (max – min + 1) + min

Example: A random integer between 4 and 10 inclusive:

int n = rand.nextInt (10 – 4 + 1) + 4

Random Questions:

Given the following declaration, how would you get:


Random rand = new Random ( );

1. A random number between 1 and 47 inclusive?

int random1 = rand.nextInt (47) + 1;

2. A random number between 1 and 47 inclusive?

int random2 = rand.nextInt (8) + 23;

Write a program that simulates rolling of two 6-sided dice until their combined result comes up
as 7.

package dice;
// Rolls two dice until a sum of 7 is reached.
import java.util.*;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int tries = 0;
int sum = 0;
while (sum != 7) {
// roll the dice once
int roll1 = rand.nextInt(6) + 1;
int roll2 = rand.nextInt(6) + 1;
sum = roll1 + roll2;
System.out.println(roll1 + " + " + roll2 + " = " + sum);

29
tries++;
}
System.out.println("You won after " + tries + " tries!");
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

4.3 Math Class

Java provides many useful methods in the Math class for performing common mathematical
functions. Here are some examples:

Math.min (a, b) returns the minimum number of two numbers


Math.max (a,b) returns the maximun number of two numbers
Math.abs (x) returns the absolute value of the number
Math.pow (a, b) returns a raised to the power of b (ab)
Math.sqrt (x) returns the square root of x for x >=0

Example:

Math.max (2.5, 4) returns 4


Math.min (3,2) returns 2
Math.abs (-2.1) returns 2.1
Math.pow (2, 3) returns 8.0
Math.sqrt(4) returns 2.0

package power;
public class Power{
public static void main (String[ ] args) {
int base = 3, exponent = -4;
double result = Math.pow (base, exponent);
System.out.println (“Answer =” +result);
}
}

Output:
____________________________________________________________________________
____________________________________________________________________________

30
Chapter 5: Date & Decimal Format

5.1 Date Format

Some common formatting symbols for SimpleDateFormat and their meanings.

Symbol Meaning Value Sample


y Year Number yyyy → 2007
M Month in year Text or Number MM → 10
MMM → Oct
MMMM → October
d Day in month Number dd → 20
D Day in year Number DDD→ 289
h Hour in AM/PM Number hh → 09
H Hour in day (0-23) Number HH → 17
a AM/PM marker Text a → AM
m Minutes in hour Number mm → 35
s Seconds in minute Number ss → 54
S Milliseconds Number mmm → 897
E Day in week Text E → Sat
EEEE → Saturday

If you do not pass any string when creating a new SimpleDateFormat object, the default
formatting is used.

Example :

SimpleDateFormat new date;


new date = new SimpleDateFormat ( );

package datedisplay1;
/* To display the month, day and year in the MM/dd/yy
shorthand format, such as 07/04/03*/
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat
public class DateDisplay1 {
public static void main (String[] args) {
Date today;
SimpleDateFormat sdf;
today = new Date();
sdf = new SimpleDateFormat ("MM/dd/yy");
System.out.println( sdf.format(today));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

package datedisplay2;

31
package datedisplay2;
//To display which day of the week today is, we can use the letter E.
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat

public class DateDisplay2 {


public static void main (String[] args) {
Date today;
SimpleDateFormat sdf;
today = new Date();
sdf = new SimpleDateFormat ("EEEE");
System.out.println("Today is " + sdf.format(today));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

package datedisplay;
import java.util.*; // for date
import java.text.*; // for SimpleDateFormat

public class DateDisplay {


public static void main (String[] args) {
Date today;
SimpleDateFormat simpleDF1, simpleDF2;

today = new Date();


simpleDF1 = new SimpleDateFormat();
simpleDF2 = new SimpleDateFormat("EEEE MMMM dd, yyyy");

//Default short format display


System.out.println( "Today is " + simpleDF1.format(today));

//Programmer-designated long format display


System.out.println("Today is " + simpleDF2.format(today));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

5.2 Decimal Format

This code allows you to round a double value to 2 decimal places using DecimalFormat.

You can increase the decimal places by adding an extra #. For example
DecimalFormat("#.###"); rounds to 3 decimal places.

32
package decimalplaces;
import java.text.*;
public class DecimalPlaces {
public static void main (String [] args) {
double d = 1.234567;
DecimalFormat df = new DecimalFormat (“#.##”);
System.out.print (df.format (d));
}
}
Output:
____________________________________________________________________________
____________________________________________________________________________

package radius;
import java.text.*; //for the decimal format
import java.util.*; //for the keyboard input

public class Radius {


public static void main (String [ ] args) {
double radius, length, volume, area;
double PI=3.142;

Scanner keyboard = new Scanner (System.in);

DecimalFormat df = new DecimalFormat ("#.##");

System.out.println("Enter the radius:");


radius=keyboard.nextDouble();

System.out.println("Enter the length:");


length=keyboard.nextDouble();

area = radius*radius*PI;

volume = area*length;

System.out.println("The volume is:" +df.format(volume) );


}
}

Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________

33
Chapter 6: Control Structures

6.1 if Statement

 The Java if statement has the following syntax:


if (condition)
statement;

 If the boolean condition is true, the statement is executed; if it is false, the statement is
skipped

 This provides basic decision making capabilities

Two-way Decisions

The windshield wipers are controlled with an ON-OFF switch. The flowchart below shows how
this decision is made.

Start at the top of the chart then follow the line to the question:
is it raining?

The answer is either true or false.

 If the answer is true,


o follow the line labeled True,
o perform the instructions in the box "wipers on",
o follow the line to "continue".

 If the answer is false,


o follow the line labeled False,

34
o perform the instructions in the box "wipers off",
o follow the line to "continue".

Decisions

The windshield wiper decision is a two-way decision (sometimes called a binary decision). The
decision seems small, but in programming, complicated decisions are made of many small
decisions. Here is a program that implements the wiper decision:

package raintester;
import java.util.Scanner;
public class RainTesterb {
public static void main (String [ ] args) {
Scanner scan = new Scanner (System.in);
String answer;
System.out.print (“Is it raining? (Y or No): ”);
answer=scan.nextLine( );
if (answer.equals (“Y”))
System.out.println(“Wipers ON”);
else
System.out.println(“Wipers OFF”);
}
}

The user is prompted to answer with a single character, Y or N :


System.out.print("Is it raining? (Y or N): ");
The Scanner reads in whatever the user enters (even if the user enters more than one
character):
answer = scan.nextLine();
The if statement tests if the user entered exactly the character Y (and nothing else):
if ( answer.equals("Y") ) // is answer exactly "Y" ?
If so, then the statement labeled "true branch" is executed. Otherwise, the statement labeled
"false branch" is executed.
The "true branch" is separated from the "false branch" by the reserved word else.

Examples:

package guess;
//demonstrate the if ...else statement
public class Guess {
public static void main(String args [ ])

/*must specify the throws java.io.IOException because the program using the System.in.read( ).
It necessary to handle input error*/

throws java.io.IOException
{
char ch, answer;
answer = 'K';//character and string are not same

35
System.out.println("I'm thinking of a letter between A and Z.");
System.out.print("Can you guess it:");

//get a char
ch=(char) System.in.read( );

if
(ch==answer) System.out.println("***Right***");
else
System.out.println("....Sorry, you're wrong." );
}
}

package division;
import java.util.Scanner; //this program demonstrates the if-else statement
public class Division
{
public static void main(String[] args)
{
double number1, number2; // division operands
double quotient; //result of division

//create a Scanner object for keyboard input


Scanner keyboard = new Scanner(System.in);

//get the first number


System.out.print("Enter a number: ");
number1 = keyboard.nextDouble();

//get the second number


System.out.print("Enter another number: ");
number2 = keyboard.nextDouble();

if(number2 == 0)
{
System.out.println("Division by zero is not possible.");
System.out.println("Please run the program again and ");
System.out.println("enter a number other than zero.");
}
else
{
quotient = number1 / number2;
System.out.println("The quotient of " +number1);
System.out.println("divided by " +number2);
System.out.println(" is " +quotient);
}
}
}

36
The if-else-if Statement

package ladder;
//Demonstrate an if-else-if ladder.
public class Ladder {
public static void main(String args[]) {
int month =4;//April
String season;

if
(month == 12 || month == 1 || month == 2)
season = "Winter";
else if
(month == 3 || month == 4 || month == 5)
season = "Spring";
else if
(month == 6 || month == 7 || month == 8)
season = "Summer";
else if
(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus month";

System.out.println("April is in the " +season+ ".");


}
}

package multipleif;
import java.util.Scanner ;
public class MultipleIf {
public static void main(String args[ ]) {
int x, y;
Scanner key = new Scanner(System.in);
System.out.println(“Enter first value:”);
x = key.nextInt();
System.out.println(“Enter second value:”);
y = key.nextInt();
if (x>y) {
System.out.print(“First value is bigger than second value”);
} else if (x<y) {
System.out.print(“First value is smaller than second vavlue”);
} else {
System.out.print(“Both values are equal”);
}
}
}

37
6.2 Switch…Case

In addition to the nested if statement, Java provides a second method for choosing from many
alternative actions. Compare the following code, each of which accomplishes the same task.

The default case, at the end of the switch statement, acts similarly to the else at the end of the
nested if. It will catch any value that doesn't have an exact match in the cases. Although it is not
necessary to include the default case (just as it is not necessary to include the else), it is good
programming practice to account for any unexpected values.

Example – This switch statement assigns a grade based on a quiz that was scored out of five.

38
package switchcase;
import java.util.Scanner;
public class SwitchCase {
public static void main (String args[]) {
char ch;
String s;
Scanner key = new Scanner(System.in);
System.out.print(“Select [F]oods [D]rinks [S]leeping : “);
s = key.nextLine();
ch = s.charAt(0);
switch (ch) {
case 'F' : System.out.println("Eating... ");
break;
case 'D' : System.out.println("Drinking...");
break;
case 'S' : System.out.println("Sleeping...");
break;
default : System.out.println("No such option!" );
break;
}
}
}

39
Chapter 7: Iteration/Repetition

A loop is part of a program that repeats. It is a control structure that causes a statement or
group of statements to repeat. Java has three looping control structures:
 while loop
 do-while loop
 for loop

7.1 while loop

A while statement has the following syntax:


while (condition) {
//statement
}

If the condition is true, the statement is executed; then the condition is evaluated again.

The statement is executed over and over until the condition becomes false.

If the condition of a while statement is false initially, the statement is never executed.

Therefore, we say that a while statement executes zero or more times.

Example:

int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}

ackage summing;
//While Loop statements executes the condition first then the loop body
import java.util.Scanner;
public class Summing {
public static void main(String[] args) {

int data;
//read an initail data
Scanner keyboard = new Scanner(System.in);
System.out.println ("Enter an integer value, \nThe program exits if the input is 0");

data = keyboard.nextInt();

// keep reading data until the input is 0

int sum = 0;

//while (loop-continuation-condition)

40
while (data != 0)
{
//loop body
sum += data; //equivalent to sum = sum + data;

//reads next data


System.out.println( "Enter an integer value, \nThe program EXITS if the
input is 0");

data = keyboard.nextInt();
}
System.out.println( "The sum is " +sum);
}
}

7.2 do-while loop

A do-while statement has the following syntax:


do {
//statement
}
while (condition);

This loop will execute the code block once, before checking if the condition is true, then it will
repeat the loop as long as the condition is true.

Example:

int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);

package testaverage;
import java.util.Scanner;
//this program demonstrates a user controlled loop.
public class TestAverage {
public static void main(String[] args) {
int score1, score2, score3; //three test scores
double average; //average test score
char repeat; //to hold 'y' or 'n'
String input;

System.out.println("This program calculates the " +


"average of three test scores.");

41
Scanner keyboard = new Scanner(System.in);

//get as many sets of test scores as the user wants


do
{
//get the first test score
System.out.print("Enter score #1: ");
score1 = keyboard.nextInt();

//get the second test score


System.out.print("Enter score #2: ");
score2 = keyboard.nextInt();

//get the third test score


System.out.print("Enter score #3: ");
score3 = keyboard.nextInt();

//consume the remaining new line


keyboard.nextLine();

//calculate and print the average test score


average = (score1 + score2 + score3) / 3.0;
System.out.println("The average is " +average);
System.out.println();

//does the user want to average another set?


System.out.println("Would you like to average " +
"another set of test scores?");
System.out.print("Enter Y for yes or N for no: ");
input = keyboard.nextLine(); //read a line
repeat = input.charAt(0); //get the first char
}
while(repeat == 'Y' || repeat == 'y');
}
}

7.3 for loop

The purpose of the for statement is to repeat Java statements many times. It is similar to the
while statement, but it is often easier to use if you are counting or indexing because it combines
three elements of many loops: initialization, testing, and incrementing.

The for statement has this form:

for(initialization; Boolean expression; update)


{

42
There are three parts in the for statement

 The initialization statement is done before the loop is started, usually to initial a
variable.
 The Boolean expression is tested at the beginning of each time the loop is done. The
loop is stopped when this Boolean expression is false (the same as the while loop)
 The update statement is done at the end of every time through the loop, and usually
increments a variable.

Example1:

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


System.out.println(i);
}

Example2:

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


System.out.println(i);
}

package squares;
public class Squares {
public static void main(String[] args) {
int number; //loopcontrol variables

System.out.println("Number Number Squared");


System.out.println("----------------------");

for (number = 1; number <= 10; number++)


{
System.out.println(number + "\t\t\t" + number * number);
}
}
}

package testsum;
// computes the sum of the first 100 positive integers
public class TestSum {
public static void main(String[ ] args) {
//initialize sum
int i, sum = 0;

// for (<initialization>; <boolean expression>; <update>)


for(i = 1; i<= 100; i++)
{

43
// loop body
sum += i; //equivalent to sum = sum + i;
}
// display result
System.out.println("The sum is " +sum);
}
}

44
References

Gaddis, T., (2019), Starting out with Java: from control structures through objects, 7th Edition,
Pearson Addison

Liang, D.Y., (2018), Introduction to JAVA Programming, 11th Edition, Pearson

45

You might also like