introduction to java programming
DESCRIPTION
This Presentation is the intro. to java programming. This presentation contain the basics of Java with example in simple language. This presentation clear your all concept about programming in java and then you can easily make programs in java.TRANSCRIPT
![Page 1: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/1.jpg)
By – Anil Kumar ( My Style Pro )
Introduction to Java Programming
![Page 2: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/2.jpg)
Contents
• The Structure of Java Programs
• Keywords and Identifiers
• Data Types
• Integral, Textual, Floating-Point
• Enumerations
• Variables, Declarations, Assignments, Operators
![Page 3: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/3.jpg)
Contents
• Expressions and Statements
• Logical Statements
• Loop Statements
• Console Input and Output
• Arrays and Array Manipulation
• Using the Java API Documentation
![Page 4: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/4.jpg)
Programming in Java
![Page 5: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/5.jpg)
The Java API
• A set of runtime libraries
• Available on any JVM
• Provide platform-independent standard
• Classes and interfaces
• Security
• Platform independence difficulties
• Implementation is specific to the host platform
![Page 6: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/6.jpg)
What is Java API Documentation?
• Java documentation is HTML based
• Also called "Java Platform Standard Edition API Specification"
• Complete documentation of all standard classes and methods
• Descriptions of all the functionality
• Links to related articles
• Use local copy or the Web version from http://java.sun.com/javase/6/docs/api/
![Page 7: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/7.jpg)
Java API Documentation
![Page 8: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/8.jpg)
A Java Program
Java methods (Java API)
Java Program
native methods (dynamic libraries)
host operating system
![Page 9: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/9.jpg)
The Java Programming Language
• Quite general-purpose• Boosts developer productivity• Combines proven techniques• Software technologies
• Object-orientation
• Multi-threading
• Structured error-handling
• Garbage collection
• Dynamic linking and extension
![Page 10: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/10.jpg)
Writing Java Programs
• Write custom source code
• In the Java programming language
• Using the Java API
• Compile the source code
• Using the “javac” compiler command
• Compiles to bytecodes
• Run the compiled code
• Using the “java” launcher command
![Page 11: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/11.jpg)
Java Program – Example
public class HelloJava { public static void main(String[] args) { System.out.println("Hello, Java!"); }}
HelloJava.java
javac HelloJava.java
java –cp . HelloJava
Hello, Java!
![Page 12: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/12.jpg)
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".
![Page 13: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/13.jpg)
Typical Errors
• Runtime Errors
• Can’t find class HelloJava
• Exception in thread "main" java.lang.NoClassDefFoundError: HelloJava/class
![Page 14: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/14.jpg)
Structure of Java Programs
![Page 15: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/15.jpg)
The Source File Contents
• Java source code files can have three "top-level" elements:
• An optional package declaration
• Any number of import statements
• Class and interface declarations
package jeecourse.example;
import java.io.*;
public class SomeClass { // ...}
![Page 16: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/16.jpg)
Classes and Packages
• Classes are the main program unit in Java
• Contain the source code of the program logic
• Can define fields
• Can contain methods (subprograms)
• Packages are containers for classes
• Can be nested hierarchically
• Each package can contain multiple classes
![Page 17: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/17.jpg)
Important Java Packages
• Important packages within the Java class library are:
• java.lang
• java.util
• java.io
• java.text
• java.awt
• java.net
• java.applet
![Page 18: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/18.jpg)
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:
• The name args is purely arbitrary:
• Any legal identifier may be used, provided the array is a single-dimension array of String objects
public static void main(String[] args)
![Page 19: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/19.jpg)
Programs, Classes, and Packages – Example
package jeecourse.example;
import java.io.*;
public class SomeClass {
private static int mValue = 5;
public static void printValue() { System.out.println("mValue = " + mValue); }
public static void main(String[] args) { System.out.println("Some Class"); printValue(); }}
![Page 20: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/20.jpg)
Keywords, Identifiers, Data Types
![Page 21: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/21.jpg)
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 language’s keywords
• Java’s keywords and other special-meaning words are listed in the next slide
![Page 22: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/22.jpg)
Java 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 Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/23.jpg)
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
![Page 24: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/24.jpg)
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$
![Page 25: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/25.jpg)
Primitive Data Types
• A primitive is a simple non-object data type that represents a single value
• Java’s primitive data types are:
• boolean
• char
• byte, short, int, long
• float, double
![Page 26: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/26.jpg)
Primitive Data Types
Type Effective Size (bits)
byte 8
short 16
int 32
long 64
float 32
double 64
char 16
• Variables of type boolean may take only the values true or false
• Their representation size might vary
![Page 27: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/27.jpg)
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
![Page 28: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/28.jpg)
Textual Types: char
• Represents a 16-bit Unicode character• Must have its literal enclosed in single
quotes(’ ’)• Uses the following notations:
• 'a' – The letter a
• '\t' – A tab
• '\n' – A new line character
• '\u????' – A specific Unicode character, ????, is replaced with exactly four hexadecimal digits, e.g. '\u1A4F'
![Page 29: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/29.jpg)
Integral Types: byte, short, int, and long
• Uses three forms – decimal, octal, or hexadecimal, e. g.• 2 – The decimal value is two
• 077 – The leading zero indicates an octal value
• 0xBAAC – The leading 0x indicates a hexadecimal value
• The default integer values are int
• Defines long by using the letter L or l:long value = 1234L;
![Page 30: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/30.jpg)
Ranges of the Integral Primitive 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 Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/31.jpg)
Floating Point Types: float and double
• Default is double• Floating point literal includes either a decimal
point or one of the following:• E or e (add exponential value)• F or f (float)• D or d (double)
• 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
![Page 32: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/32.jpg)
Ranges of the Floating-Point 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 Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/33.jpg)
Non-numeric Floating-Point Values
• Float.NaN
• Float.NEGATIVE_INFINITY
• Float.POSITIVE_INFINITY
• Double.NaN
• Double.NEGATIVE_INFINITY
• Double.POSITIVE_INFINITY
![Page 34: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/34.jpg)
Textual Types: String
• Is not a primitive data type
• It is a class
• Has its literal enclosed in double quotes (" ")
• Example:
• Can be used as follows:String greeting = "Good Morning !! \n";String errorMsg = "Record Not Found!";
"The quick brown fox jumps over the lazy dog."
![Page 35: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/35.jpg)
Values and Objects
• Primitive Data Types• Are value types
• Contain directly their values
• Examples: int, float, char, boolean
• Objects• Are reference types
• Contain a pointer (memory address) of their values
• Examples: String, Object, Date
![Page 36: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/36.jpg)
Values vs. Objects
• Consider the following code fragment:
• Two variables refer to a single object:
int x = 7;int y = x;String s = "Hello";String t = s;
7x
7y
0x01234567s
0x01234567t
"Hello" 0x01234567
Heap (dynamic memory)
![Page 37: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/37.jpg)
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;
![Page 38: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/38.jpg)
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) { ...}
![Page 39: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/39.jpg)
Variables, Declarations, Assignments, Operators
![Page 40: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/40.jpg)
Variables, Declarations, andAssignments
• Variables are names places in the memory that contain some value
• Variables have a type (int, float, String, ...)
• Variables should be declared before use
• Variables can be assigned
• Examples:
int i; // declare variableint value = 5; // declare and assign variablei = 25; // assign a value to a variable that is already declared
![Page 41: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/41.jpg)
Variables, Declarations, andAssignments – Examples
public class Assignments { public static void main(String args []) { int x, y; // declare int variables float z = 3.414f; // declare and assign float double w = 3.1415; // declare and assign double boolean b = true; // declare and assign boolean char ch; // declare character variable String str; // declare String variable String s = "bye"; // declare and assign String ch = 'A'; // assign a value to char variable str = "Hi out there!"; // assign value to String x = 6; // assign value to int variable y = 1000; // assign values to int variable ... }}
![Page 42: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/42.jpg)
Variables and Scope
• Local variables are:
• Variables that are defined inside a method and are called local, automatic, temporary, or stack variables
• Created when the method is executed and destroyed when the method is exited
• Variables that must be initialized before they are used or compile-time errors will occur
![Page 43: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/43.jpg)
Operators
Category Operators
Unary ++ -- + - ! ~ (type)
Arithmetic * / %
+ -
Shift << >> >>>
Comparison < <= > >= instanceof
== !=
Bitwise & ^ |
Short-circuit && ||
Conditional ? :
Assignment = op=
![Page 44: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/44.jpg)
The Ordinal Comparisons Operators: <, <=, >, and >=
• The ordinal comparison operators are:
• Less than: <
• Less than or equal to: <=
• Greater than: >
• Greater than or equal to: >=
![Page 45: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/45.jpg)
The Ordinal Comparisons Operators – Example
• int p = 9;
• int q = 65;
• int r = -12;
• float f = 9.0F;
• char c = ‘A’;
• p < q true
• f < q true
• f <= c true
• c > r true
• c >= q true
![Page 46: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/46.jpg)
Short-Circuit Logical Operators
• The operators are && (AND) and || (OR)
• These operators can be used as follows:
MyDate d = null;
if ((d != null) && (d.day() > 31)) { // Do something}
boolean goodDay = (d == null) || ((d != null) && (d.day() >= 12));
![Page 47: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/47.jpg)
String Concatenation with +
• The + operator:• Performs String concatenation
• Produces a new String as a result:
• First argument must be a String object• Non-strings are converted to String objects
automatically
String salutation = "Dr. ";String name = "Pete " + "Seymour"; System.out.println(salutation + name + 5);
![Page 48: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/48.jpg)
The Unary Operators
• Unary operators take only a single operand and work just on that
• Java provides seven unary operators:
• The increment and decrement operators: ++ and --
• The unary plus and minus operators: + and -
• The bitwise inversion operator: ~
• The boolean complement operator: !
• The cast operator: ()
![Page 49: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/49.jpg)
The Cast Operator: (type)
• Implicit type conversions are possible when no information can be lost
• E.g. converting int long
• 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);
![Page 50: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/50.jpg)
The Multiplication and Division Operators: * and /
• The * and / operators perform multiplication and division on all primitive numeric types and char
• Integer division will generate an ArithmeticException when attempting to divide by zero
int a = 5;int value = a * 10;
![Page 51: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/51.jpg)
The Bitwise Operators
• The bitwise operators: &, ^, and | provide bitwise AND, eXclusive-OR (XOR), and OR operations, respectively
• They are applicable to integral types
int first = 100;int second = 200;
int xor = first ^ second;
int and = first & second;
![Page 52: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/52.jpg)
Operator Evaluation Order
• In Java, the order of evaluation of operands in an expression is fixed – left to right
• Consider this code fragment:
• In this case, it might be unclear which element of the array is modified:
• Which value of b is used to select the array element, 0 or 1
int[] a = {4, 4};int b = 1;a[b] = b = 0;
![Page 53: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/53.jpg)
Expressions and Statements
![Page 54: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/54.jpg)
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 circledouble surface = Math.PI * r * r;
// Expression for calculation of// the perimeter of the circledouble perimeter = 2 * Math.PI * r;
![Page 55: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/55.jpg)
Statements
• Statements are the main programming constructs
• Types of statements
• Simple statements
• The smallest programming instructions
• Block statements – { ... }
• Conditional statements (if, if-else, switch)
• Loop statements (for, while, do/while)
![Page 56: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/56.jpg)
Statements and Blocks
• A statement is a single line of code terminated by a semicolon(;)
• A block is a collection of statements bounded by opening and closing braces:
• You can nest block statements
salary = days * daySalary;
{ x = x + 1; y = y + 1;}
![Page 57: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/57.jpg)
Conditional Statements
• The if, if-else statements:
if (boolean condition) { statement or block;}
if (boolean condition) { statement or block;} else { statement or block;}
![Page 58: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/58.jpg)
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!"); }}
![Page 59: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/59.jpg)
Conditional Statements
• The switch statement
switch (expression) { case constant1: statements; break; case constant2: statements; break; default: statements; break;}
![Page 60: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/60.jpg)
The switch Statement – Example
int dayOfWeek = 3;switch (dayOfWeek) { case 1: System.out.println("Monday"); break; case 2: System.out.println("Tuesday"); break; ... default: System.out.println("Invalid day!"); break;}
![Page 61: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/61.jpg)
Looping Statements
• The for statement:
• Example:
for (init_expr; boolean testexpr; alter_expr) { statement or block;}
for (int i = 0; i < 10; i++) { System.out.println("i=" + i);}System.out.println("Finished!")
![Page 62: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/62.jpg)
Looping Statements
• The enhanced for statement:
• Example:
for (Type variable : some collection) { statement or block;}
public static void main(String[] args) { String[] towns = new String[] { "Sofia", "Plovdiv", "Varna" }; for (String town : towns) { System.out.println(town); }}
![Page 63: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/63.jpg)
Looping Statements
• The while loop:
• Examples:
while (boolean condition) { statement or block;}
int i=100;while (i>0) { System.out.println("i=" + i); i--;}
while (true) { // This is an infinite loop}
![Page 64: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/64.jpg)
Looping Statements
• The do/while loop:
• Example:
do { statement or block;} while (boolean condition);
public static void main(String[] args) { int counter=100; do { System.out.println("counter=" + counter); counter = counter - 5; } while (counter>=0);}
![Page 65: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/65.jpg)
Special Loop Flow Control
• Some special operators valid in loops:
• break [label];
• continue [label];
• label: statement; // Where statement should be a loop
• Example (breaking a loop):
for (int counter=100; counter>=0; counter-=5) { System.out.println("counter=" + counter); if (counter == 50) break;}
![Page 66: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/66.jpg)
Special Loop Flow Control – Examples
• Example (continuing a loop):
for (int counter=100; counter>=0; counter-=5) { if (counter == 50) { continue; } System.out.println("counter=" + counter);}
![Page 67: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/67.jpg)
Special Loop Flow Control – Examples
• Example (breaking a loop with a label):
outerLoop: for (int i=0; i<50; i++) { for (int counter=100; counter>=0; counter-=5) { System.out.println("counter=" + counter); if ((i==2) && (counter == 50)) { break outerLoop; } } }
![Page 68: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/68.jpg)
Comments
• Three permissible styles of comment in a Java technology program are:
// comment on one line
/* comment on oneor more lines */
/** documenting comment */
![Page 69: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/69.jpg)
Console Input and Output
![Page 70: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/70.jpg)
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
• To facilitate some operations additional classes should be involved
• Scanner
• BufferedReader, InputStreamReader
![Page 71: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/71.jpg)
Printing to the Console
• System.out.print(...)
• Can take as input different types
•String, int, float, Object, ...
• Non-string types are converted to String
• 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);
![Page 72: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/72.jpg)
Reading from the Console
• First construct a Scanner that is attached to the “standard input stream” System.in
• Then use various methods of the Scanner class to read input
• nextLine() String
• Reads a line of input
• next() String
• Reads a single word delimited by whitespace
Scanner in = new Scanner(System.in);
![Page 73: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/73.jpg)
Reading from the Console
• Scanner – more methods
• nextInt() int
• Reads an int value. Throws InputMismatchException on error
• nextLong() long
• nextFloat() float
• Reads a float value. Throws InputMismatchException on error
• nextDouble() double
![Page 74: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/74.jpg)
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)); }}
![Page 75: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/75.jpg)
Formatting Output
• System.out.printf(<format>, <values>)
• Like the printf function in C language
• Some formatting patterns
• %s – Display as string %f – Display as float
• %d – Display as number %t – Display as date
* For more details see java.util.Formatter
String name = "Nakov";int age = 25;System.out.printf( "My name is %s.\nI am %d years old.", name, age);
![Page 76: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/76.jpg)
Arrays and Array Manipulation
![Page 77: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/77.jpg)
Creating Arrays
• To create and use an array, follow three steps:
1. Declaration
2. Construction
3. Initialization
4. Access to Elements
![Page 78: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/78.jpg)
Array Declaration
• Declaration tells the compiler the array’s name and what type its elements will be
• For example:
• The square brackets can come before or after the array variable name:
int[] ints;Dimensions[] dims;float[][] twoDimensions;
int ints[];
![Page 79: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/79.jpg)
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:
• Declaration and construction may be performed in a single line:
int[] ints; // Declaration ints = new int[25]; // Construction
int[] ints = new int[25];
![Page 80: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/80.jpg)
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 0-like values, as shown in the next slide
![Page 81: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/81.jpg)
Elements 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 Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/82.jpg)
Array Elements Initialization
• Initial values for the elements can be specified at the time of declaration and initialization:
• The array size is inferred from the number of elements within the curly braces
float[] diameters = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f};
![Page 83: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/83.jpg)
Access to Elements
• Accessing array elements:
• Elements access is range checked
• Arrays has field length that contains their number of elements
int[] arr = new int[10];arr[3] = 5; // Writing elementint value = arr[3]; // Reading element
int[] arr = new int[10];int value = arr[10];// ArrayIndexOutOfBoundsException
![Page 84: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/84.jpg)
Arrays – Example
// Finding the smallest and largest// elements in an arrayint[] 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);
![Page 85: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/85.jpg)
Multi-dimensional Arrays
• Multidimensional arrays in Java are actually arrays of arrays
• Defining matrix:
• Accessing matrix elements:
• Getting the number of rows/columns:
int[][] matrix = new int[3][4];
matrix[1][3] = 42;
int rows = matrix.length;int colsInFirstRow = matrix[0].length;
![Page 86: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/86.jpg)
Multi-dimensional Arrays
• Consider this declaration plus initialization:
• It’s natural to assume that the myInts contains 12 ints and to imagine them as organized into rows and columns, as shown:
WRONG!
int[][] myInts = new int[3][4];
![Page 87: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/87.jpg)
Multi-dimensional Arrays
• The right way to think about multi-dimension arrays
CORRECT!
![Page 88: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/88.jpg)
Multi-dimensional Arrays
• The subordinate arrays in a multi-dimension array don’t 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} };
![Page 89: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/89.jpg)
Multi-dimensional Arrays – Example
// Finding the sum of all positive// cells from the matrixint[][] matrix = {{2,4,-3}, {8,-1,6}};int sum = 0;for (int row=0; row<matrix.length; row++) { for (int col=0; col<matrix[row].length; col++) { if (matrix[row][col] > 0) { sum += matrix[row][col]; } }}System.out.println("Sum = " + sum);
![Page 90: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/90.jpg)
Questions?
Introduction to Java Programming
![Page 91: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/91.jpg)
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.
![Page 92: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/92.jpg)
Exercises
6. Write a program that asks the user for a four-digit number abcd and:1. Calculates the sum of its digits
2. Prints its digits in reverse order: dcba
3. Puts the last digit in at the front: dabc
4. 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.
![Page 93: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/93.jpg)
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.
![Page 94: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/94.jpg)
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. Don’t 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.
![Page 95: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/95.jpg)
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.
![Page 96: Introduction to Java Programming](https://reader036.vdocuments.mx/reader036/viewer/2022081507/554f5511b4c905524c8b50fd/html5/thumbnails/96.jpg)
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.