Sei sulla pagina 1di 34

CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Labsheet 1:
Basic Java Programming

In this first labsheet, students are required to read through the document below
that introduces the Java syntax and Java basic programming constructs. Students
are then required to try all the examples given in this document on the Eclipse
development environment.

1. The Anatomy of a Java Program .......................................................... 2


2. Data Types............................................................................................... 3
3. Writing methods (functions) ................................................................. 6
4. Programming Style: In Java… ............................................................. 8
5. Operators & Expressions....................................................................... 8
6. Arrays .................................................................................................... 13
7. Comments in Java ................................................................................ 17
8. Class Types – e.g String ....................................................................... 17
9. Control Structures................................................................................ 20
10. Simple Input and Output..................................................................... 28
11. Packages ................................................................................................ 30
12. Exceptions ............................................................................................. 31
13. Additional Examples ............................................................................ 32

-1-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

1. The Anatomy of a Java Program


It is customary for a programmer‟s first program in a new language to be “Hello,
World.” Here‟s our HelloWorld.java program:

Example 1: HelloWorld

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, world!");
}
}

 The first line declares our HelloWorld class. Class is the syntax for declaring
a class, and prepending with the public modifier means the class will be visible
outside HelloWorld„s package. For now just think of them as boilerplate.

 Because we didn‟t declare a package explicitly, HelloWorld is in the default


package. More on that in a few lectures.

 The code between the curly braces, { ... } define the contents of the
HelloWorld class, in this case a single method, main

 In order to make a class executable with the java command, it must have a
main method. Every Java application must have a main() method, where
execution begins

public static void main(String[] args) { ... }

 The public modifier means we can call this method from outside the class.

 The static modifier means the method can be called without instantiating an
object of the class. Static methods (and variables) are sometimes called class
methods.

 void is the return type. In particular, main returns nothing. Sometimes such
subprograms are called procedures and distinguished from functions, which
return values.

 After the method name, main, comes the parameter list. Main takes a single
parameter of type String[]- an array of Strings. Args is the name of the
parameter, which we can refer to within the body of main

-2-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

2. Data Types
There are two kinds of types in Java:
 Data Types
 Class Types

Data types are types that are built into the Java compiler
 boolean values are either true or false
 char values are 16-bit Unicode values (e.g., 'A', 'B', …, '0', '1', …, '$', '?', …)
 byte values are 8-bit signed integers (-128 … 127)
15 15
 short values are 16-bit signed integers (-2 … 2 -1)
31 31
 int values are 32-bit signed integers (-2 … 2 -1)
64 64
 long values are 64-bit signed integers (-2 … 2 -1)
 float values are 32-bit signed reals (-3.4e38 … 3.4e38)
 double values are 64-bit signed double precision reals (-1.7e308 …
1.7e308) accurate to 14 or 15 digits

Class types are types that must be defined for the compiler
-- Object, Applet, Thread, String, …

Data variables can be declared using any of the data types:

boolean done = false;


int counter = 1;
char initial = 'C';
double sum = 0.0;

Simplified Pattern:

Type VariableName [ = InitialValue ] ;

Class variables must be defined slightly differently, using the new operator:
String name = new String("CSE Yr2");

Simplified Pattern:

Type VariableName = new ClassName (Arguments);

Constants can be declared by preceding a variable declaration with final static:

final static int N = 20;

-3-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

final static char TOP_GRADE = 'A';

final static double PI = 3.14159;

Pattern:
final static Type CONSTANT_NAME = InitialValue;

Example 2: Boolean Example

public class BooleanEx {

public static void main(String[] args) {


boolean flag = false;
int x;

if (flag==true)
x=10;
else
x=20;

System.out.println("The value of x is "+x);


}

Example 3: Data Types

public class LiteralTest {


public static void main(String[] args) {
String name = "Tan Ah Teck"; // String is double-quoted
char gender = 'm'; // char is single-quoted
boolean isMarried = true; // true or false
byte numChildren = 8; // Range of byte is [-127,
128]
short yearOfBirth = 1945; // Range of short is [-
32767, 32768]. Beyond byte
int salary = 88000; // Beyond the ranges of
byte and short
long netAsset = 8234567890L; // Need suffix 'L' for
long. Beyond int
double weight = 88.88; // With fractional part
float gpa = 3.88f; // Need suffix 'f' for
float

-4-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
// println() can be used to print value of any type
System.out.println("Name is " + name);
System.out.println("Gender is " + gender);
System.out.println("Is married is " + isMarried);
System.out.println("Number of children is " +
numChildren);
System.out.println("Year of birth is " + yearOfBirth);
System.out.println("Salary is " + salary);
System.out.println("Net Asset is " + netAsset);
System.out.println("Weight is " + weight);
System.out.println("GPA is " + gpa);
}
}

Program Output:

Name is Tan Ah Teck


Gender is m
Is married is true
Number of children is 8
Year of birth is 1945
Salary is 88000
Net Asset is 1234567890
Weight is 88.88
Height is 188.8

-5-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

3. Writing methods (functions)

A class method is a method that accesses the class fields declared in its class. To
declare a class method, specify the static keyword in the class method
signature. Check out the examples below.

Example 4: Square Method

public class SquareEx {

public static void main(String[] args) {


int x=10;
int y=square(x);
System.out.println("The square of x is "+y);
}

public static int square(int a){


int b;
b=a*a;
return b;
}

Example 5: Power Method

public class PowerEx {

public static void main(String[] args) {

int x=2;
int n=3;
int result;

result = Power(x,n);

System.out.println("The result is "+result);

-6-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
public static int Power(int a, int b){
int c=1;

for(int i=1; i<=b;i++)


c=c*a;

return c;
}

Example 6: Factorial Method

class FactorialFinder extends Object


{

public static void main(String [] args)


{
static final int N = 10;
int nFactorial = factorial(N);
System.out.println(N + "! = " + nFactorial);
}

public static int factorial(int n)


{
int result = 1;
for (int counter = 2; counter <= n; counter++)
{
result *= counter;
}
return result;
}
}

Sample Run (N == 12):

12! = 479001600
Press any key to continue . . .

-7-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

4. Programming Style: In Java…

 Variable names are usually written in all lowercase letters,


with the first letter of each word after the first word capitalized.

 Constant names are usually written in all uppercase letters,


with an underscore (_) separating each word in the name.

5. Operators & Expressions


Relational Operators
A data variable’s value can be compared to another value using the relational
operators:
 a == b // true iff a equals b
 a != b // true iff a does not equal b
 a <= b // …
 a >= b // …
 a < b // …
 a > b // …
Complex boolean expressions can be built from AND (&&), OR (||) and NOT
(!):

 'A' <= initial && initial <= 'Z'


// true iff initial is uppercase

 score < 0 || score > 100


// true iff score is in 0..100

 value > 0 && !done


// true iff value is positive and done is false

Variables can be assigned a value using the assignment operator:


sum = 0.0;

count = 1;

initial = 'A';

-8-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
done = 6>7;

Assignments may also be chained when it makes sense to do so:


int a, b, c;

a = b = c = 0; //a == 0 && b == 0 && c == 0

Example 7: Comparison Operators

The following program, ComparisonDemo, tests the comparison operators:

class ComparisonDemo {

public static void main(String[] args){


int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}

Output:

value1 != value2
value1 < value2
value1 <= value2

Arithmetic Operators
The usual numeric operations are supported for the numeric types:

 + for addition
 - for subtraction
 * for multiplication
 / for integer and real division
 % for integer modulus (remainder)

-9-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Increment/Decrement Shortcuts:

Instead of Write

x = x + 1; x++;

x = x – 1; x--;

Each of these shortcuts has two forms: a prefix form and a postfix form…

x = 1;
y = ++x; // y == 2, x == 2

x = 1;
y = x++; // y == 1 && x == 2

x = 1;
y = --x; // ?

x = 1;
y = x--; // ?

Example 8: Arithmetic Operators

The following program, ArithmeticDemo, tests the arithmetic operators.

class ArithmeticDemo {

public static void main (String[] args){

// result is now 3
int result = 1 + 2;
System.out.println(result);

// result is now 2
result = result - 1;
System.out.println(result);

// result is now 4
result = result * 2;
System.out.println(result);

// result is now 2
result = result / 2;

- 10 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
System.out.println(result);

// result is now 10
result = result + 8;
// result is now 3
result = result % 7;
System.out.println(result);
}
}

Example 9: Unary Operators

The following program, UnaryDemo, tests the unary operators:

class UnaryDemo {

public static void main(String[] args){


// result is now 1
int result = +1;
System.out.println(result);
// result is now 0
result--;
System.out.println(result);
// result is now 1
result++;
System.out.println(result);
// result is now -1
result = -result;
System.out.println(result);
boolean success = false;
// false
System.out.println(success);
// true
System.out.println(!success);
}
}

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

- 11 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 10: Conditional Operator


public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


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

This would produce the following result:

Value of b is : 30
Value of b is : 20

- 12 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

6. Arrays
In Java, unlike most other programming languages, there are three steps to
actually filling out an array, rather one.

1. Declare the array. There are 2 ways to do this:

int MyIntArray[];
int[] MyIntArray;

2. Create space for the array and define the size. To do this, use the keyword
new, followed by the variable type and size:

MyIntArray = new int[500];

3. Place data in the array. For arrays of native types, the array values are all set
to 0 initially.

MyIntArray[4] = 467;

Examples of declaring arrays:

// Declare an array and assign some memory to hold


it.
long Primes[] = new long[1000000];

// Another way of declaring an array


long[] EvenPrimes = new long[1];

// Populate the array.


EvenPrimes[0] = 2;

// An array declaration using an implied 'new'


// and populating it.
long Fibonacci[] ={1,1,2,3,5,8,13,21,34,55,89,144};

// Declare an array. Default value is null.


long BlackFlyNum[];

// Array indexes must be type int.


BlackFlyNum = new long[2147483647];
- 13 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

// Declare a two dimensional array.


int twoD[][] = new int[3][4];

// Uninitialized 3D array.
long[][][] ThreeDTicTacToe;

 Indexing of arrays starts with 0, as in C or C++. I.e. the first element of an


array is: MyArray[0]

Example 11: Array

class ArraySample {

public static void main (String args[]) {

int arr[] = {10,20,30,40,50};

for (int i=0; i<arr.length; i++) {


System.out.println(“arr[“ + i + ”]=” +arr[i]);

}
}
}

Example 12: Array Sum

public class ArraySum {

public static void main(String[] args) {

int arr[] = new int[10];


int sum=0;
for(int i=0;i<10;i++)
arr[i]=i;

for(int j=0;j<10;j++)
sum=sum+arr[j];

System.out.println("The sum of the array is "+sum);


}

- 14 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 13: Array Manipulation

Here is a complete example of showing how to create, initialize and process arrays:

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

This would produce the following result:

1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

Example 14: Passing an array to a method

public class ArrayMethod {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int arr[] = new int[10];


int sum1;
for(int i=0;i<10;i++)
arr[i]=i;

sum1=arraySum(arr);

- 15 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

System.out.println("The sum of the array is "+sum1);


}

public static int arraySum(int arr2[]){


int sum2=0;
for(int j=0;j<10;j++)
sum2=sum2+arr2[j];

return sum2;
}

Example 15: Passing and Returning an array


public class ArrayMethod2 {
public static void main(String[] args) {

int arr[] = new int[10];


for(int i=0;i<10;i++)
arr[i]=i;

int arr3[]=arrayAdd(arr);

for(int k=0;k<10;k++)
System.out.println(arr3[k]);
}

public static int [] arrayAdd(int arr2[]){


for(int j=0;j<10;j++)
arr2[j]=arr2[j]+1;
return arr2;
}
}

- 16 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

7. Comments in Java
C++ Style Comments
Comments are preceded by a slash-slash (//) and ends where the current source
code line ends.
e.g.

//This is a C++ style comment in Java source code

Multi-line comments begin with a slash-star (/*) and ends with a star-slash
(*/).
e.g.
/* this is a multi-line comment in
Java. Comments are useful for describing the
meaning of a section of code */

8. Class Types – e.g String


In addition to data types, Java also provides many predefined class types…
One of these is String class:

String module = new String("Object Oriented


Techniques");

Java also provides a more convenient way to initialize String objects:


String module = "Object Oriented Techniques";

The + operator is defined to perform concatenation for String objects,


and += is defined as a concatenation short-cut, so we could instead have written:
String module = "Object" + " Oriented";
module += " Techniques";

You can access a substring from within a String:

String s1 = "listen";
String s2 = s1.substring(0, 3);
String s3 = s1.substring(4, 5);
String s4 = s3 + s2;

- 17 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

and you can access individual characters within them:

char ch = s1.charAt(4);

and you can find their length:

int itsLength = s4.length();

Note: Calling a method from a different class is different from calling a method
from the same class:

int itsLength = s4.length();

Pattern:

ObjectName.MethodName ( Arguments )

In O-O terminology, calling a method is described as sending a message to an


object…

The expression

s4.length()

is sending the object s4 the length() message, to which s4 responds with


the number of chars it contains…

To compare two String objects, you must use the String class’s methods,
not the relational operators:

String s1 = "John";
boolean done = s1.equals("John"); // true!
boolean undun = s1 == s2; // never true!

A more general compare() method is also provided for arbitrary comparisons:

String s1 = "John";
String s2 = "Jane";
int flag1 = s1.compare(s2) < 0; // true
int flag2 = s1.compare(s2) >= 0; // false

String s3 = "Joan";

- 18 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
int flag3 = s1.compare(s3) > 0; // true
int flag4 = s1.compare(s3) <= 0; // false

String s4 = "John";
int flag5 = s1.compare(s4) == 0; // true
int flag6 = s1.compare(s4) != 0; // false

Example 16: String Manipulation


public class StringEx {

public static void main(String[] args) {


String s1 = "listen";
String s2 = s1.substring(0, 4);
String s3 = s1.substring(4, 6);
String s4 = s3 + s2;

System.out.println("s1 is "+s1);
System.out.println("s2 is "+s2);
System.out.println("s3 is "+s3);
System.out.println("s4 is "+s4);

char ch = s1.charAt(4);
System.out.println("ch is "+ch);

int itsLength = s4.length();


System.out.println("Length of s4 is "+itsLength);

String s5 = "John";
boolean done = s1.equals("John");
System.out.println("Comparison is "+done);

- 19 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

9. Control Structures
The Java if Statement

public long factorial(long n)


{
if (n > 1)
return n * factorial(n-1);
else if (n == 1)
return 1;
else
{
System.err.println("factorial(" + n + ") is
invalid");
System.exit(1);
}
}

Pattern:
if ( BooleanExpression ) Statement1 [ else
Statement2 ]

Note that each Statement can be either a single statement,


or a block (multiple statements enclosed in braces)…

Example 17: If-Then-Else

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A
for a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
public static void main(String[] args) {

int testscore = 76;


char grade;

if (testscore >= 90) {


grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {

- 20 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is:

Grade = C

Control Structures: The switch Statement


public void PerformChoice(char menuChoice)
{
switch (menuChoice)
{
case 'A': ActionA();
break;
case 'B': ActionB();
break;
case 'C': ActionC();
break;
// . . .
default:

System.err.println("PerformChoice(" + menuChoice
+") is invalid!");
}
}

Note: A break or return statement is needed at the end of each “case


section”, or else execution will “fall through” to the next “case section”…

Unlike if-then and if-then-else statements, the switch statement can have a number
of possible execution paths. A switch works with the byte, short, char, and int
primitive data types. It also works with enumerated types (discussed in Enum Types), the
String class, and a few special classes that wrap certain primitive types: Character,
Byte, Short, and Integer (discussed in Numbers and Strings).

The following code example, SwitchDemo, declares an int named month whose value
represents a month. The code displays the name of the month, based on the value of month,
using the switch statement.
- 21 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 18: Switch Case


public class SwitchDemo {
public static void main(String[] args) {

int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}

In this case, August is printed to standard output.

Example 19: Switch Multiple Case

The following code example, SwitchDemo2, shows how a statement can have multiple case
labels. The code example calculates the number of days in a particular month:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

- 22 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}

This is the output from the code:

Number of Days = 29

Control Structures: The while (Pretest) Loop


public int find(char ch, String str)
{
int pos = str.length()-1;
boolean done = false;

while (pos >= 0 && !done)


if (str.charAt(pos) == ch)
done = true;
else
pos--;
return pos;
}
Pattern: while (Condition) Statement

Condition -- any boolean expression; repetition continues so long as it is true


Statement – either a single statement or a block of Java statements

- 23 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 20: While Loop

public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Control Structures: The do (Posttest) while Loop


public int find(char ch, String str)
{
int pos = str.length()-1;
boolean done;

if (str.length() > 0)
do
if (str.charAt(pos) == ch) done = true;
else pos--;
while (pos > 0 && !done);

return pos;
}

Pattern: do Statement while (Condition);

Statement – either a single statement or a block of Java statements


Condition -- any boolean expression; repetition continues so long as it is true.

- 24 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 21: Do-While Loop

public class Test {

public static void main(String args[]){


int x = 10;

do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

This would produce the following result:

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Control Structures: The for Loop


public int find(char ch, String str)
{
for (int pos = str.length()-1; pos >= 0; pos--)
if (str.charAt(pos) == ch)
break;

return pos;
}
Pattern:

for ( Initializer; Condition; StepExpression)


Statement

Initializer -- any expression that initializes the loop-control variable


Condition -- any boolean expression; repetition continues so long as it is true
StepExpression -- any expression (usually changing the loop-control variable)
Statement -- either a single statement or block of statements
- 25 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Control Structures: The indeterminate Loop


Java provides no indeterminate loop, but it is easy to build your own.

Pattern1:

for (;;)
{
Statements1
if (TerminationCondition) break;
Statements2
}

Pattern2:

while (true)
{
Statements1
if (TerminationCondition) break;
Statements2
}

Example 22: For Loop

class ForDemo2 {
public static void main(String[] args){
int sum=0;
for(int i=1; i<11; i++){
sum = sum+i;
}

System.out.println("The sum is: "+ sum);


}
}

Example 23: For Loop Sum

public class Sum1To100 {


public static void main(String[] args) {
int sum = 0;
double average;
int number = 1;
while (number <= 100) {
sum += number; // Final sum is int 5050
++number;
}
average = (double) sum / 100;

- 26 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
System.out.println("Average is " + average); // Average is 50.0
}
}

Control Structures: The try-catch Block

static private BufferedReader myReader = new


BufferedReader(new InputStreamReader(System.in));

public static char getChar()


{
int myValue = 0;
try
{
myValue = myReader.read();
}
catch (IOException err)
{
System.out.println(err);
System.exit(1);
}
return (char) myValue;
}

Methods may throw exceptions…


-- If so, their declaration must state it…

Example: Here is the declaration of BufferedReader.read():

public int read() throws IOException

If a method throws an exception,


any call to that method must take place in a try-block,
and the exception must be caught and handled
in the corresponding catch-block…

A package typically defines its own set of exception classes,


so to handle them, you must browse a package’s documentation…

- 27 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

10. Simple Input and Output

Input From Keyboard via "Scanner"

Java, like all other languages, supports three standard input/output streams: System.in
(standard input device), System.out (standard output device), and System.err (standard
error device). The System.in is defaulted to be the keyboard; while System.out and
System.err are defaulted to the console. They can be re-directed to other devices, e.g., it is
quite common to redirect System.err to a disk file to save these error message.

You can read input from keyboard via System.in (standard input device).

Java SE 5 introduced a new class called Scanner in package java.util to simplify


formatted input (and a new method printf() for formatted output described earlier). You
can construct a Scanner to scan input from System.in (keyboard), and use methods such
as nextInt(), nextDouble(), next() to parse the next int, double and String token
(delimited by white space of blank, tab and newline).

Example 24: Scanner Sum


import java.util.*;
public class ReadAndSum {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sn = new Scanner(System.in);

System.out.println("Input first number: ");


num1=sn.nextInt();
System.out.println("Input second number: ");
num2=sn.nextInt();

sum=num1+num2;
System.out.println("Sum is "+sum);
sn.close();

}
}

Example 25: Scanner Loop

import java.util.*;

public class ScannerLoop {


public static void main(String[] args) {
double n; // Holds the next input number.
double sum = 0; // Sum of all input numbers.
Scanner in = new Scanner(System.in);
//Prompt and read input in a loop.
System.out.println("Will add numbers. Non-number stops input.");

- 28 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
while (in.hasNextDouble()) {
n = in.nextDouble();
sum = sum + n;
}
in.close();
//Display output
System.out.println("The total is " + sum);
}
}

Example 26: Scanner Test


import java.util.Scanner; // Needed to use the Scanner
public class ScannerTest {
public static void main(String[] args) {
int num1;
double num2;
String str;
// Construct a Scanner named "in" for scanning System.in (keyboard)
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
num1 = in.nextInt(); // Use nextInt() to read int
System.out.print("Enter a floating point: ");
num2 = in.nextDouble(); // Use nextDouble() to read double
System.out.print("Enter a string: ");
str = in.next(); // Use next() to read a String token, up
to white space
// Formatted output via printf()
System.out.printf("%s, Sum of %d & %.2f is %.2f%n", str, num1, num2,
num1+num2);
}
}

Example 27: Scanner Line

You can also use method nextLine() to read in the entire line, including white spaces, but
excluding the terminating newline.

import java.util.Scanner; // Needed to use the Scanner


public class ScannerNextLineTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string (with space): ");
// Use nextLine() to read entire line including white spaces,
// but excluding the terminating newline.
String str = in.nextLine();
System.out.printf("%s%n", str);
}
}

- 29 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

11. Packages
Java stores classes in packages, which are containers for storing related
classes…

To use a class from a package, you must name them in an import statement:

import java.io.BufferedReader;

or you can import everything in a package using the * wildcard:

import java.io.*;

Every Java program automatically imports the classes from the package
java.lang, so you need not import classes stored there…
In fact

Some of the useful classes in the java.lang package include:


 Character // char-related functionality
 Integer // int-related functionality
 Double // double-related functionality
 Math // standard mathematical functions
 ...

java.lang.Object

public class Object


class Object is the root of the class hierarchy. Every class has Object as a
superclass.

All of the packages and classes in Java 8 are documented at


API specification for the Java™ Platform
http://docs.oracle.com/javase/8/docs/api/index.html

- 30 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

12. Exceptions
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:

 A user has entered invalid data.


 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or the JVM has
run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

To understand how exception handling works in Java, you need to understand the three
categories of exceptions:

 Checked exceptions: A checked exception is an exception that is typically a user


error or a problem that cannot be foreseen by the programmer. For example, if a file is
to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compilation.
 Errors: These are not exceptions at all, but problems that arise beyond the control of
the user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error
will arise. They are also ignored at the time of compilation.

Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A
try/catch block is placed around the code that might generate an exception. Code within a
try/catch block is referred to as protected code, and the syntax for using try/catch looks like
the following:

try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}

A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.

- 31 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 28: Exception

The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{

public static void main(String args[]){


try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}

This would produce the following result:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3


Out of the block

13. Additional Examples


Example 29: Temperature Conversion Program

import java.util.*;
public class Temperature {

public static void main(String[] args) {

double cel;
double far;
Scanner sn = new Scanner(System.in);

System.out.println("Input temperature in Celcius:


");
cel = sn.nextDouble();

far = (9.0/5*cel)+32;

System.out.println("Temperature in Fahrenheit:
"+far);
}

- 32 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

Example 30: Switch Case Menu

import java.util.*;

public class SwitchExample{


public static void main(String[] args){
int x, y;
int choice = 0;
Scanner sn = new Scanner(System.in);
do {
System.out.println("Enter two numbers for operation:");
x = sn.nextInt();
y = sn.nextInt();
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Exit");
System.out.println("Enter your choice:");
choice= sn.nextInt();
switch (choice){
case 1:
System.out.println("The sum is " + (x+y));
break;
case 2:
System.out.println("The subtaction is " + (x-y));
break;
case 3:
System.out.println("The multiplication is "+
(x*y));
break;
case 4:
System.out.println("The division is "+ (x/y));
break;
case 5:
System.exit(0);
default:
System.out.println("Invalid Entry!:");
}

}while (choice!=5);

Example 31: Getting Current Date & Time

This is very easy to get current date and time in Java. You can use a simple Date object with
toString() method to print current date and time as follows:

import java.util.Date;
- 33 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1

public class DateDemo {


public static void main(String args[]) {
// Instantiate a Date object
Date date = new Date();

// display time and date using toString()


System.out.println(date.toString());
}
}

- 34 -

Potrebbero piacerti anche