• No results found

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

N/A
N/A
Protected

Academic year: 2022

Share "Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner."

Copied!
11
0
0

Loading.... (view fulltext now)

Full text

(1)

Handout 1

Introduction to Java programming language.

Java primitive types and operations.

Reading keyboard Input using class Scanner.

Java – an object-oriented programming language

Introduced by James Golsling in 1995 (at Sun ).

• supports development of full fledged applications and browser-run applets

• includes support for concurrency and security

• C++-like syntax, but no pointers, thus safer code

• supported by powerful vendor: Oracle Java Application

Standalone programs - run using a Java Virtual Machine interpreter

Widely used for

Networking

Database applications

Multi-tiered architectures

Important features of Java

• Portability - Java code compiles into platform independent byte-code, which is interpreted on each platform by a java-virtual -machine.

• Automatic garbage collection (no memory allocation/leakage worries)

• No pointer arithmetic (safer code)

• Multiple inheritance supported only for interfaces

• Rigorous support for exception (error) handling

• Supports method execution across a network via Remote Method Invocation

• Comes with an extensive library of predefined classes (Java API)

(2)

Object-Oriented Development

It is popular because of issues of productivity and overall speed of development.

Key idea – focus modeling and implementation on the individuals of the problem domain rather then system functions, build system description “around” the objects, because domain objects usually comprise the most stable part of the system (usually don’t change much even if system requirements change dramatically).

Class: a general description of objects of similar kind. Includes data and methods that operate on that data

Example: a banking application operates on accounts

Class: Account

Data (properties): Owner, Number, Open Date, Transactions Methods (behaviors): Compute Balance

Key OO concepts:

1. Objects and Classes

problem domain entities classified according to their properties 2. Encapsulation and Information Hiding

package an object’s data attributes and behavior together restrict access to data

3. Specialization (a.k.a. inheritance)

detect commonalities between classes – create class hierarchy to “inherit”

common properties without repeating them

Example: Checking account, Savings account classes are subclasses of Account. Inherit properties of Account,

Class: Checking Account

Data (properties): All those of Account class + Service Fee Methods (behaviors): All those of Account class + Deposit, Withdraw

4. Communication with messages

to invoke an object – send it a message, let the object itself handle it 5. Polymorphism

often same operation exists in many classes, example: Print each class implements it differently, but uses the same name for it

Compared to structured development, OO provides additional flexibility, potential for reuse and robustness in face of changes.

Click to see an illustration.

From Java source code to execution

(3)

Java application is a collection of classes. Here’s the simplest example with one class containing just a single method called main.

Create a Java source file called HelloWorldApp.java.

The name of the file must match the name of the class.

Java is case sensitive,

e.g. main is different from Main, Hello is different from hello

/* HelloWorldApp.java * Prints Hello, World! */

public class HelloWorldApp {

public static void main(String[] args) {

// print Hello World!

System.out.println("Hello, World! Welcome to Bentley.");

} }

In compiled languages:

In Java:

Java Virtual Machine (JVM) interprets byte-code Source Code

Processor- Specific Compiler

Binary File Runtime System

Java Virtual Machine Source

Code

Compiler javac.exe

Bytecode

Processor- Specific Interpreter

java.exe

Runtime System

Hello.class Hello.java

(4)

LEXICAL ELEMENTS:

Words and symbols that make up a language, including comments, keywords, identifiers, punctuation, literals, and operators.

Example:

/* This is an example of a simple Java program that prints the value stored to the variable x */

public class DeclareVar{

public static void main(String[] args){

int x; // declare variable x x = 5; // store the value 5 to x

System.out.println("x = " + x); // print the value of x }// end of main method

} // end of class DeclareVar

Comments: // for a single line , till the end of line

/* Start a multiple

line comment with the slash and asterisk End it with an asterisk and a slash

*/

Punctuation: a “;” is used to indicate the end of a statement.

Variable - is a named location to store data

• It can hold only one type of data

• All program variables must be declared before using them. A variable declaration associates a name with a storage location in memory and specifies the type of data it will store: e.g. int, float, double, char, String

x 5

Identifiers: names for elements in a program, including classes, methods, and variables

May consist of letters, digits, the underscore(_) and $ (reserved for system identifiers)

Must not start with a digit

Can’t be a keyword: word that has a meaning in the language, such as if, boolean, or class.

Can’t include spaces, punctuation symbols

Are case sensitive: x is not the same as X!

By convention: class names start with an uppercase letter, variables and methods start with the lowercase.

(5)

DATA TYPES: Each variable has a name and a type. Type refers to the values that can be stored in a variable. Java has primitive and class types.

1. Primitive: built into Java, define non-decomposable values.

(1) Numeric:

byte 8 bits = 1 byte -128 to 127 short 16 bits -32768 to 32767

int 32 bits -231 to 231-1 Default for integer literal

long 64 bits specify by adding an l or L: 23L

float 32 bits specify by adding f or F: 37.23F double 64 bits default for floating point literal

ex. of floating point types: 3.12342, 2.18e-25 (= 2.18 x 10-25)

(2) char: stores a single character, digit, or symbol. Always surrounded by single quotes, such as ‘a’ or ‘9’.

Stored in 2-bytes (as opposed to many other languages – allows for many alphabets)

Each character is stored as its code number in Unicode.

(3) boolean: true or false.

All variables must be declared either before or when they are first used:

ASSIGNMENT OPERATOR =

Used to set, or assign a variable is to store a given value in the location denoted by the variable name . Not the same as equality in algebra, It means -

“Store the value of the expression on the right side to the variable on the left side.”

Can have any expression on the right hand side of =

Restriction: the type of the variable must be compatible with the type of the expression on the right hand side.

Examples:

// declare integer variable and store value to it int x;

x = 3;

//declare new integer and store value of x to it int y = x;

// evaluated right to left:

// set value stored to x = value stored to y = 4 x = y = 4;

(6)

// declare two doubles and store values to them double u, v;

u = 2.32; v = x;

//declare two integers and store value to one of them int a = 2, b;

// declare a character variable and store a value to it char letter = ‘a’;

//declare two boolean variables and store values to them boolean done = false;

boolean start = true;

2. Classes : all other data types (i.e., non-primitives) are defined as class types.

String: stored as object of class String. Always enclosed in double quotes.

// declare a string variable and store a value to it String prompt = “enter your name”;

OPERATORS

Arithmetic Operators: only operate on numerical data.

+, -, *, /, %, ( )

(1) integer division: results from dividing one int by another. Returns whole number quotient, ignoring remainder (truncates).

21 / 4 = ? 7 / 2 = ?

(2) %: modulus, or remainder.

21 % 4 = ? 8 % 2 = ?

/* Illustration of % operator

*/

public class Remainder{

public static void main(String[] args){

int x = 7;

int y = 3;

int z = (x/y)*y + x%y

System.out.println("z = " + z); // print value of z } // end of main method

} // end of class Remainder

(7)

Order of precedence (elements in the same row have the same precedence):

()

+(unary) –(unary)

* / % + -

= (assignment)

Unary operators take one operand.

Example: -3 + 5

// unary operator is (–) before the three; the (+) is a binary operator here

Read from left to right when evaluating an expression.

Example:

int x = 4, y = 5, z = 3, answer;

answer = y - x * z;

System.out.println(answer);

answer = (y - x) * z;

System.out.println(answer);

answer = y / x + z;

System.out.println(answer);

answer = y / (x + z);

System.out.println(answer);

answer = x - y % z + y;

System.out.println(answer);

answer = (x - y) % (z + y);

System.out.println(answer);

Java automatically converts from int to double when the data types are mixed:

double x = 4; //4 is converted to a double x = 3.4 * 2; //2 treated as a double

Rule for implicit conversion: any numeric value can be assigned to a numeric value of any type that supports a larger range of values.

ints are converted to doubles in mixed-type expression.

doubles are not converted to ints in mixed-type expression.

Explicit type casting:

double x = 4.3; //

int y = (int)x; // truncates and stores 4 in y

int z = (int)'a'; // explicitly converts char to an int

(8)

Relational Operators: also called Comparison Operators.

Used with operands: <operand> operator <operand>

Use them for making decisions: true or false for outcome.

Include: > < >= <= == !=

!” is a not operator, so != means “not equal

=” is an assignment operator, while “==” is a comparison operator)

x = 3; // assigns 3 to x

y = x + 1; // increment x by 1 and store to y // compare x and y

x == y; // evaluates to true or false

// Demo of comparison operators and boolean type public class Comparison {

public static void main(String [] args) {

int grade = 87;

System.out.println( grade>50 );

// set a = boolean that condition evaluates to boolean a = (grade == 100);

System.out.println("Student earned 100% is " + a);

} }

Examples:

boolean state;

int i = 5;

int j = 9;

state = (i > j);

state = (i == j);

state = (i – 3) <= j;

state = (i != j);

(9)

OUTPUT

Print: use print and println methods. println moves the cursor to the beginning of the next line after completing the print.

Examples:

System.out.print(x); //print the value of x

System.out.println(x); //print the value of x followed by a //new line

System.out.println(“The result is ” + result);

System.out.println(“The sum of 2 + 3 is ” + 2 + 3);

// prints The sum of 2 + 3 is 23

System.out.println(“The sum of 2 + 3 is ” + (2 + 3));

// prints The sum of 2 + 3 is 5

Special characters:

\n //newline

\t //tab

\b //backspace \” //double quote

\\ //backslash

Example:

/*

This is a printing demo.

Shows special characters within a string

*/

public class PrintJava {

public static void main(String [] args) {

System.out.println("This\nwill start a new line");

System.out.println(3+"\n"+ 4 + "\non different lines");

System.out.println("first column\tsecond column");

System.out.println("with \"double quotes around it\"");

System.out.println("directory c:\\cs603\\homework");

}

}

(10)

INPUT Using Scanner class:

Use Scanner class to read from keyboard.

Scanner – a class for text input processing from keyboard, file, or string.

To read input from the keyboard:

a. Need to include the following line above the class definition

import java.util.Scanner;

This statement tells Java to

– Make the Scanner class available to the program

– Find the Scanner class in a library of classes (i.e., Java package) named java.util

b. Need to create an object of Scanner class inside the main method as follows:

Scanner kb = new Scanner (System.in);

Once a Scanner object has been created, a program can then use that object to read user input from the keyboard using methods of the Scanner class These methods are type-specific

kb.nextInt(); - returns an integer entered by the user. Skips all white space (space, tab, end-of-line characters) that appear before the integer.

kb.nextDouble(); - double

kb.nextBoolean();

kb.next(); - returns the String value consisting of characters up to, but not including the next white space (or end of line).

Essentially, reads one word, where word is a sequence of non-white space characters.

kb.nextLine(); - returns the String value consisting of characters up to, but not including the end of the current line. Unlike the other methods, does not skip the end-of-line character, instead treats it as the end of the line.

int x = kb.nextInt();

double y = kb.nextDouble();

String word = kb.next();

String line = kb.nextLine();

Subtle point:

• The method nextLine of the class Scanner reads the remainder of a line of text starting wherever the last keyboard reading left off. This can cause problems when combining it with different methods for reading from the keyboard such as nextInt

(11)

Example: Given the code,

Scanner keyboard = new Scanner(System.in);

int n = keyboard.nextInt();

String s1 = keyboard.nextLine();

String s2 = keyboard.nextLine();

and user input, 2

Heads are better than 1 head.

what are the values of n, s1, and s2?

Answer: n will be set to 2, s1 will be equal to "", and s2 will be equal to "Heads are better than"

Explanation: \n below denotes the “invisible” end of line character. Here’s what the user input looks like

2\nHeads are better than\n1 head.\n

If the following results were desired instead

n equal to 2, s1 equal to "heads are better than", and s2 equal to "1 head"

then an extra invocation of nextLine() would be needed to get rid of the end of line character '\n'.

Scanner keyboard = new Scanner(System.in);

int n = keyboard.nextInt();

keyboard.nextLine(); // to get rid of \n after number String s1 = keyboard.nextLine();

String s2 = keyboard.nextLine();

This only happens when the program needs to read a new line with nextLine() after using any other Scanner reading methods (next(), nextInt(), nextDouble(), etc..)

References

Related documents

Finally, by performing the hits of the West End at the imperial periphery, touring companies not only allowed colonial audiences to participate in the metropolitan culture, but

Different pathways or biological processes were represented by genes associated with aggressive (zinc ion response and lipid metabolism), order (lipid metabolism), sexual/religious

It has been reported that taurine play an important role in production and reproduction behavior of the species (Gaylord et al., 2014). Fish hydrolysate contains well

import java.util.Scanner; // include scanner utility for accepting keyboard

characters and instantiate inFile, an object of the class Scanner, which is going to fetch the input data from the file chosen be the user. Other type of

The quantities of rock excavation by ripper unit to form embankment for road formation construction shall be the net cubic content of the rock to the lines,

Following the method described in Section 3.5 , to model the dependence of distances on assumptions about SN color and selection effects, the BBC method is applied with two

We find that, assuming 5% distance errors, the SNeIA distances we could obtain with LSST are already suf ficient to improve over the RSD constraints below z =0.15 and