Building Java Program
Building Java Program
Building Java Program
@ Jane Nteere 1
LECTURE OUTLINE
• Java programming Language
• Phases of developing Java Program
• Java Terminologies
• Java executable file
• Java structure and Java Fundamentals (Code Formatting and
Code Elements)
• Compiling and running a Java Program
• Input and Output statements in Java
@ Jane Nteere 2
@ Jane Nteere 3
JAVA
Java (this is what you need to know for this course)
• A complete programming language developed by Sun Microsystems
INC in 1991 (James Gosling and Patrick Naughton)and later acquired
by Oracle
• Like any programming language, the Java language has its own
structure, syntax rules, and programming paradigm.
• The Java language's programming paradigm is based on the concept
of OOP, which the language's features support.
• Can be used to develop either web based (java applets) or stand-
alone software
• Java applets are programs that run from a Web browser and
make the Web responsive and interactive. Through the use of
applets, the Web becomes responsive, interactive, and fun to
use
• Java has many pre-created code libraries available
@ Jane Nteere 4
JAVA PLATFORM COMPONENTS
1. Java Language
2. Java Compiler
• Java translator that translates java instructions (source code) which are
.java files into an intermediate language called bytecode which are .class
files
3. Java Virtual Machine (JVM)
• At runtime, the JVM reads and interprets .class files and executes the
program's instructions on the native hardware platform for which the JVM
was written.
• JVM is a piece of software written specifically for a particular platform.
The JVM is the heart of the Java language's "write-once, run-anywhere"
principle. Your code can run on any chipset for which a suitable JVM
implementation is available. JVMs are available for major platforms like
Linux and Windows, and subsets of the Java language have been
implemented in JVMs for mobile phones.
@ Jane Nteere 5
JAVA PLATFORM COMPONENTS
4. Java Development Kit (JDK)
• Includes: Java compiler, the Java virtual machine (JVM) and the Java
class libraries of prebuilt utilities that help you accomplish most
common application-development tasks. These libraries can be
accessed: https://docs.oracle.com/javase/8/docs/api/
• In order to create, compile and run Java program you would need
JDK installed on your computer.
5. Java Runtime Environment (JRE)
• JRE consists of the JVM and the Java class libraries. Those contain
the necessary functionality to start Java programs.
• When you only need to run a java program on your computer, you
would only need JRE.
@ Jane Nteere 6
JDK EDITIONS
• Java Standard Edition (J2SE)
• J2SE can be used to develop client-side standalone applications or
applets.
• Java Enterprise Edition (J2EE)
• J2EE can be used to develop server-side applications such as Java
servlets and Java ServerPages.
• Java Micro Edition (J2ME).
• J2ME can be used to develop applications for mobile devices such
as cell phones.
@ Jane Nteere 7
PROGRAMMING ENVIRONMENTS
1. Text Editor is used to create simple text files
2. Integrated development environment (IDE)
• It provides an editor, compiler, and other programming tools
• Supports the programmer in the task of writing code, e.g., it
provides auto-formating of the source code, highlighting of the
important keywords, etc.
• calls the Java compiler (javac) which creates
the bytecode instructions. These instructions are stored
in .class files and can be executed by the Java Virtual Machine
• Examples
• Netbeans
• Eclipse
8 @ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere
COMPILING JAVA PROGRAM
At compile time, java file is compiled by Java Compiler (It does
not interact with OS) and converts the java code into bytecode.
@ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere 9
PROCESSING A JAVA PROGRAM (CONT..)
@ Jane Nteere
ENCAPSULATION
• Encapsulation is the mechanism that binds together code and
data, keeping them safe from external interference and misuse.
• When code and data are linked, an object is created.
• Within an object code and data may be private or public to that
object.
• Private code and data is only accessible by another part of the object. Not
accessed by another piece of program that exist outside the object.
• Public code and data other parts of the program can access it even if its
defined within the object.
• Basic unit of encapsulation is class. A class:
• Defines the form of an object
• Specifies members of a class (data and code that will operate on data)
• Member variables or instance variables = data defined by class
• Member methods or methods = code that operates on the data
• Objects are instances of a class
@ Jane Nteere
–Example 1:
Understanding Objects Object: circle
State:
Radius
•Objects Behaviour/action
–Represents an entity in real world. setRadius()
getArea()
E.g. student, table, dog, circle etc. getPerimeter()
@ Jane Nteere
@ Jane Nteere
ANATOMY OF A JAVA PROGRAM
• Comments
• Package
• Reserved words
• Modifiers
• Statements
• Blocks
• Classes
• Methods
• The main method
@ Jane Nteere
/*
FIRST JAVA PROGRAM
First Java application that prints "This is my first program in java"
on the screen
*/
//Java Package NB: name is in lowercase
package firstjavaprogram;
//Java class NB: name starts with capital letter of every word combined
public class FirstJavaProgram {
//main method
public static void main(String[] args) {
// statements to be executed are written here
System.out.println("This is my first program in java“);
}
}
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - PACKAGE
package firstjavaprogram;
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM
import package.*;
• When package.* is used, then all the classes and interfaces of this package will
be accessible.
• import keyword is used
• Example:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*; //access by use of keyword import followed by package name
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
@ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere 21
}
UNDERSTANDING JAVA PROGRAM
import package.classname;
• When package.classname* is used, then only declared class of this package will
be accessible..
• import keyword is used
• Example:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A; //access by use of keyword import followed by packagename. classname
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
@ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere 22
}
UNDERSTANDING JAVA PROGRAM
fully qualified name.
• Only declared class of this package will be accessible
• import keyword is NOT used
• Example:
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - CLASS
public class FirstJavaProgram {
• The class can be accessed by other classes within the program. This is
because of the use of public access modifier,
• A java file can have any number of classes but it can have only one
public class and the file name should be same as public class name.
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - METHOD
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - METHOD
• A Java method is a collection of statements that are grouped together to perform an
operation.
• Method definition consists of a method header and a method body.
• syntax
modifier returnType nameOfMethod (Parameter List) //method header
{
// method body
}
• 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.
• Parameter List − 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.
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - METHOD
• Example:
public static int methodName(int a, int b)
{
// body
}
• In this case:
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM – MAIN METHOD
• The main method provides the control of program flow.
• The Java interpreter executes the application by invoking
the main method.
• In order to run a class, the class must contain a method
named main. The program is executed from the main method
• The main method looks like this:
public static void main(String[] args)
{
// Statements;
}
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM – MAIN METHOD
public static void main(String[] args){
// Statements;
System.out.println("This is my first program in java");
}
• public: This makes the main method public that means that
we can call the method from outside the class.
• static: We do not need to create object for static methods to
run. They can run itself.
• void: It does not return anything.
• main: It is the method name. This is the entry point method
from which the JVM can run your program.
• (String[] args): Used for command line arguments that are
passed as strings. We will cover that in a separate post.
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM -
STATEMENTS
System.out.println("This is my first program in
java");
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM -
STATEMENTS
• 4 Types of Java Statements
1. Import statements
• Used to import the components of a package into a program
• Use reserved word import
2. Expression statements
• change values of variables, call methods, and create objects.
3. Declaration statements
• declare variables.
4. Control flow statements
• determine the order that statements are executed and implement
branching or looping so that the Java program can run particular
sections of code based on certain conditions.
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM -
STATEMENTS
• Examples of Java Statements
• //import statement
import java.io.*;
• //declaration statement
int number;
• //expression statement
number = 4;
• //control flow statement
if (number < 10 )
{
//expression statement
System.out.println(number + " is less than ten");
} CSC111:Jan
@ 2018 Week 4 @ Jane Nteere
Jane Nteere 32
@ Jane Nteere
SCOPE, VISIBILITY, ACCESSIBILITY
• Scope refers to the boundaries of programs and components of
programs.
• Visibility refers to portions of the scope that can be known to a
component of a program.
• Accessibility refers to portions of the scope that a component can
interact with.
@ Jane Nteere
SCOPE
• Scope
• Also referred to as a block
• Part of program where a variable may be referenced
• Determined by location of variable declaration
• Boundary usually demarcated by { }
• Example
public MyMethod1()
{
int myVar; myVar accessible in
... method between { }
}
@ Jane Nteere
SCOPE – EXAMPLE
Scope
package mypackage ;
public class MyClass1 {
public void MyMethod1() {
Method
...
}
public void MyMethod2() {
Package
Class
...
Method
}
}
public class MyClass2 {
}
Class
@ Jane Nteere
ACCESSIBILITY/VISIBILITY MODIFIERS
• Modifiers can control visibility/accessibility.
• Visibility and Accessibility are normally used interchangeably, since visible
components are normally accessible and accessible components are normally
visible.
• Java uses certain reserved words called modifiers that specify the properties
of the data, methods, and classes and how they can be used. These
keywords are:
• public
• Static
• private
• Final
• Abstract
• protected.
• A public datum, method, or class can be accessed by other programs. A private datum
or method cannot be accessed by other programs.
@ Jane Nteere
VISIBILITY MODIFIER – WHERE VISIBLE
• “public”
• Referenced anywhere (i.e., outside package)
• “protected”
• Referenced within package, or by subclasses outside
package
• None specified (package)
• Referenced only within package
• “private”
• Referenced only within class definition
• Applicable to class fields & methods
@ Jane Nteere
CLASS MODIFIERS
• Class modifiers include the following:
• <none> - When no modifier is present, by default the class is
accessible by all the classes within the same package.
• public - A public class is accessible by any class.
• abstract - An abstract class contains abstract methods.
• final - A final class may not be extended, that is, have subclasses.
• NB: A single Java file can only contain one class that is declared
public.
@ Jane Nteere
METHOD MODIFIERS
• Method Modifiers include the following:
• <none> - When no modifier is present, by default the method is accessible by
all the classes within the same package.
• public - A public method is accessible by any class.
• protected -A protected method is accessible by the class itself, all its
subclasses.
• private - A private method is accessible only by the class itself.
• static - accesses only static fields.
• final - may not be overridden in subclasses.
• abstract - defers implementation to its subclasses.
@ Jane Nteere
TYPES OF VARIABLES
• Local Variable
• Declared inside method of the class. Their scope is limited to
the method hence cannot be changed their value nor
accessed outside the method.
• Static (or Class) Variable
• Associated with class and common for all instances of the
class.
• Instance variable
• A variable which is declared inside the class but outside the
method, is called instance variable . It is not declared as static
41 @ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere
@ Jane Nteere
STREAMS
• Stream: an object that either delivers data to its destination (screen, file, etc.)
or that takes data from a source (keyboard, file, etc.)
• Input stream: a stream that provides input to a program
• System.in is an input stream
• Output stream: a stream that accepts output from a program
• System.out is an output stream
• Java provides the following three standard streams −
• Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented as System.in
• Standard Output − This is used to output the data produced by the user's program and
usually a computer screen is used for standard output stream and represented
as System.out
• Standard Error − This is used to output the error data produced by the user's program
and usually a computer screen is used for standard error stream and represented
as System.err
• The java.io package contains a collection of stream classes.
@ Jane Nteere
ESCAPE SEQUENCES
• escape sequence: A special sequence of characters used to represent
certain special characters in a string.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
• Example:
System.out.println("\\hello\nhow\tare \"you\"?\\\\");
• Output:
\hello
how are "you"?\\
@ Jane Nteere
Formatting text with printf
System.out.printf("format string", parameters);
• A format string can contain placeholders to insert parameters:
• %d integer
• %f real number
• %s string
• these placeholders are used instead of + concatenation
• Example:
int x = 3;
int y = -17;
System.out.printf("x is %d and y is %d!\n", x, y);
// x is 3 and y is -17!
• printf does not drop to the next line unless you write \n
@ Jane Nteere
printf width
• %Wd integer, W characters wide, right-aligned
• %-Wd integer, W characters wide, left-aligned
• %Wf real number, W characters wide, right-aligned
• ...
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 10; j++) {
System.out.printf("%4d", (i * j));
}
System.out.println(); // to end the line
}
Output:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
@ Jane Nteere
printf precision
• %.Df real number, rounded to D digits after decimal
• %W.Df real number, W chars wide, D digits after decimal
• %-W.Df real number, W wide (left-align), D after decimal
Output:
your GPA is 3.3
more precisely: 3.254
@ Jane Nteere
printf question
• Modify our Receipt program to better format its output.
• Display results in the format below, with $ and 2 digits after .
Subtotal: $70.00
Tax: $5.60
Tip: $10.50
Total: $86.10
@ Jane Nteere
printf answer (partial)
...
@ Jane Nteere
Input and System.in
• System.out
• An object with methods named println and print
• System.in
• not intended to be used directly
• We use a second object, from a class Scanner, to help us.
@ Jane Nteere
Java class libraries, import
• Java class libraries: Classes included with Java's JDK.
• organized into groups named packages
• To use a package, put an import declaration in your program.
• Syntax:
// put this at the very top of your program
import packageName.*;
• To use Scanner, you must place the above line at the top of your program (before
the public class header).
@ Jane Nteere
Method
Scanner methods
Description
nextInt() reads a token of user input as an int
nextDouble() reads a token of user input as a double
next() reads a token of user input as a String
nextLine() reads and returns next entire line of
input as a String
• Each of these methods causes your program to pause until the user has typed
input and pressed Enter, then it returns the typed value to your program.
@ Jane Nteere
Another Scanner example
import java.util.*; // so that I can use Scanner
public class ScannerSum {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please type three numbers: ");
int num1 = console.nextInt();
int num2 = console.nextInt();
int num3 = console.nextInt();
int sum = num1 + num2 + num3;
System.out.println("The sum is " + sum);
}
}
@ Jane Nteere
Input tokens
• token: A unit of user input, as read by the Scanner.
• Tokens are separated by whitespace (spaces, tabs, newlines).
• How many tokens appear on the following line of input?
23 John Smith 42.0 "Hello world" $2.50 " 19"
@ Jane Nteere
@ Jane Nteere
STRINGS
• string: An object storing a sequence of text characters.
• Unlike most other objects, a String is not created with new.
String name = "text";
String name = expression;
• Examples:
String name = "Marla Singer";
int x = 3;
int y = 5;
String point = "(" + x + ", " + y + ")";
@ Jane Nteere
Indexes
• Characters of a string are numbered with 0-based indexes:
String name = "P. Diddy";
index 0 1 2 3 4 5 6 7
char P . D i d d y
@ Jane Nteere
String methods
Method name Description
indexOf(str) index where the start of the given string
appears in this string (-1 if it is not there)
length() number of characters in this string
substring(index1, index2) the characters in this string from index1
or (inclusive) to index2 (exclusive);
substring(index1) if index2 omitted, grabs till end of string
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters
@ Jane Nteere
Modifying strings
• Methods like substring, toLowerCase, etc. create/return
a new string, rather than modifying the current string.
String s = "lil bow wow";
s.toUpperCase();
System.out.println(s); // lil bow wow
@ Jane Nteere
Strings as user input
• Scanner's next method reads a word of input as a String.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
name = name.toUpperCase();
System.out.println(name + " has " + name.length() +
" letters and starts with " + name.substring(0, 1));
Output:
What is your name? Madonna
MADONNA has 7 letters and starts with M
@ Jane Nteere
Comparing strings
• Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name == "Barney") {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}
• This code will compile, but it will not print the song.
@ Jane Nteere
The equals method
• Objects are compared using a method named equals.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name.equals("Barney")) {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}
@ Jane Nteere
String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
@ Jane Nteere
Type char
• char : A primitive type representing single characters.
• Each character inside a String is stored as a char value.
• Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or '\''
@ Jane Nteere
The charAt method
• The chars in a String can be accessed using the charAt method.
String food = "cookie";
char firstLetter = food.charAt(0); // 'c'
System.out.println(firstLetter + " is for " + food);
System.out.println("That's good enough for me!");
@ Jane Nteere
char vs. int
• All char values are assigned numbers internally by the computer,
called ASCII values.
• Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42
• What is s + 1 ? What is c + 1 ?
• What is s + s ? What is c + c ?
@ Jane Nteere
Comparing char values
• You can compare char values with relational operators:
'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
@ Jane Nteere
RECAP
• Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have
different meaning in Java.
• Class Names − the first letter should be in Upper Case. If several words are used to form a name
of the class, each inner word's first letter should be in Upper Case.
Example: class MyFirstJavaClass
• Method Names − All method names should start with a Lower Case letter. If several words are
used to form the name of the method, then each inner word's first letter should be in Upper
Case.
Example: public void myMethodName()
• Program File Name − Name of the program file should exactly match the class name. When
saving the file, you should save it using the class name (Remember Java is case sensitive) and
append '.java' to the end of the name (if the file name and the class name do not match, your
program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
• public static void main(String args[]) − Java program processing starts from the main() method
which is a mandatory part of every Java program
@ Jane Nteere