0% found this document useful (0 votes)
51 views34 pages

Object Oriented Programming: Week 2

The document provides an overview of object oriented programming concepts in Java including: 1. Defining variables of primitive types like int, boolean, double, etc. and using wrapper classes. 2. Accepting user input using System.in.read() and converting between strings, primitives, and wrappers. 3. Common programming constructs like if/else, for loops, methods, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views34 pages

Object Oriented Programming: Week 2

The document provides an overview of object oriented programming concepts in Java including: 1. Defining variables of primitive types like int, boolean, double, etc. and using wrapper classes. 2. Accepting user input using System.in.read() and converting between strings, primitives, and wrappers. 3. Common programming constructs like if/else, for loops, methods, and exception handling.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Object Oriented Programming

Week 2
Comments on Homework 1
• It is not possible to miss a homework. To pass
this course, you need an average of 75%. If
you have a good reason not to do your work
on time, then make sure I know it.
• Homeworks need to be named with your
name so that I don’t have to search through
my emails. Call your files something like
“ChrisPayneHmwk1.java”
• Use two-space formatting and camel format.
Primitive Variables
Defining Variables
All variable names must be defined in advance of use.

int thisInteger;
boolean finished = false;
double size = 56.2345;
byte b = 34;
char = ‘@’;
float valueFloat;
short s = 334;
long veryBig = 13452678;
String s1, s2 = “This is a string”, s3;
System.in.read
public class StringIn1{
public static void main(String[] args) throws Exception{
int i = System.in.read();
System.out.println(i);
}

Returns the ASCII values of input


System.in.read() – ASCII Output
System.in.read() - Output
ASCII and UNICODE
ASCII (American Standard Code for Information Interchange)
Is an 8-bit code with 256 characters numbered 0-255

UNICODE (Universal Code) is a 16-bit character code in general


use. Charcaters are numbered 0-65335 and includes most
alphabets and symbol systems.
ASCII Code
Values 0-31 – codes for device control
Values 32-127 – Visible ASCII, the keyboard
Values 128-255 – So-called “high Ascii” with
variable characters.
UNICODE includes ASCII as its first 255
characters
0-255 in Unicode has 00000000 ASCII
256-65335 Unicode, the first byte is non-zero
Strings

String s = “Hello Mom!”;

or

String s = “\”This is in quotes “\”;

• Strings can be output as literals by the


System.out.print command.
Output of several values
System.out.print
and
System.out.println
can combine values with strings e.g.
System.out.println(“Days since the new year = “
+ daysSinceNewYear + “up until today.”);
Constant values

final double PI = 3.14159;

By convention, constant identifiers are


capitalized
Strong typing, type casting, type promotion

Mixed type expressions

double average = doubleSum/integerSetSize;

Type promotion

byte a = 40, b = 60;


int c = a + b:

Type casting
byte b;
char c = (char) b;
int anInteger = (int) aDouble;
Selection statements – two forms

if (logical statement) {
.................
}

if (logical statement) {
.................
}
else
{
.................
}
The switch statement
switch (someVariable){

case (value1):
/* statement sequence ending with */
break;
................... // multiple case and break statements

case (valueN):
/* statement sequence ending with */
break;

default: // statement sequence (optional)


}
The try... catch statement

try {
/*successful operation code*/
}
catch(Exception sE){
/*exception handling code*/
}

The Exception class is an object class.


The Iteration Statements

1. while(logical statement is true) {


...........
}

2. do {
..........
}
while (logical statement is true)

3. for(initialization,condition,iteration) {
..........
}
Arithmetic and Logical Operators

Arithmetic operators

+, -, *, /, %, ++, --, +=, -=, *=, /=, %=


==, !=, >, <, >=, <=
Logical operators

&& = ‘AND’ || = ‘OR’ ! = ‘NOT’

ratio = denom == 0 ? 0 : num/denom;


Constructors

• The constructor is a method called when a


class is instantiated to a working object.

• Used for initialization of variables and other


objects.

• Can be omitted if no initialization is needed.


User-defined class Circle.java

public class Circle{


final double PI = 3.15159;
public double circumference(double radius){
return 2.0*radius*PI;
}

public double area(double radius) {


return PI*radius*radius;
}
}
Use of the class Circle.class
class UseCircle {

double radius, area, circumference;

public UseCircle() { // constructor


Circle c = new Circle(); // a new object Circle
radius = 10.0;
}

public void run() {


area = c.area(radius); // using the method area from Circle
circumference = c.circumference(radius);
System.out.println (“The area is “ + area + “The circumference is “ + circumference);
}

public static void main(String[] args) {


UseCircle uC = new UseCircle(); // the constructor instantiates this program
uC.run();
}
}
Java I/O Byte Streams
import java.io.*;
public class InputFromKeyboard {
String name;
public static void main(String[] args){
try{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(reader);
System.out.print(“What is your name?”);
name = keyboard.readLine();
System.out.println(“Hello “+name);
}
catch(IOException e){
System.out.println(e);
System.exit(1);
}
}
}
Importing packages

import java.io.InputStreamReader;
import java.io.Buffered Reader;

Alternatively

import java.io.*;
Input and double a number – Strings and
wrappers
import java.lang.*;
import java.io.*;
public class ManipulatingNumbers {
public static void main(String[] args) {
String sNumber,outString;
int twiceNumber;
try{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(reader);
Input and double a number – Strings and
wrappers (cont.)
System.out.print(“Enter a number: );
sNumber = keyboard.readLine();
twiceNumber = 2*Integer.parseInt(sNumber);
outString = Integer.toString(twiceNumber);
System.out.println();
System.out.println (“The number doubled is : “ + outString);
}
catch(IOException e) {
System.exit(1);
}
}
}
Constructors and static variables

• If all the useful part of the program is contained within the main()
method, then the global variables may also be defined inside main().

• Variables used by main() but declared outside main() must be declared as


static because main() is static.

• We must convert the String keyboard input sRadius, to a double using


Double.parseDouble(sRadius) from the wrapper class Double.

• We must trap the exception in case the input format is not recognised as
in a double form.

• There is no need, in this program, to convert the double answers back to


strings since that is taken care of by System.out.println();.
The Wrapper Classes
Classes for number conversions

• Character
• Boolean
• Byte
• Short
• Integer
• Long
• Float
• Double
The Wrapper Classes
Number formatting
import java.text.*;
public class NumberFormatting {
public static void main(String[] args) {
double d1 = 1.23456;
NumberFormat form2D =
NumberFormat.getNumberInstance();
form2D.setMaximumFractionDigits(2);
form2D.setMinimumFractionDigits(2);
System.out.println(form2D.format(d1));
}
}
}
The NumberFormat class
Using the command line String arguments

public class StringArguments {


public static void main(String[] args) {
int numberOfArguments;
for (int i = 0; i < args.length; i++){
System.out.println(args[i]);
}
}
}
A String application (Part 1)

import java.lang.*;
import java.io.*;
public class StringMethods {
public static void main(String[] args) {
String inString;
String outString = ““;
int stringLength;
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader keyboard = new BufferedReader(reader);
try{
System.out.println(“Enter a long string more than 20 characters long...”);
inString = keyboard.readLine();
stringLength = inString.length();
System.out.println(“The string”s length = “ + stringLength);
System.out.println(“Extract a substring “ + “of characters 12 to 24 ...”);
outString = outString + inString.substring(12,24);
A String application (Part 2)

System.out.println(outString);
outString = ““;
System.out.println(“The odd numbered characters” + “ in the string are : - “);
for (int i = 0; i < stringLength; i = i + 2){
outString = outString + inString.charAt(i);
}
System.out.println(outString);
System.out.println( “The ASCII values of the”+“ last six characters in the string...”);
for (int i = stringLength-6; i< stringLength; i++){
System.out.print((byte) inString.charAt(i) + “ “);
}
}
catch(IOException iE){....}
}
}
Using the String class

You might also like