Escolar Documentos
Profissional Documentos
Cultura Documentos
Contents
The Structure of Java Programs
Contents
Console Input and Output Arrays and Array Manipulation Using the Java API Documentation
Programming in Java
A Java Program
Java Program
public class HelloJava { public static void main(String[] args) { System.out.println("Hello, Java!"); } }
javac HelloJava.java
java cp . HelloJava
Hello, Java!
Typical Errors
Compile-Time Errors
javac: Command not found HelloJava.java:10: Method printl(java.lang.String) not found in class java.io.PrintStream HelloJava.java:4: Public class HelloJava must be defined in a file called "HelloJava.java".
Typical Errors
Runtime Errors
Cant find class HelloJava Exception in thread "main" java.lang.NoClassDefFoundError: HelloJava/class
java.text
java.awt java.net java.applet
Java Programs
Java programs are sets of class definitions The main() method is the entry point for standalone Java applications The signature for main() is:
public static void main(String[] args)
Keywords
A keyword is a word whose meaning is defined by the programming language Anyone who claims to be competent in a language must at the very least be familiar with that languages keywords
Javas keywords and other special-meaning words are listed in the next slide
Reserved Words
You may notice null, true, and false do not appear anywhere on the keywords list true, false, and null are not keywords but they are reserved words
You cannot use them as names in your programs either
Identifiers
Names given to a variable, method, field, class, interface, etc. Can start with a letter, underscore(_), or dollar sign($) Can contain letters, $, _, and digits Case sensitive Have no maximum length Examples:
userName, $app_name, __test, value, totalRevenue, location$
byte
short int long
8
16 32 64
Variables of type boolean may take only the values true or false Their representation size might vary
float
double char
32
64 16
Boolean Type
The boolean data type has two literals, true and false For example, the statement:
boolean truth = true;
declares the variable truth as boolean type and assigns it a value of true
The default integer values are int Defines long by using the letter L or l:
long value = 1234L;
Examples:
3.14 A simple floating-point value (a double) 6.02E23 A large floating-point value 2.718F A simple float size value 123.4E+306D A large double value with redundant D
Float.POSITIVE_INFINITY
Double.NaN Double.NEGATIVE_INFINITY Double.POSITIVE_INFINITY
Objects
Are reference types Contain a pointer (memory address) of their values Examples: String, Object, Date
Enumerations (enums)
Enumerations are special types that
Get values from a given set of constants
Are strongly typed Compiled to classes that inherit java.lang.Enum
public enum Color { WHITE, RED, GREEN, BLUE, BLACK } ... Color c = Color.RED;
Enumerations (enums)
Allow using if and switch:
switch (color) { case WHITE: System.out.println(""); break; case RED: System.out.println(""); break; ... } if (color == Color.RED) { ... }
Examples:
int i; // declare variable int value = 5; // declare and assign variable i = 25; // assign a value to a variable that is already declared
Operators
Category Unary Arithmetic Shift Comparison Operators ++ -- + - ! ~ (type) * / % + << >> >>> < <= > >= instanceof == !=
float f = 9.0F;
char c = A;
c > r true
c >= q true
Casting is used for explicit conversion of the type of an expression Casts can be applied to change the type of primitive values
For example, forcing a double value into an int variable like this:
int circum = (int)(Math.PI * diameter);
Expressions
Expression is a sequence of operators, variables and literals that is evaluated to some value
int r = (150-20) / 2 + 5; // Expression for calculation of // the surface of the circle double surface = Math.PI * r * r; // Expression for calculation of // the perimeter of the circle double perimeter = 2 * Math.PI * r;
Statements
Statements are the main programming constructs Types of statements
Simple statements
The smallest programming instructions
Conditional Statements
The if, if-else statements:
if (boolean condition) { statement or block; }
If Statement Example
public static void main(String[] args) { int radius = 5; double surface = Math.PI * radius * radius; if (surface > 100) { System.out.println("The circle is too big!"); } else if (surface > 50) { System.out.println( "The circle has acceptable size!"); } else { System.out.println( "The circle is too small!"); } }
Conditional Statements
The switch statement
switch (expression) { case constant1: statements; break; case constant2: statements; break; default: statements; break; }
Looping Statements
The for statement:
for (init_expr; boolean testexpr; alter_expr) { statement or block; }
Example:
for (int i = 0; i < 10; i++) { System.out.println("i=" + i); } System.out.println("Finished!")
Looping Statements
The enhanced for statement:
for (Type variable : some collection) { statement or block; }
Example:
public static void main(String[] args) { String[] towns = new String[] { "Sofia", "Plovdiv", "Varna" }; for (String town : towns) { System.out.println(town); } }
Looping Statements
The while loop:
while (boolean condition) { statement or block; }
Examples:
int i=100; while (i>0) { System.out.println("i=" + i); i--; } while (true) { // This is an infinite loop }
Looping Statements
The do/while loop:
do { statement or block; } while (boolean condition);
Example:
public static void main(String[] args) { int counter=100; do { System.out.println("counter=" + counter); counter = counter - 5; } while (counter>=0); }
Comments
Three permissible styles of comment in a Java technology program are:
// comment on one line /* comment on one or more lines */
Console Input/Output
The input/output from the console is done through 3 standard streams
System.in the standard input System.out the standard output System.err the standard error output
System.out.println(...)
Like print(...) but moves to the next line
System.out.print(3.14159); System.out.println("Welcome to Java"); int i=5; System.out.println("i=" + i);
next() String
Reads a single word delimited by whitespace
nextLong() long
nextFloat() float
Reads a float value. Throws InputMismatchException on error
nextDouble() double
Scanner Example
import java.util.Scanner;
public class ScannerDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in);
// Get the first input System.out.print("What is your name? "); String name = console.nextLine();
// Get the second input System.out.print("How old are you? "); int age = console.nextInt(); // Display output on the console System.out.println("Hello, " + name + ". " + "Next year, you'll be " + (age + 1));
Formatting Output
System.out.printf(<format>, <values>)
Creating Arrays
To create and use an array, follow three steps: 1. Declaration 2. Construction 3. Initialization
4. Access to Elements
Array Declaration
Declaration tells the compiler the arrays name and what type its elements will be For example:
int[] ints; Dimensions[] dims; float[][] twoDimensions;
The square brackets can come before or after the array variable name:
int ints[];
Array Construction
The declaration does not specify the size of an array
Size is specified at runtime, when the array is allocated via the new keyword For example:
int[] ints; // Declaration ints = new int[25]; // Construction
Array Initialization
When an array is constructed, its elements are automatically initialized to their default values
These defaults are the same as for object member variables Numerical elements are initialized to 0 Non-numeric elements are initialized to 0like values, as shown in the next slide
Elements Initialization
Element Type byte int float char object reference short long double boolean Initial Value 0 0 0.0f \u0000 null 0 0L 0.0d false
The array size is inferred from the number of elements within the curly braces
Access to Elements
Accessing array elements:
int[] arr = new int[10]; arr[3] = 5; // Writing element int value = arr[3]; // Reading element
Arrays Example
// Finding the smallest and largest // elements in an array int[] values = {3,2,4,5,6,12,4,5,7}; int min = values[0]; int max = values[0]; for (int i=1; i<values.length; i++) { if (values[i] < min) { min = values[i]; } else if (values[i] > max) { max = values[i]; } } System.out.printf("MIN=%d\n", min); System.out.printf("MAX=%d\n", max);
Multi-dimensional Arrays
Multidimensional arrays in Java are actually arrays of arrays Defining matrix:
int[][] matrix = new int[3][4];
Multi-dimensional Arrays
Consider this declaration plus initialization:
int[][] myInts = new int[3][4];
Its natural to assume that the myInts contains 12 ints and to imagine them as organized into rows and columns, as shown:
WRONG!
Multi-dimensional Arrays
CORRECT!
Multi-dimensional Arrays
The subordinate arrays in a multidimension array dont have to all be the same length Such an array may be created like this:
int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94}, {2001, 2002} };
Questions?
Exercises
1. Write an expression that checks if given integer is odd or even. 2. Write a boolean expression that for given integer checks if it can be divided (without remainder) by 7 and 5. 3. Write an expression that checks if a given integer has 7 for its third digit (right-to-left). 4. Write a boolean expression for finding if the bit 3 of a given integer is 1 or 0. 5. Write a program that for a given width and height of a rectangle, outputs the values of the its surface and perimeter.
Exercises
6. Write a program that asks the user for a fourdigit number abcd and:
1. 2. 3. 4. Calculates the sum of its digits Prints its digits in reverse order: dcba Puts the last digit in at the front: dabc Changes the position of the second and third digits: acbd
7. Write an expression that checks if a given number n (n 100) is a prime number. 8. Write a boolean expression that returns true if the bit at position p in a given integer v is 1. Example: if v=5 and p=1, return false.
Exercises
9. Write a program that reads 3 integer numbers from the console and prints their sum. 10.Write a program that reads the radius r of a circle and prints its perimeter and area.
11.A company has name, address, phone number, fax number, Web site and manager. The manager has first name, last name and a phone number. Write a program that reads the information about a company and its manager and prints it on the console.
Exercises
12.Write a program that reads from the console two integer numbers and prints how many numbers exist between them, such that the reminder of the division by 5 is 0.
13.Write a program that gets two numbers from the console and prints the greater of them. Dont use if statements.
14.Write a program that reads 5 numbers and prints the greatest of them. 15.Write a program that reads 5 numbers and prints their sum.
Exercises
16.Write an if statement that examines two integer variables and exchanges their values if the first one is greater than the second one. 17.Write a program that shows the sign (+ or -) of the product of three real numbers without calculating it. Use sequence of if statements. 18.Write a program that finds the biggest of three integers using nested if statements. 19.Write a program that sorts 3 real values in descending order using nested if statements.
Exercises
20.Write program that for a given digit (0-9) entered as input prints the name of that digit (in Bulgarian). Use a switch statement.