Introduction to-programming

96
Introduction to Introduction to Java Programming Java Programming

description

Introduction to programming with Java - types and variables, conditional statements, loops, arrays

Transcript of Introduction to-programming

Page 1: Introduction to-programming

Introduction to Java Introduction to Java ProgrammingProgramming

Page 2: Introduction to-programming

ContentsContents

• The Structure of Java ProgramsThe Structure of Java Programs

• Keywords and IdentifiersKeywords and Identifiers

• Data TypesData Types

• Integral, Textual, Floating-PointIntegral, Textual, Floating-Point

• EnumerationsEnumerations

• Variables, Declarations, Assignments, Variables, Declarations, Assignments, OperatorsOperators

Page 3: Introduction to-programming

ContentsContents

• Expressions and StatementsExpressions and Statements

• Logical StatementsLogical Statements

• Loop StatementsLoop Statements

• Console Input and OutputConsole Input and Output

• Arrays and Array ManipulationArrays and Array Manipulation

• Using the Java API DocumentationUsing the Java API Documentation

Page 4: Introduction to-programming

Programming in JavaProgramming in Java

Page 5: Introduction to-programming

The Java APIThe Java API

• A set of runtime librariesA set of runtime libraries

• Available on Available on anyany JVM JVM

• Provide platform-independent standardProvide platform-independent standard

• Classes and interfacesClasses and interfaces

• SecuritySecurity

• Platform independence difficultiesPlatform independence difficulties

• Implementation is specific to the host Implementation is specific to the host platformplatform

Page 6: Introduction to-programming

What is Java API What is Java API Documentation?Documentation?

• Java documentation is HTML basedJava documentation is HTML based

• Also called "Also called "Java Platform Standard Edition Java Platform Standard Edition API SpecificationAPI Specification""

• Complete documentation of all standard Complete documentation of all standard classes and methodsclasses and methods

• Descriptions of all the functionalityDescriptions of all the functionality

• Links to related articlesLinks to related articles

• Use local copy or the Web version from Use local copy or the Web version from http://java.sun.com/javase/6/docs/api/

Page 7: Introduction to-programming

Java API DocumentationJava API Documentation

Page 8: Introduction to-programming

A Java ProgramA Java Program

Java methods (Java API)

Java Program

native methods (dynamic libraries)

host operating system

Page 9: Introduction to-programming

The Java Programming The Java Programming LanguageLanguage

• Quite general-purposeQuite general-purpose• Boosts developer productivityBoosts developer productivity• Combines proven techniquesCombines proven techniques• Software technologiesSoftware technologies

• Object-orientationObject-orientation

• Multi-threadingMulti-threading

• Structured error-handlingStructured error-handling

• Garbage collectionGarbage collection

• Dynamic linking and extensionDynamic linking and extension

Page 10: Introduction to-programming

Writing Java ProgramsWriting Java Programs

• Write custom source codeWrite custom source code

• In the Java programming languageIn the Java programming language

• Using the Java APIUsing the Java API

• Compile the source codeCompile the source code

• Using the “Using the “javacjavac” compiler command” compiler command

• Compiles to bytecodesCompiles to bytecodes

• Run the compiled codeRun the compiled code

• Using the “Using the “javajava” launcher command” launcher command

Page 11: Introduction to-programming

Java Program – ExampleJava Program – Example

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

HelloJava.javaHelloJava.java

javac HelloJava.javajavac HelloJava.java

java –cp . HelloJavajava –cp . HelloJava

Hello, Java!Hello, Java!

Page 12: Introduction to-programming

Typical ErrorsTypical Errors

• Compile-Time ErrorsCompile-Time Errors

• javac: Command not foundjavac: Command not found

• HelloJava.java:10: Method HelloJava.java:10: Method printl(java.lang.String) not found in class printl(java.lang.String) not found in class java.io.PrintStreamjava.io.PrintStream

• HelloJava.java:4: Public class HelloJava HelloJava.java:4: Public class HelloJava must be defined in a file called must be defined in a file called "HelloJava.java"."HelloJava.java".

Page 13: Introduction to-programming

Typical ErrorsTypical Errors

• Runtime ErrorsRuntime Errors

• Can’t find class HelloJavaCan’t find class HelloJava

• Exception in thread "main" Exception in thread "main" java.lang.NoClassDefFoundError: java.lang.NoClassDefFoundError: HelloJava/classHelloJava/class

Page 14: Introduction to-programming

Structure of Java ProgramsStructure of Java Programs

Page 15: Introduction to-programming

The Source File ContentsThe Source File Contents

• Java source code files can have tJava source code files can have three "top-hree "top-level" elements:level" elements:

• An optional package declarationAn optional package declaration

• Any number of import statementsAny number of import statements

• Class and interface declarationsClass and interface declarations

package jeecourse.example;package jeecourse.example;

import java.io.*;import java.io.*;

public class SomeClass {public class SomeClass { // ...// ...}}

Page 16: Introduction to-programming

Classes and PackagesClasses and Packages

• Classes are the main program unit in JavaClasses are the main program unit in Java

• Contain the source code of the program Contain the source code of the program logiclogic

• Can define fieldsCan define fields

• Can contain methods (subprograms)Can contain methods (subprograms)

• Packages are containers for classesPackages are containers for classes

• Can be nested hierarchicallyCan be nested hierarchically

• Each package can contain multiple classesEach package can contain multiple classes

Page 17: Introduction to-programming

Important Java PackagesImportant Java Packages

• Important packages within the Java class Important packages within the Java class library are:library are:

• java.langjava.lang

• java.utiljava.util

• java.iojava.io

• java.textjava.text

• java.awtjava.awt

• java.netjava.net

• java.appletjava.applet

Page 18: Introduction to-programming

Java ProgramsJava Programs

• Java programs are sets of class definitionsJava programs are sets of class definitions

• The The main()main() method is the entry point for method is the entry point for standalone Java applicationsstandalone Java applications

• The signature forThe signature for main()main() is is::

• TThe name he name argsargs is purely arbitrary: is purely arbitrary:

• AAny legal identifier may be used, providedny legal identifier may be used, provided the the array is a single-dimension array of String array is a single-dimension array of String objectsobjects

public static void main(String[] args)public static void main(String[] args)

Page 19: Introduction to-programming

Programs, Classes, and Programs, Classes, and Packages – ExamplePackages – Example

package jeecourse.example;package jeecourse.example;

import java.io.*;import java.io.*;

public class SomeClass {public class SomeClass {

private static int mValue = 5;private static int mValue = 5;

public static void printValue() {public static void printValue() { System.out.println("mValue = " + mValue);System.out.println("mValue = " + mValue); }}

public static void main(String[] args) {public static void main(String[] args) { System.out.println("Some Class");System.out.println("Some Class"); printValue();printValue(); }}}}

Page 20: Introduction to-programming

Keywords, Identifiers, Data Keywords, Identifiers, Data TypesTypes

Page 21: Introduction to-programming

KeywordsKeywords

• A keyword is a word whose meaning is A keyword is a word whose meaning is defined by the programming languagedefined by the programming language

• Anyone who claims to be competent in a Anyone who claims to be competent in a language must at the very least be familiar language must at the very least be familiar with that language’s keywordswith that language’s keywords

• Java’s keywords and other special-meaning Java’s keywords and other special-meaning words are listed in the next slidewords are listed in the next slide

Page 22: Introduction to-programming

Java Language KeywordsJava Language Keywords

abstract continue for new switch

assert  default goto  package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum  instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp  volatile

const  float native super while

Page 23: Introduction to-programming

Reserved WordsReserved Words

• You may notice You may notice nullnull, , truetrue, and , and falsefalse do do not appear anywhere on the keywords listnot appear anywhere on the keywords list

• truetrue, , falsefalse, and , and nullnull are not keywords are not keywords but they are reserved wordsbut they are reserved words

• You cannot use them as names in your You cannot use them as names in your programs eitherprograms either

Page 24: Introduction to-programming

IdentifiersIdentifiers

• Names given to a variable, method, field, class, Names given to a variable, method, field, class, interface, etc.interface, etc.

• Can start with a letter, underscore(_), or dollar Can start with a letter, underscore(_), or dollar sign($)sign($)

• Can contain letters, $, _, and digitsCan contain letters, $, _, and digits

• Case sensitiveCase sensitive

• Have no maximum lengthHave no maximum length

• Examples:Examples:

• userName, $app_name, __test, value, userName, $app_name, __test, value, totalRevenue, location$totalRevenue, location$

Page 25: Introduction to-programming

Primitive Data TypesPrimitive Data Types

• A A primitiveprimitive is a simple non-object data type is a simple non-object data type that represents a single valuethat represents a single value

• Java’s primitive data types are:Java’s primitive data types are:

• booleanboolean

• charchar

• bytebyte, , shortshort, , intint, , longlong

• floatfloat, , doubledouble

Page 26: Introduction to-programming

Primitive Data TypesPrimitive Data Types

Type Effective Size (bits)

byte 8

short 16

int 32

long 64

float 32

double 64

char 16

• Variables of type Variables of type booleanboolean may take may take only the values only the values truetrue or or falsefalse

• Their representation Their representation size might varysize might vary

Page 27: Introduction to-programming

Boolean TypeBoolean Type

• The boolean data type has two literals, true The boolean data type has two literals, true and falseand false

• For example, the statement:For example, the statement:

• boolean truth = true;boolean truth = true;

• declares the variable truth as boolean type declares the variable truth as boolean type and assigns it a value of trueand assigns it a value of true

Page 28: Introduction to-programming

Textual Types: Textual Types: charchar

• Represents a 16-bit Unicode characterRepresents a 16-bit Unicode character• Must have its literal enclosed in single Must have its literal enclosed in single

quotes(’ ’)quotes(’ ’)• Uses the following notations:Uses the following notations:

• 'a' – The letter 'a' – The letter aa

• '\t' – A tab'\t' – A tab

• '\n' – A new line character'\n' – A new line character

• '\u????' – A specific Unicode '\u????' – A specific Unicode character, ????, is replaced with exactly character, ????, is replaced with exactly four hexadecimal digits, e.g. '\u1A4F'four hexadecimal digits, e.g. '\u1A4F'

Page 29: Introduction to-programming

Integral Types: Integral Types: bytebyte, , shortshort, , intint, and , and longlong

• Uses three forms – decimal, octal, or Uses three forms – decimal, octal, or hexadecimal, e. g.hexadecimal, e. g.• 22 – The decimal value is two – The decimal value is two

• 077077 – The leading zero indicates an octal – The leading zero indicates an octal valuevalue

• 0xBAAC0xBAAC – The leading 0x indicates a – The leading 0x indicates a hexadecimal valuehexadecimal value

• The default integer values are The default integer values are intint

• Defines long by using the letter Defines long by using the letter LL or or ll::long value = 1234L;long value = 1234L;

Page 30: Introduction to-programming

Ranges of the Integral Ranges of the Integral Primitive TypesPrimitive Types

Type Size Minimum Maximum

byte 8 bits -27 27 – 1

short 16 bits -215 215 – 1

int 32 bits -231 231 – 1

long 64 bits -263 263 – 1

Page 31: Introduction to-programming

Floating Point Types: Floating Point Types: floatfloat and and doubledouble

• Default is doubleDefault is double• Floating point literal includes either a decimal Floating point literal includes either a decimal

point or one of the following:point or one of the following:• E or e (add exponential value)E or e (add exponential value)• F or f (float)F or f (float)• D or d (double)D or d (double)

• Examples:Examples:• 3.14 – A simple floating-point value (a double)3.14 – A simple floating-point value (a double)• 6.02E23 – A large floating-point value6.02E23 – A large floating-point value• 2.718F – A simple float size value2.718F – A simple float size value• 123.4E+306D – A large double value with 123.4E+306D – A large double value with

redundant redundant DD

Page 32: Introduction to-programming

Ranges of the Floating-Ranges of the Floating-Point Primitive TypesPoint Primitive Types

Type Size Minimum Maximum

float 32 bits +/- 1.40-45 +/- 3.40+38

double 64 bits +/- 4.94-324 +/- 1.79+308

char 16 bits 0 216 - 1

Page 33: Introduction to-programming

Non-numeric Floating-Point Non-numeric Floating-Point ValuesValues

• Float.NaNFloat.NaN

• Float.NEGATIVE_INFINITYFloat.NEGATIVE_INFINITY

• Float.POSITIVE_INFINITYFloat.POSITIVE_INFINITY

• Double.NaNDouble.NaN

• Double.NEGATIVE_INFINITYDouble.NEGATIVE_INFINITY

• Double.POSITIVE_INFINITYDouble.POSITIVE_INFINITY

Page 34: Introduction to-programming

Textual Types: StringTextual Types: String

• Is not a primitive data typeIs not a primitive data type

• It is a classIt is a class

• Has its literal enclosed in double quotes (" ")Has its literal enclosed in double quotes (" ")

• Example:Example:

• Can be used as follows:Can be used as follows:String greeting = "Good Morning !! \n";String greeting = "Good Morning !! \n";String errorMsg = "Record Not Found!";String errorMsg = "Record Not Found!";

"The quick brown fox jumps over the lazy dog.""The quick brown fox jumps over the lazy dog."

Page 35: Introduction to-programming

Values and ObjectsValues and Objects

• Primitive Data TypesPrimitive Data Types• Are value typesAre value types

• Contain directly their valuesContain directly their values

• Examples: Examples: intint, , floatfloat, , charchar, , booleanboolean

• ObjectsObjects• Are reference typesAre reference types

• Contain a pointer (memory address) of their Contain a pointer (memory address) of their valuesvalues

• Examples: Examples: StringString, , ObjectObject, , DateDate

Page 36: Introduction to-programming

Values vs. ObjectsValues vs. Objects

• Consider the following code fragment:Consider the following code fragment:

• Two variables refer to a single object:Two variables refer to a single object:

int x = 7;int x = 7;int y = x;int y = x;String s = "Hello";String s = "Hello";String t = s;String t = s;

77xx

77yy

0x012345670x01234567ss

0x012345670x01234567tt

"Hello""Hello" 0x012345670x01234567

Heap (dynamic memory)Heap (dynamic memory)

Page 37: Introduction to-programming

Enumerations (enums)Enumerations (enums)

• Enumerations are special types thatEnumerations are special types that

• Get values from a given set of constantsGet values from a given set of constants

• Are strongly typedAre strongly typed

• Compiled to classes that inherit Compiled to classes that inherit java.lang.Enumjava.lang.Enum

public enum Color {public enum Color { WHITE, RED, GREEN, BLUE, BLACKWHITE, RED, GREEN, BLUE, BLACK}}......Color c = Color.RED;Color c = Color.RED;

Page 38: Introduction to-programming

Enumerations (enums)Enumerations (enums)

• Allow using Allow using ifif and and switchswitch::

switch (color) {switch (color) { case WHITE: case WHITE: System.out.println("бяло"); System.out.println("бяло"); break;break; case RED: case RED: System.out.println("червено"); System.out.println("червено"); break;break; ......}}if (color == Color.RED) {if (color == Color.RED) { ......}}

Page 39: Introduction to-programming

Variables, Declarations, Variables, Declarations, Assignments, OperatorsAssignments, Operators

Page 40: Introduction to-programming

Variables, Declarations, andVariables, Declarations, andAssignmentsAssignments

• Variables are names places in the memory Variables are names places in the memory that contain some valuethat contain some value

• Variables have a type (int, float, String, ...)Variables have a type (int, float, String, ...)

• Variables should be declared before useVariables should be declared before use

• Variables can be assignedVariables can be assigned

• Examples:Examples:

int i; // declare variableint i; // declare variableint value = 5; // declare and assign variableint value = 5; // declare and assign variablei = 25; // assign a value to a variable that is i = 25; // assign a value to a variable that is already declaredalready declared

Page 41: Introduction to-programming

Variables, Declarations, andVariables, Declarations, andAssignments – Examples Assignments – Examples

public class Assignments {public class Assignments { public static void main(String args []) {public static void main(String args []) { int x, y; // declare int variablesint x, y; // declare int variables float z = 3.414f; // declare and assign floatfloat z = 3.414f; // declare and assign float double w = 3.1415; // declare and assign doubledouble w = 3.1415; // declare and assign double boolean b = true; // declare and assign booleanboolean b = true; // declare and assign boolean char ch; // declare character variablechar ch; // declare character variable String str; // declare String variableString str; // declare String variable String s = "bye"; // declare and assign StringString s = "bye"; // declare and assign String ch = 'A'; // assign a value to char variablech = 'A'; // assign a value to char variable str = "Hi out there!"; // assign value to Stringstr = "Hi out there!"; // assign value to String x = 6; // assign value to int variablex = 6; // assign value to int variable y = 1000; // assign values to int variabley = 1000; // assign values to int variable ...... }}}}

Page 42: Introduction to-programming

Variables and ScopeVariables and Scope

• Local variables are:Local variables are:

• Variables that are defined inside a method Variables that are defined inside a method and are called and are called locallocal, , automaticautomatic, , temporary,temporary, or or stackstack variables variables

• Created when the method is executed and Created when the method is executed and destroyed when the method is exiteddestroyed when the method is exited

• Variables that must be initialized before they Variables that must be initialized before they are used or compile-time errors will occurare used or compile-time errors will occur

Page 43: Introduction to-programming

OperatorsOperators

Category Operators

Unary ++ -- + - ! ~ (type)

Arithmetic * / %

+ -

Shift << >> >>>

Comparison < <= > >= instanceof

== !=

Bitwise & ^ |

Short-circuit && ||

Conditional ? :

Assignment = op=

Page 44: Introduction to-programming

The Ordinal Comparisons The Ordinal Comparisons Operators: <, <=, >, and >=Operators: <, <=, >, and >=

• The ordinal comparison operators are:The ordinal comparison operators are:

• Less than: <Less than: <

• Less than or equal to: <=Less than or equal to: <=

• Greater than: >Greater than: >

• Greater than or equal to: >=Greater than or equal to: >=

Page 45: Introduction to-programming

The Ordinal Comparisons The Ordinal Comparisons Operators – ExampleOperators – Example

• int p = 9;int p = 9;

• int q = 65;int q = 65;

• int r = -12;int r = -12;

• float f = 9.0F;float f = 9.0F;

• char c = ‘A’;char c = ‘A’;

• p < q p < q true true

• f < q f < q true true

• f <= c f <= c true true

• c > r c > r true true

• c >= q c >= q true true

Page 46: Introduction to-programming

Short-Circuit Logical Short-Circuit Logical OperatorsOperators

• The operators are && (The operators are && (ANDAND) and || () and || (OROR))

• These operators can be used as follows:These operators can be used as follows:

MyDate d = null;MyDate d = null;

if ((d != null) && (d.day() > 31)) {if ((d != null) && (d.day() > 31)) { // Do something// Do something}}

boolean goodDay = (d == null) || ((d != null) && boolean goodDay = (d == null) || ((d != null) && (d.day() >= 12));(d.day() >= 12));

Page 47: Introduction to-programming

String Concatenation with +String Concatenation with +

• The + operator:The + operator:• Performs String concatenationPerforms String concatenation

• Produces a new String as a result:Produces a new String as a result:

• First argument must be a String objectFirst argument must be a String object• Non-strings are converted to String objects Non-strings are converted to String objects

automaticallyautomatically

String salutation = "Dr. ";String salutation = "Dr. ";String name = "Pete " + "Seymour"; String name = "Pete " + "Seymour"; System.out.println(salutation + name + 5);System.out.println(salutation + name + 5);

Page 48: Introduction to-programming

The Unary OperatorsThe Unary Operators

• Unary operators take only a single operand Unary operators take only a single operand and work just on thatand work just on that

• Java provides seven unary operators:Java provides seven unary operators:

• The increment and decrement operators: ++ The increment and decrement operators: ++ and --and --

• The unary plus and minus operators: + and -The unary plus and minus operators: + and -

• The bitwise inversion operator: ~The bitwise inversion operator: ~

• The boolean complement operator: !The boolean complement operator: !

• The cast operator: ()The cast operator: ()

Page 49: Introduction to-programming

The Cast Operator: (type)The Cast Operator: (type)

• Implicit type conversions are possible when Implicit type conversions are possible when no information can be lostno information can be lost

• E.g. converting E.g. converting intint longlong

• Casting is used for explicit conversion of the Casting is used for explicit conversion of the type of an expressiontype of an expression

• Casts can be applied to change the type of Casts can be applied to change the type of primitive valuesprimitive values

• For example, forcing a For example, forcing a doubledouble value into an value into an intint variable like this: variable like this:

int circum = (int)(Math.PI * diameter);int circum = (int)(Math.PI * diameter);

Page 50: Introduction to-programming

The Multiplication and The Multiplication and Division Operators: * and /Division Operators: * and /

• The * and / operators perform multiplication The * and / operators perform multiplication and division on all primitive numeric types and division on all primitive numeric types and charand char

• Integer division will generate an Integer division will generate an ArithmeticExceptionArithmeticException when attempting to when attempting to divide by zerodivide by zero

int a = 5;int a = 5;int value = a * 10;int value = a * 10;

Page 51: Introduction to-programming

The Bitwise OperatorsThe Bitwise Operators

• The bitwise operators: &, ^, and | provide The bitwise operators: &, ^, and | provide bitwise AND, eXclusive-OR (XOR), and OR bitwise AND, eXclusive-OR (XOR), and OR operations, respectivelyoperations, respectively

• They are applicable to integral typesThey are applicable to integral types

int first = 100;int first = 100;int second = 200;int second = 200;

int xor = first ^ second;int xor = first ^ second;

int and = first & second;int and = first & second;

Page 52: Introduction to-programming

Operator Evaluation OrderOperator Evaluation Order

• In Java, the order of evaluation of operands in In Java, the order of evaluation of operands in an expression is fixed – an expression is fixed – left to rightleft to right

• Consider this code fragment:Consider this code fragment:

• In this case, it might be unclear which element In this case, it might be unclear which element of the array is modified:of the array is modified:

• Which value of Which value of b b is used to select the is used to select the array element, array element, 0 0 or or 11

int[] a = {4, 4};int[] a = {4, 4};int b = 1;int b = 1;a[b] = b = 0;a[b] = b = 0;

Page 53: Introduction to-programming

Expressions and StatementsExpressions and Statements

Page 54: Introduction to-programming

ExpressionsExpressions

• Expression is a sequence of operators, Expression is a sequence of operators, variables and literals that is evaluated to variables and literals that is evaluated to some valuesome value

int r = (150-20) / 2 + 5;int r = (150-20) / 2 + 5;

// Expression for calculation of// Expression for calculation of// the surface of the circle// the surface of the circledouble surface = Math.PI * r * r;double surface = Math.PI * r * r;

// Expression for calculation of// Expression for calculation of// the perimeter of the circle// the perimeter of the circledouble perimeter = 2 * Math.PI * r;double perimeter = 2 * Math.PI * r;

Page 55: Introduction to-programming

StatementsStatements

• Statements are the main programming Statements are the main programming constructsconstructs

• Types of statementsTypes of statements

• Simple statementsSimple statements

• The smallest programming instructionsThe smallest programming instructions

• Block statements – Block statements – { ...{ ... }}

• Conditional statements (Conditional statements (ifif, , if-elseif-else, , switchswitch))

• Loop statements (Loop statements (forfor, , whilewhile, , do/whiledo/while))

Page 56: Introduction to-programming

Statements and BlocksStatements and Blocks

• A A statementstatement is a single line of code is a single line of code terminated by a semicolon(;)terminated by a semicolon(;)

• A A block block is a collection of statements is a collection of statements bounded by opening and closing braces:bounded by opening and closing braces:

• You can nest block statementsYou can nest block statements

salary = days * daySalary;salary = days * daySalary;

{{ x = x + 1;x = x + 1; y = y + 1;y = y + 1;}}

Page 57: Introduction to-programming

Conditional Statements Conditional Statements

• The The ifif, , if-elseif-else statements: statements:

if (boolean condition) {if (boolean condition) { statement or block;statement or block;}}

if (boolean condition) {if (boolean condition) { statement or block;statement or block;} else {} else { statement or block;statement or block;}}

Page 58: Introduction to-programming

If Statement – ExampleIf Statement – Example

public static void main(String[] args) {public static void main(String[] args) { int radius = 5;int radius = 5; double surface = Math.PI * radius * radius;double surface = Math.PI * radius * radius; if (surface > 100) {if (surface > 100) { System.out.println("The circle is too big!");System.out.println("The circle is too big!"); } else if (surface > 50) {} else if (surface > 50) { System.out.println(System.out.println( "The circle has acceptable size!");"The circle has acceptable size!"); } else {} else { System.out.println(System.out.println( "The circle is too small!");"The circle is too small!"); }}}}

Page 59: Introduction to-programming

Conditional StatementsConditional Statements

• The The switchswitch statement statement

switch (expression) {switch (expression) { case constant1:case constant1: statements;statements; break;break; case constant2:case constant2: statements;statements; break;break; default:default: statements;statements; break;break;}}

Page 60: Introduction to-programming

The The switchswitch Statement – Statement – ExampleExample

int dayOfWeek = 3;int dayOfWeek = 3;switch (dayOfWeek) {switch (dayOfWeek) { case 1:case 1: System.out.println("Monday");System.out.println("Monday"); break;break; case 2:case 2: System.out.println("Tuesday");System.out.println("Tuesday"); break;break; ...... default:default: System.out.println("Invalid day!");System.out.println("Invalid day!"); break;break;}}

Page 61: Introduction to-programming

Looping StatementsLooping Statements

• The The forfor statement: statement:

• Example:Example:

for (init_expr; boolean testexpr; alter_expr) {for (init_expr; boolean testexpr; alter_expr) { statement or block;statement or block;}}

for (int i = 0; i < 10; i++) {for (int i = 0; i < 10; i++) { System.out.println("i=" + i);System.out.println("i=" + i);}}System.out.println("System.out.println("FinishedFinished!")!")

Page 62: Introduction to-programming

Looping StatementsLooping Statements

• The enhanced The enhanced forfor statement: statement:

• Example:Example:

for (for (Type variable : some collectionType variable : some collection) {) { statement or block;statement or block;}}

public static void main(String[] args) {public static void main(String[] args) { String[] towns = new String[] {String[] towns = new String[] { "Sofia", "Plovdiv", "Varna" };"Sofia", "Plovdiv", "Varna" }; for (String town : towns) {for (String town : towns) { System.out.println(town);System.out.println(town); }}}}

Page 63: Introduction to-programming

Looping StatementsLooping Statements

• The The whilewhile loop: loop:

• Examples:Examples:

while (boolean condition) {while (boolean condition) { statement or block;statement or block;}}

int i=100;int i=100;while (i>0) {while (i>0) { System.out.println("i=" + i);System.out.println("i=" + i); i--;i--;}}

while (true) {while (true) { // This is an infinite loop// This is an infinite loop}}

Page 64: Introduction to-programming

Looping StatementsLooping Statements

• The The do/whiledo/while loop: loop:

• Example:Example:

do {do { statement or block;statement or block;} while (boolean condition);} while (boolean condition);

public static void main(String[] args) {public static void main(String[] args) { int counter=100;int counter=100; do {do { System.out.println("counter=" + counter);System.out.println("counter=" + counter); counter = counter - 5;counter = counter - 5; } while (counter>=0);} while (counter>=0);}}

Page 65: Introduction to-programming

Special Loop Flow ControlSpecial Loop Flow Control

• Some special operators valid in loops:Some special operators valid in loops:

• break [label];break [label];

• continue [label]; continue [label];

• label: statement; // Where statement label: statement; // Where statement should be a loopshould be a loop

• Example (breaking a loop):Example (breaking a loop):

for (int counter=100; counter>=0; counter-=5) {for (int counter=100; counter>=0; counter-=5) { System.out.println("counter=" + counter);System.out.println("counter=" + counter); if (counter == 50)if (counter == 50) break;break;}}

Page 66: Introduction to-programming

Special Loop Flow Control – Special Loop Flow Control – ExamplesExamples

• Example (continuing a loop):Example (continuing a loop):

for (int counter=100; counter>=0; counter-=5) {for (int counter=100; counter>=0; counter-=5) { if (counter == 50)if (counter == 50) { { continuecontinue;; }} System.out.println("counter=" + counter);System.out.println("counter=" + counter);}}

Page 67: Introduction to-programming

Special Loop Flow Control – Special Loop Flow Control – ExamplesExamples

• Example (breaking a loop with a label):Example (breaking a loop with a label):

outerLoop:outerLoop: for (int i=0; i<50; i++) {for (int i=0; i<50; i++) { for (int counter=100; counter>=0; counter-=5) {for (int counter=100; counter>=0; counter-=5) { System.out.println("counter=" + counter);System.out.println("counter=" + counter); if ((i==2) && (counter == 50))if ((i==2) && (counter == 50)) { { break outerLoop;break outerLoop; }} }} }}

Page 68: Introduction to-programming

CommentsComments

• Three permissible styles of comment in a Three permissible styles of comment in a Java technology program are:Java technology program are:

// comment on one line// comment on one line

/* comment on one/* comment on oneor more lines */or more lines */

/** documenting comment *//** documenting comment */

Page 69: Introduction to-programming

Console Input and OutputConsole Input and Output

Page 70: Introduction to-programming

Console Input/OutputConsole Input/Output

• The input/output from the console is done The input/output from the console is done through 3 standard streamsthrough 3 standard streams

• System.inSystem.in – the standard input – the standard input

• System.outSystem.out – the standard output – the standard output

• System.errSystem.err – the standard error output – the standard error output

• To facilitate some operations additional To facilitate some operations additional classes should be involvedclasses should be involved

• ScannerScanner

• BufferedReaderBufferedReader, , InputStreamReaderInputStreamReader

Page 71: Introduction to-programming

Printing to the ConsolePrinting to the Console

• System.out.print(...)System.out.print(...)

• Can take as input different typesCan take as input different types

• StringString, , intint, , floatfloat, , ObjectObject, ..., ...

• Non-string types are converted to Non-string types are converted to StringString

• System.out.println(...)System.out.println(...)

• Like Like print(...)print(...) but moves to the next line but moves to the next line

System.out.print(3.14159);System.out.print(3.14159);System.out.println("Welcome to Java");System.out.println("Welcome to Java");int i=5;int i=5;System.out.println("i=" + i);System.out.println("i=" + i);

Page 72: Introduction to-programming

Reading from the ConsoleReading from the Console

• First construct a First construct a ScannerScanner that is attached to that is attached to the “standard input stream” the “standard input stream” System.inSystem.in

• Then use various methods of the Then use various methods of the ScannerScanner class to read inputclass to read input

• nextLine() nextLine() String String

• Reads a line of inputReads a line of input

• next() next() String String

• Reads a single word delimited by whitespaceReads a single word delimited by whitespace

Scanner in = new Scanner(System.in);Scanner in = new Scanner(System.in);

Page 73: Introduction to-programming

Reading from the ConsoleReading from the Console

• ScannerScanner – more methods – more methods

• nextInt() nextInt() int int

• Reads an Reads an intint value. Throws value. Throws InputMismatchExceptionInputMismatchException on error on error

• nextLong() nextLong() long long

• nextFloat() nextFloat() float float

• Reads aReads a floatfloat value. Throws value. Throws InputMismatchExceptionInputMismatchException on error on error

• nextDouble() nextDouble() double double

Page 74: Introduction to-programming

Scanner – Example Scanner – Example

import java.util.Scanner;import java.util.Scanner;

public class ScannerDemo {public class ScannerDemo { public static void main(String[] args) {public static void main(String[] args) { Scanner console = new Scanner(System.in);Scanner console = new Scanner(System.in);

// Get the first input// Get the first input System.out.print("What is your name? ");System.out.print("What is your name? "); String name = console.nextLine();String name = console.nextLine(); // Get the second input// Get the second input System.out.print("How old are you? ");System.out.print("How old are you? "); int age = console.nextInt();int age = console.nextInt();

// Display output on the console// Display output on the console System.out.println("Hello, " + name + ". " + System.out.println("Hello, " + name + ". " + "Next year, you'll be " + (age + 1));"Next year, you'll be " + (age + 1)); }}}}

Page 75: Introduction to-programming

Formatting OutputFormatting Output

• System.out.printf(<format>, <values>)System.out.printf(<format>, <values>)

• Like the Like the printfprintf function in function in CC language language

• Some formatting patternsSome formatting patterns

• %s – Display as string%s – Display as string %f – Display as float %f – Display as float

• %d – Display as number %t – Display as date%d – Display as number %t – Display as date

* For more details see * For more details see java.util.Formatterjava.util.Formatter

String name = "Nakov";String name = "Nakov";int age = 25;int age = 25;System.out.printf(System.out.printf( "My name is %s.\nI am %d years old.","My name is %s.\nI am %d years old.", name, age);name, age);

Page 76: Introduction to-programming

Arrays and Array Arrays and Array ManipulationManipulation

Page 77: Introduction to-programming

Creating ArraysCreating Arrays

• To create and use an array, follow three To create and use an array, follow three steps:steps:

1. Declaration1. Declaration

2. Construction2. Construction

3. Initialization3. Initialization

4. Access to Elements4. Access to Elements

Page 78: Introduction to-programming

Array DeclarationArray Declaration

• Declaration tells the compiler the array’s Declaration tells the compiler the array’s name and what type its elements will bename and what type its elements will be

• For example:For example:

• The square brackets can come before or The square brackets can come before or after the array variable name:after the array variable name:

int[] ints;int[] ints;Dimensions[] dims;Dimensions[] dims;float[][] twoDimensions; float[][] twoDimensions;

int ints[];int ints[];

Page 79: Introduction to-programming

Array ConstructionArray Construction

• The declaration does not specify the size of The declaration does not specify the size of an arrayan array• Size is specified at runtime, when the array Size is specified at runtime, when the array

is allocated via the is allocated via the newnew keyword keyword

• For example:For example:

• Declaration and construction may be Declaration and construction may be performed in a single line:performed in a single line:

int[] ints; // Declaration int[] ints; // Declaration ints = new int[25]; // Constructionints = new int[25]; // Construction

int[] ints = new int[25];int[] ints = new int[25];

Page 80: Introduction to-programming

Array InitializationArray Initialization

• When an array is constructed, its elements When an array is constructed, its elements are automatically initialized to their default are automatically initialized to their default valuesvalues

• These defaults are the same as for object These defaults are the same as for object member variablesmember variables

• Numerical elements are initialized to 0Numerical elements are initialized to 0

• Non-numeric elements are initialized to 0-Non-numeric elements are initialized to 0-like values, as shown in the next slidelike values, as shown in the next slide

Page 81: Introduction to-programming

Elements InitializationElements Initialization

Element Type Initial Value

byte 0

int 0

float 0.0f

char ‘\u0000’

object reference null

short 0

long 0L

double 0.0d

boolean false

Page 82: Introduction to-programming

Array Elements InitializationArray Elements Initialization

• Initial values for the elements can be Initial values for the elements can be specified at the time of declaration and specified at the time of declaration and initialization:initialization:

• The array size is inferred from the number The array size is inferred from the number of elements within the curly bracesof elements within the curly braces

float[] diameters =float[] diameters = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};{1.1f, 2.2f, 3.3f, 4.4f, 5.5f};

Page 83: Introduction to-programming

Access to ElementsAccess to Elements

• Accessing array elements:Accessing array elements:

• Elements access is range checkedElements access is range checked

• Arrays has field Arrays has field lengthlength that contains their that contains their number of elementsnumber of elements

int[] arr = new int[10];int[] arr = new int[10];arr[3] = 5; // Writing elementarr[3] = 5; // Writing elementint value = arr[3]; // Reading elementint value = arr[3]; // Reading element

int[] arr = new int[10];int[] arr = new int[10];int value = arr[10];int value = arr[10];// ArrayIndexOutOfBoundsException// ArrayIndexOutOfBoundsException

Page 84: Introduction to-programming

Arrays – ExampleArrays – Example

// Finding the smallest and largest// Finding the smallest and largest// elements in an array// elements in an arrayint[] values = {3,2,4,5,6,12,4,5,7};int[] values = {3,2,4,5,6,12,4,5,7};int min = values[0];int min = values[0];int max = values[0];int max = values[0];for (int i=1; i<values.length; i++) {for (int i=1; i<values.length; i++) { if (values[i] < min) {if (values[i] < min) { min = values[i];min = values[i]; } else if (values[i] > max) {} else if (values[i] > max) { max = values[i];max = values[i]; }}}}System.out.printf("MIN=%d\n", min);System.out.printf("MIN=%d\n", min);System.out.printf("MAX=%d\n", max);System.out.printf("MAX=%d\n", max);

Page 85: Introduction to-programming

MMulti-dimensionulti-dimensionalal AArraysrrays

• Multidimensional arrays in Java are actually Multidimensional arrays in Java are actually arrays of arraysarrays of arrays

• Defining matrix:Defining matrix:

• Accessing matrix elements:Accessing matrix elements:

• Getting the number of rows/columns:Getting the number of rows/columns:

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

matrix[1][3] = 42;matrix[1][3] = 42;

int rows = matrix.length;int rows = matrix.length;int colsInFirstRow = matrix[0].length;int colsInFirstRow = matrix[0].length;

Page 86: Introduction to-programming

MMulti-dimensionulti-dimensionalal AArraysrrays

• Consider this declaration plus initialization:Consider this declaration plus initialization:

• It’s natural to assume that the It’s natural to assume that the myIntsmyInts contains 12 ints and to imagine them as contains 12 ints and to imagine them as organized intoorganized into rows and columns, as shownrows and columns, as shown::

WRONG!

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

Page 87: Introduction to-programming

MMulti-dimensionulti-dimensionalal AArraysrrays

• The right way to The right way to think about multi-think about multi-dimension arraysdimension arrays

CORRECT!

Page 88: Introduction to-programming

MMulti-dimensionulti-dimensionalal AArraysrrays

• The subordinate The subordinate arrays in a multi-arrays in a multi-dimension array don’t dimension array don’t have to all be the have to all be the same lengthsame length

• Such an array may be Such an array may be created like this:created like this:

int[][] myInts = { {1, 2, 3},int[][] myInts = { {1, 2, 3}, {91, 92, 93, 94},{91, 92, 93, 94}, {2001, 2002} };{2001, 2002} };

Page 89: Introduction to-programming

MMulti-dimensionulti-dimensionalal AArraysrrays – – ExampleExample

// Finding the sum of all positive// Finding the sum of all positive// cells from the matrix// cells from the matrixint[][] matrix = int[][] matrix = {{2,4,-3}, {{2,4,-3}, {8,-1,6}};{8,-1,6}};int sum = 0;int sum = 0;for (int row=0; row<matrix.length; row++) {for (int row=0; row<matrix.length; row++) { for (int col=0; col<matrix[row].length;for (int col=0; col<matrix[row].length; col++) {col++) { if (matrix[row][col] > 0) {if (matrix[row][col] > 0) { sum += matrix[row][col];sum += matrix[row][col]; }} }}}}System.out.println("Sum = " + sum);System.out.println("Sum = " + sum);

Page 90: Introduction to-programming

QuestionsQuestions??

Introduction to Java Introduction to Java Programming Programming

Page 91: Introduction to-programming

ExercisesExercises

1.1. Write an expression that checks if given integer Write an expression that checks if given integer is odd or even.is odd or even.

2.2. Write a boolean expression that for given Write a boolean expression that for given integer checks if it can be divided (without integer checks if it can be divided (without remainder) by 7 and 5.remainder) by 7 and 5.

3.3. Write an expression that checks if a given Write an expression that checks if a given integer has 7 for its third digit (right-to-left).integer has 7 for its third digit (right-to-left).

4.4. Write a boolean expression for finding if the bit Write a boolean expression for finding if the bit 3 of a given integer is 1 or 0.3 of a given integer is 1 or 0.

5.5. Write a program that for a given width and Write a program that for a given width and height of a rectangle, outputs the values of the height of a rectangle, outputs the values of the its surface and perimeter.its surface and perimeter.

Page 92: Introduction to-programming

ExercisesExercises

6.6. Write a program that asks the user for a four-Write a program that asks the user for a four-digit number digit number abcd and: and:

1.1. Calculates the sum of its digitsCalculates the sum of its digits

2.2. Prints its digits in reverse order: Prints its digits in reverse order: dcbadcba

3.3. Puts the last digit in at the front: Puts the last digit in at the front: dabcdabc

4.4. Changes the position of the second and third Changes the position of the second and third digits: digits: acbdacbd

7.7. Write an expression that checks if a given Write an expression that checks if a given number number nn ( (nn ≤ 100) is a prime number. ≤ 100) is a prime number.

8.8. Write a boolean expression that returns Write a boolean expression that returns truetrue if if the bit at position the bit at position pp in a given integer in a given integer vv is 1. is 1. Example: if v=5 and p=1, return false. Example: if v=5 and p=1, return false.

Page 93: Introduction to-programming

ExercisesExercises

9.9. Write a program that reads 3 integer numbers Write a program that reads 3 integer numbers from the console and prints their sum.from the console and prints their sum.

10.10.Write a program that reads the radius Write a program that reads the radius rr of a of a circle and prints its perimeter and area.circle and prints its perimeter and area.

11.11.A company has name, address, phone number, A company has name, address, phone number, fax number, Web site and manager. The fax number, Web site and manager. The manager has first name, last name and a phone manager has first name, last name and a phone number. Write a program that reads the number. Write a program that reads the information about a company and its manager information about a company and its manager and prints it on the console.and prints it on the console.

Page 94: Introduction to-programming

ExercisesExercises

12.12.Write a program that reads from the console Write a program that reads from the console two integer numbers and prints how many two integer numbers and prints how many numbers exist between them, such that the numbers exist between them, such that the reminder of the division by 5 is 0.reminder of the division by 5 is 0.

13.13.Write a program that gets two numbers from Write a program that gets two numbers from the console and prints the greater of them. the console and prints the greater of them. Don’t use Don’t use if if statements.statements.

14.14.Write a program that reads 5 numbers and Write a program that reads 5 numbers and prints the greatest of them.prints the greatest of them.

15.15.Write a program that reads 5 numbers and Write a program that reads 5 numbers and prints their sum.prints their sum.

Page 95: Introduction to-programming

ExercisesExercises

16.16.Write an Write an ifif statement that examines two statement that examines two integer variables and exchanges their values if integer variables and exchanges their values if the first one is greater than the second one.the first one is greater than the second one.

17.17.Write a program that shows the sign (+ or -) of Write a program that shows the sign (+ or -) of the product of three real numbers without the product of three real numbers without calculating it. Use sequence of calculating it. Use sequence of ifif statements. statements.

18.18.Write a program that finds the biggest of three Write a program that finds the biggest of three integers using nested integers using nested ifif statements. statements.

19.19.Write a program that sorts 3 real values in Write a program that sorts 3 real values in descending order using nested descending order using nested ifif statements. statements.

Page 96: Introduction to-programming

ExercisesExercises

20.20.Write program that for a given digit (0-9) Write program that for a given digit (0-9) entered as input prints the name of that digit (in entered as input prints the name of that digit (in Bulgarian). Use a Bulgarian). Use a switchswitch statement. statement.