Академический Документы
Профессиональный Документы
Культура Документы
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-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
Example 1: HelloWorld
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.
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
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, …
Simplified Pattern:
Class variables must be defined slightly differently, using the new operator:
String name = new String("CSE Yr2");
Simplified Pattern:
-3-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
Pattern:
final static Type CONSTANT_NAME = InitialValue;
if (flag==true)
x=10;
else
x=20;
-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:
-5-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
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.
int x=2;
int n=3;
int result;
result = Power(x,n);
-6-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
public static int Power(int a, int b){
int c=1;
return c;
}
12! = 479001600
Press any key to continue . . .
-7-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
count = 1;
initial = 'A';
-8-
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
done = 6>7;
class ComparisonDemo {
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--; // ?
class ArithmeticDemo {
// 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);
}
}
class UnaryDemo {
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:
- 11 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
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.
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:
3. Place data in the array. For arrays of native types, the array values are all set
to 0 initially.
MyIntArray[4] = 467;
// Uninitialized 3D array.
long[][][] ThreeDTicTacToe;
class ArraySample {
}
}
}
for(int j=0;j<10;j++)
sum=sum+arr[j];
- 14 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
sum1=arraySum(arr);
- 15 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
return sum2;
}
int arr3[]=arrayAdd(arr);
for(int k=0;k<10;k++)
System.out.println(arr3[k]);
}
- 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.
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 */
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
char ch = s1.charAt(4);
Note: Calling a method from a different class is different from calling a method
from the same class:
Pattern:
ObjectName.MethodName ( Arguments )
The expression
s4.length()
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!
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
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);
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
Pattern:
if ( BooleanExpression ) Statement1 [ else
Statement2 ]
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) {
- 20 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
Grade = C
System.err.println("PerformChoice(" + menuChoice
+") is invalid!");
}
}
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
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);
}
}
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);
}
}
Number of Days = 29
- 23 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
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
if (str.length() > 0)
do
if (str.charAt(pos) == ch) done = true;
else pos--;
while (pos > 0 && !done);
return pos;
}
- 24 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
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
return pos;
}
Pattern:
Pattern1:
for (;;)
{
Statements1
if (TerminationCondition) break;
Statements2
}
Pattern2:
while (true)
{
Statements1
if (TerminationCondition) break;
Statements2
}
class ForDemo2 {
public static void main(String[] args){
int sum=0;
for(int i=1; i<11; i++){
sum = sum+i;
}
- 26 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
System.out.println("Average is " + average); // Average is 50.0
}
}
- 27 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
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).
sum=num1+num2;
System.out.println("Sum is "+sum);
sn.close();
}
}
import java.util.*;
- 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);
}
}
You can also use method nextLine() to read in the entire line, including white spaces, but
excluding the terminating newline.
- 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;
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
java.lang.Object
- 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:
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:
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
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.
import java.util.*;
public class Temperature {
double cel;
double far;
Scanner sn = new Scanner(System.in);
far = (9.0/5*cel)+32;
System.out.println("Temperature in Fahrenheit:
"+far);
}
- 32 -
CSE 2020Y(3) – Object-Oriented Techniques Labsheet 1
import java.util.*;
}while (choice!=5);
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
- 34 -