You are on page 1of 72

WEEK FOUR (5)

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

NB: this class will use J2SE (standalone applications).

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

CSC111:Jan 2018 Week 4 @ Jane Nteere @ Jane Nteere 10


JAVA – Object Oriented
• REM: Programs can be organized in two ways:
• around the code (what is happening)
• around its data (what is being affected).
• Structured programming -programs are organized around the
code i.e. code acting on data
• Object oriented programming (OOP) – programs are organized
around data i.e. ”data controlling access to code”. Thus, one
defines the data and the routines permitted to act on that data.
• To support OOP, all OOP languages have 3 traits:
• Encapsulation
• Polymorphism
• Inheritance

@ 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()

–Has state and behavior – Example 2:


–Object state = characteristics that define an Object: Student
object, also called attributes State:
Name
–Object behaviour/action = self-contained
ID
block of program code that carries out an Grades
action Behaviour/action
computeGPA()
@ Jane Nteere
CSC111:Jan 2018 Week 4 @ Jane Nteere getID() 13
Understanding
•Class
Classes, Objects
–Describes objects with common properties (describes state and
behavior that objects of its type supports)

@ Jane Nteere 14 CSC111:Jan 2018 Week 4 @ Jane Nteere


POLYMORPHISM & INHERITANCE
• Inheritance
• An important feature of object-oriented programs
• Classes share attributes and methods of existing classes but with
more specific features
• Helps you understand real-world objects
• Polymorphism
• Means “many forms”
• Allows the same word to be interpreted correctly in different
situations based on context

@ 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;

• This is a Java Package = a group of similar types of classes, interfaces


and sub-packages.
• Package in java can be categorized in two form:
 built-in package
 There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
 user-defined package.
 Programmers defined packages
• The package statement should be the first line in the source file.
• There can be only one package statement in each source file, and it
applies to all types in the file.
@ Jane Nteere
UNDERSTANDING JAVA PROGRAM - PACKAGE

• Accessing Java packages


• There are three ways to access the package from
outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

@ 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 {

• This is a Java class


• Every java application must have at least one class definition that
consists of class keyword followed by class name. By convention,
class names start with an uppercase letter. In this example, the class
name is 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

public static void main(String[] args){


// Statements;
System.out.println("This is my first program in java");
}

• This is 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

@ 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");

• This is a java statement. It prints the contents inside the


double quotes into the console and inserts a newline after
execution.

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

• Syntax for class modifiers:


[ClassModifier] class ClassName {…}
• Example:
public class Employee {…}

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

• Syntax for method modifiers:


[MethodModifers] ReturnType MethodName ([ParameterList) {}
• Example:
private void GetEmployee(int ID) { }

@ 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

double gpa = 3.253764;


System.out.printf("your GPA is %.1f\n", gpa);
System.out.printf("more precisely: %.3f\n", gpa);

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 .

• Example log of execution:


How many people ate? 4
Person #1: How much did your dinner cost? 20.00
Person #2: How much did your dinner cost? 15
Person #3: How much did your dinner cost? 25.0
Person #4: How much did your dinner cost? 10.00

Subtotal: $70.00
Tax: $5.60
Tip: $10.50
Total: $86.10

@ Jane Nteere
printf answer (partial)
...

// Calculates total owed, assuming 8% tax and 15% tip


public static void results(double subtotal) {
double tax = subtotal * .08;
double tip = subtotal * .15;
double total = subtotal + tax + tip;

// System.out.println("Subtotal: $" + subtotal);


// System.out.println("Tax: $" + tax);
// System.out.println("Tip: $" + tip);
// System.out.println("Total: $" + total);

System.out.printf("Subtotal: $%.2f\n", subtotal);


System.out.printf("Tax: $%.2f\n", tax);
System.out.printf("Tip: $%.2f\n", tip);
System.out.printf("Total: $%.2f\n", total);
}
} @ Jane Nteere
INTERACTIVE PROGRAMS
• We have written programs that print console output, but it is also
possible to read input from the console.
• The user types input into the console. We capture the input and use it in our
program.
• Such a program is called an interactive program.

• Interactive programs can be challenging.


• Computers and users think in very different ways.
• Users misbehave.

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

• Constructing a Scanner object to read console input:


Scanner name = new Scanner(System.in);
• Example:
Scanner console = new Scanner(System.in);

@ 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.*;

• Scanner is in a package named java.util


import java.util.*;

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

System.out.print("How old are you? "); // prompt


int age = console.nextInt();
System.out.println("You'll be 40 in " +
(40 - age) + " years.");

• prompt: A message telling the user what input to type.


@ Jane Nteere
Example Scanner usage
import java.util.*; // so that I can use Scanner

public class ReadSomeInput {


public static void main(String[] args) {
Scanner console = new Scanner(System.in);

System.out.print("How old are you? ");


int age = console.nextInt();

System.out.println(age + "... That's quite old!");


}
}

• Output (user input underlined):


How old are you? 14
14... That's quite old!

@ 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);
}
}

• Output (user input underlined):


Please type three numbers: 8 6 13
The sum is 27

• The Scanner can read multiple values from one line.

@ 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"

• When a token is not the type you ask for, it crashes.


System.out.print("What is your age? ");
int age = console.nextInt();
Output:
What is your age? Timmy
java.util.InputMismatchException
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...

@ 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

• The first character's index is always 0


• The last character's index is 1 less than the string's length

• The individual characters are values of type char (seen later)

@ 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

• These methods are called using the dot notation:


String gangsta = "Dr. Dre";
System.out.println(gangsta.length()); // 7
@ Jane Nteere
String method examples
// index 012345678901
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // 8
System.out.println(s1.substring(7, 10)) // "Reg"
String s3 = s2.substring(2, 8);
System.out.println(s3.toLowerCase()); // "rty st"

• Given the following string:


// index 0123456789012345678901
String book = "Building Java Programs";
• How would you extract the word "Java" ?
• How would you extract the first word from any string?

@ 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

• To modify a variable, you must reassign it:


String s = "lil bow wow";
s = 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

• The nextLine method reads a line of input as a String.


System.out.print("What is your address? ");
String address = console.nextLine();

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

• == compares objects by references (seen later), so it often gives false even


when two Strings have the same letters.

@ 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!");
}

• Technically this is a method that returns a value of type boolean,


the type used in logical tests.

@ 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

String name = console.next();


if (name.startsWith("Dr.")) {
System.out.println("Are you single?");
} else if (name.equalsIgnoreCase("LUMBERG")) {
System.out.println("I need your TPS reports.");
}

@ 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 '\''

• It is legal to have variables, parameters, returns of type char


char letter = 'S';
System.out.println(letter); // S

• char values can be concatenated with strings.


char initial = 'P';
System.out.println(initial + " Diddy"); // P Diddy

@ 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!");

• You can use a for loop to print or examine each character.


String major = "CSE";
for (int i = 0; i < major.length(); i++) {
char c = major.charAt(i);
System.out.println(c);
}
Output:
C
S
E

@ 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

• Mixing char and int causes automatic conversion to int.


'a' + 10 is 107, 'A' + 'A' is 130

• To convert an int into the equivalent char, type-cast it.


(char) ('a' + 2) is 'c'
@ Jane Nteere
char vs. String
• "h" is a String
'h' is a char (the two behave differently)
• String is an object; it contains methods
String s = "h";
s = s.toUpperCase(); // 'H'
int len = s.length(); // 1
char first = s.charAt(0); // 'H'
• char is primitive; you can't call methods on it
char c = 'h';
c = c.toUpperCase(); // ERROR: "cannot be dereferenced"

• 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'

• An example that prints the alphabet:


for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c);
}

• You can test the value of a string's character:


String word = console.next();
if (word.charAt(word.length() - 1) == 's') {
System.out.println(word + " is plural.");
}

@ 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

You might also like