SlideShare a Scribd company logo
1 of 96
Contents
•

The Structure of Java Programs

•

Keywords and Identifiers

•

Data Types
•

•

•

Integral, Textual, Floating-Point

Enumerations

Variables, Declarations, Assignments,
Operators
Contents
•

Expressions and Statements
•

Logical Statements

•

Loop Statements

•

Console Input and Output

•

Arrays and Array Manipulation

•

Using the Java API Documentation
Programming in Java
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
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/
Java API Documentation
A Java Program
Java
Program

Java methods (Java API)
native methods (dynamic libraries)

host operating system
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
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
Java Program – Example
HelloJava.java

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
• Can‟t find class HelloJava
• Exception in thread "main"
java.lang.NoClassDefFoundError:
HelloJava/class
Structure of Java Programs
The Source File Contents
• Java source code files can have three "toplevel" elements:
• An optional package declaration

• Any number of import statements
• Class and interface declarations
package jeecourse.example;
import java.io.*;
public class SomeClass {
// ...
}
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
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
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)

• The name args is purely arbitrary:
• Any legal identifier may be used, provided the
array is a single-dimension array of String
objects
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();
}
}
Keywords, Identifiers, Data
Types
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
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
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$
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
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
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
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'
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;
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
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
Ranges of the FloatingPoint 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
Non-numeric Floating-Point
Values
• Float.NaN
• Float.NEGATIVE_INFINITY
• Float.POSITIVE_INFINITY
• Double.NaN
• Double.NEGATIVE_INFINITY

• Double.POSITIVE_INFINITY
Textual Types: String
• Is not a primitive data type
• It is a class

• Has its literal enclosed in double quotes (" ")
• Example:
"The quick brown fox jumps over the lazy dog."

• Can be used as follows:
String greeting = "Good Morning !! n";
String errorMsg = "Record Not Found!";
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
Values vs. Objects
• Consider the following code fragment:
int x = 7;
int y = x;
String s = "Hello";
String t = s;

• Two variables refer to a single object:
x
y
s
t

7
7

0x01234567
0x01234567

Heap (dynamic memory)
"Hello" 0x01234567
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) {
...
}
Variables, Declarations,
Assignments, Operators
Variables, Declarations, and
Assignments
• 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 variable
int value = 5; // declare and assign variable
i = 25; // assign a value to a variable that is
already declared
Variables, Declarations, and
Assignments – 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
...
}
}
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
Operators
Category

Operators

Unary

++ -- + - ! ~ (type)

Arithmetic

* / %
+ -

Shift

<< >> >>>

Comparison

< <= > >= instanceof
== !=

Bitwise

& ^ |

Short-circuit

&& ||

Conditional

?:

Assignment

= op=
The Ordinal Comparisons
Operators: <, <=, >, and >=
• The ordinal comparison operators are:
• Less than: <
• Less than or equal to: <=
• Greater than: >

• Greater than or equal to: >=
The Ordinal Comparisons
Operators – Example
• int p = 9;

• p < q  true

• int q = 65;

• f < q  true

• int r = -12;

• f <= c  true

• float f = 9.0F;

• c > r  true

• char c = „A‟;

• c >= q  true
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));
String Concatenation with +
• The + operator:
• Performs String concatenation
• Produces a new String as a result:
String salutation = "Dr. ";
String name = "Pete " + "Seymour";
System.out.println(salutation + name + 5);

• First argument must be a String object
• Non-strings are converted to String objects
automatically
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: ()
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);
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;
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;
Operator Evaluation Order
• In Java, the order of evaluation of operands in
an expression is fixed – left to right
• Consider this code fragment:
int[] a = {4, 4};
int b = 1;
a[b] = b = 0;

• 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
Expressions and Statements
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

• Block statements – { ... }
• Conditional statements (if, if-else,
switch)
• Loop statements (for, while, do/while)
Statements and Blocks
• A statement is a single line of code
terminated by a semicolon(;)
salary = days * daySalary;

• A block is a collection of statements
bounded by opening and closing braces:
{
x = x + 1;
y = y + 1;
}

• You can nest block statements
Conditional Statements
• The if, if-else statements:
if (boolean condition) {
statement or block;
}

if (boolean condition) {
statement or block;
} else {
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;
}
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;
}
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);
}
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;
}
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);
}
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;
}
}
}
Comments
• Three permissible styles of comment in a
Java technology program are:
// comment on one line
/* comment on one
or more lines */

/** documenting comment */
Console Input and Output
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
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);
Reading from the Console
• First construct a Scanner that is attached to
the “standard input stream” System.in
Scanner in = new Scanner(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
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
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>)

• Like the printf function in C language
String name = "Nakov";
int age = 25;
System.out.printf(
"My name is %s.nI am %d years old.",
name, age);

• 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
Arrays and Array
Manipulation
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 array‟s
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

• Declaration and construction may be
performed in a single line:
int[] ints = new int[25];
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

Initial Value

byte

0

int

0

float

0.0f

char

‘u0000’

object reference

null

short

0

long

0L

double

0.0d

boolean

false
Array Elements Initialization
• Initial values for the elements can be
specified at the time of declaration and
initialization:
float[] diameters =
{1.1f, 2.2f, 3.3f, 4.4f, 5.5f};

• 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

• Elements access is range checked
int[] arr = new int[10];
int value = arr[10];
// ArrayIndexOutOfBoundsException

• Arrays has field length that contains their
number of elements
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=%dn", min);
System.out.printf("MAX=%dn", max);
Multi-dimensional Arrays
• Multidimensional arrays in Java are actually
arrays of arrays
• Defining matrix:
int[][] matrix = new int[3][4];

• Accessing matrix elements:
matrix[1][3] = 42;

• Getting the number of rows/columns:
int rows = matrix.length;
int colsInFirstRow = matrix[0].length;
Multi-dimensional Arrays
• Consider this declaration plus initialization:
int[][] myInts = new int[3][4];

• It‟s 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!

• The right way to
think about multidimension arrays
Multi-dimensional Arrays
• The subordinate
arrays in a multidimension 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} };
Multi-dimensional Arrays –
Example
// Finding the sum of all positive
// cells from the matrix
int[][] 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);
Introduction to Java
Programming

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.
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.
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.

More Related Content

What's hot

L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variablesteach4uin
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2mohamedsamyali
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1ppJ. C.
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IAjit Nayak
 
Indexers, Partial Class And Partial Method
Indexers, Partial Class And Partial MethodIndexers, Partial Class And Partial Method
Indexers, Partial Class And Partial MethodGopal Ji Singh
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed OverviewBuddha Tree
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1mohamedsamyali
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyMartin Odersky
 

What's hot (16)

L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 
C# Summer course - Lecture 2
C# Summer course - Lecture 2C# Summer course - Lecture 2
C# Summer course - Lecture 2
 
Csc240 -lecture_4
Csc240  -lecture_4Csc240  -lecture_4
Csc240 -lecture_4
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Cse java
Cse javaCse java
Cse java
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Object Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part IObject Oriented Programming using C++ Part I
Object Oriented Programming using C++ Part I
 
Indexers, Partial Class And Partial Method
Indexers, Partial Class And Partial MethodIndexers, Partial Class And Partial Method
Indexers, Partial Class And Partial Method
 
Java core - Detailed Overview
Java  core - Detailed OverviewJava  core - Detailed Overview
Java core - Detailed Overview
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Implementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in DottyImplementing Higher-Kinded Types in Dotty
Implementing Higher-Kinded Types in Dotty
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 

Viewers also liked

Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 CertificationsGiacomo Veneri
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesAAKASH KUMAR
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5ashish singh
 
java collections
java collectionsjava collections
java collectionsjaveed_mhd
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Java collections
Java collectionsJava collections
Java collectionsAmar Kutwal
 
C Programming basics
C Programming basicsC Programming basics
C Programming basicsJitin Pillai
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programmingChitrank Dixit
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programsJames Brotsos
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event HandlingJava Programming
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language CourseVivek chan
 
02 java basics
02 java basics02 java basics
02 java basicsbsnl007
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 

Viewers also liked (20)

Java: Collections
Java: CollectionsJava: Collections
Java: Collections
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
 
Advance java practicalty bscit sem5
Advance java practicalty bscit sem5Advance java practicalty bscit sem5
Advance java practicalty bscit sem5
 
java collections
java collectionsjava collections
java collections
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java collections
Java collectionsJava collections
Java collections
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
 
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conferenceJava Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
Java Certification by HUJAK - 2015-05-12 - at JavaCro'15 conference
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT IIC PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
Java Basics
Java BasicsJava Basics
Java Basics
 
02 java basics
02 java basics02 java basics
02 java basics
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 

Similar to Introduction to Java Programming

demo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptdemo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptFerdieBalang
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptxssuserb1a18d
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptxSmitNikumbh
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART IHari Christian
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf2b75fd3051
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2Aziz Sahat
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languagessuser2963071
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptxVijalJain3
 
COMPUTER PROGRAMMING LANGUAGE.pptx
COMPUTER PROGRAMMING LANGUAGE.pptxCOMPUTER PROGRAMMING LANGUAGE.pptx
COMPUTER PROGRAMMING LANGUAGE.pptxSofiaArquero2
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1Ali Raza Jilani
 

Similar to Introduction to Java Programming (20)

demo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.pptdemo1 java of demo 1 java with demo 1 java.ppt
demo1 java of demo 1 java with demo 1 java.ppt
 
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
 
OOP-java-variables.pptx
OOP-java-variables.pptxOOP-java-variables.pptx
OOP-java-variables.pptx
 
intro_java (1).pptx
intro_java (1).pptxintro_java (1).pptx
intro_java (1).pptx
 
01 Java Language And OOP PART I
01 Java Language And OOP PART I01 Java Language And OOP PART I
01 Java Language And OOP PART I
 
CSC111-Chap_02.pdf
CSC111-Chap_02.pdfCSC111-Chap_02.pdf
CSC111-Chap_02.pdf
 
ITFT - Java
ITFT - JavaITFT - Java
ITFT - Java
 
Zaridah lecture2
Zaridah lecture2Zaridah lecture2
Zaridah lecture2
 
Java ce241
Java ce241Java ce241
Java ce241
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
C language
C languageC language
C language
 
C language
C languageC language
C language
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Java
Java Java
Java
 
Java-Intro.pptx
Java-Intro.pptxJava-Intro.pptx
Java-Intro.pptx
 
COMPUTER PROGRAMMING LANGUAGE.pptx
COMPUTER PROGRAMMING LANGUAGE.pptxCOMPUTER PROGRAMMING LANGUAGE.pptx
COMPUTER PROGRAMMING LANGUAGE.pptx
 
Introduction to Swift 2
Introduction to Swift 2Introduction to Swift 2
Introduction to Swift 2
 
C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1C++ Basics introduction to typecasting Webinar Slides 1
C++ Basics introduction to typecasting Webinar Slides 1
 

More from One97 Communications Limited

WAP to invoke constructors using super keyword in java
WAP to invoke constructors using super keyword in javaWAP to invoke constructors using super keyword in java
WAP to invoke constructors using super keyword in javaOne97 Communications Limited
 
WAP to find out whether the number is prime or not in java
WAP to find out whether the number is prime or not in javaWAP to find out whether the number is prime or not in java
WAP to find out whether the number is prime or not in javaOne97 Communications Limited
 
How to achieve multiple inheritances by using interface in java
How to achieve multiple inheritances by using interface in java How to achieve multiple inheritances by using interface in java
How to achieve multiple inheritances by using interface in java One97 Communications Limited
 
WAP to implement inheritance and overloading methods in java
WAP to implement inheritance and overloading methods in javaWAP to implement inheritance and overloading methods in java
WAP to implement inheritance and overloading methods in javaOne97 Communications Limited
 
WAP to initialize different objects with different values in java
WAP to initialize different objects with different values in javaWAP to initialize different objects with different values in java
WAP to initialize different objects with different values in javaOne97 Communications Limited
 

More from One97 Communications Limited (20)

Er. Model Of Hospital Management
Er. Model Of Hospital ManagementEr. Model Of Hospital Management
Er. Model Of Hospital Management
 
Financial
FinancialFinancial
Financial
 
Railway
RailwayRailway
Railway
 
Library
LibraryLibrary
Library
 
Fcfs Cpu Scheduling With Gantt Chart
Fcfs Cpu Scheduling With Gantt ChartFcfs Cpu Scheduling With Gantt Chart
Fcfs Cpu Scheduling With Gantt Chart
 
Neural Interfacing
Neural Interfacing Neural Interfacing
Neural Interfacing
 
Blue eye technology
Blue eye technology Blue eye technology
Blue eye technology
 
Computer Forensics
Computer ForensicsComputer Forensics
Computer Forensics
 
Backtrack
BacktrackBacktrack
Backtrack
 
Protect Folders without using any Software
Protect Folders without using any SoftwareProtect Folders without using any Software
Protect Folders without using any Software
 
Topology
TopologyTopology
Topology
 
WAP to invoke constructors using super keyword in java
WAP to invoke constructors using super keyword in javaWAP to invoke constructors using super keyword in java
WAP to invoke constructors using super keyword in java
 
WAP to find out whether the number is prime or not in java
WAP to find out whether the number is prime or not in javaWAP to find out whether the number is prime or not in java
WAP to find out whether the number is prime or not in java
 
Overriding abstract in java
Overriding abstract in javaOverriding abstract in java
Overriding abstract in java
 
How to achieve multiple inheritances by using interface in java
How to achieve multiple inheritances by using interface in java How to achieve multiple inheritances by using interface in java
How to achieve multiple inheritances by using interface in java
 
Method overriding in java
Method overriding in javaMethod overriding in java
Method overriding in java
 
WAP to implement inheritance and overloading methods in java
WAP to implement inheritance and overloading methods in javaWAP to implement inheritance and overloading methods in java
WAP to implement inheritance and overloading methods in java
 
program on Function overloading in java
program on  Function overloading in javaprogram on  Function overloading in java
program on Function overloading in java
 
Program on usage of Final keyword in java
Program on usage of  Final keyword in javaProgram on usage of  Final keyword in java
Program on usage of Final keyword in java
 
WAP to initialize different objects with different values in java
WAP to initialize different objects with different values in javaWAP to initialize different objects with different values in java
WAP to initialize different objects with different values in java
 

Recently uploaded

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 

Recently uploaded (20)

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 

Introduction to Java Programming

  • 1.
  • 2. Contents • The Structure of Java Programs • Keywords and Identifiers • Data Types • • • Integral, Textual, Floating-Point Enumerations Variables, Declarations, Assignments, Operators
  • 3. Contents • Expressions and Statements • Logical Statements • Loop Statements • Console Input and Output • Arrays and Array Manipulation • Using the Java API Documentation
  • 5. 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
  • 6. 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/
  • 8. A Java Program Java Program Java methods (Java API) native methods (dynamic libraries) host operating system
  • 9. 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
  • 10. 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
  • 11. Java Program – Example HelloJava.java public class HelloJava { public static void main(String[] args) { System.out.println("Hello, Java!"); } } javac HelloJava.java java –cp . HelloJava Hello, Java!
  • 12. 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".
  • 13. Typical Errors • Runtime Errors • Can‟t find class HelloJava • Exception in thread "main" java.lang.NoClassDefFoundError: HelloJava/class
  • 14. Structure of Java Programs
  • 15. The Source File Contents • Java source code files can have three "toplevel" elements: • An optional package declaration • Any number of import statements • Class and interface declarations package jeecourse.example; import java.io.*; public class SomeClass { // ... }
  • 16. 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
  • 17. 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
  • 18. 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) • The name args is purely arbitrary: • Any legal identifier may be used, provided the array is a single-dimension array of String objects
  • 19. 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(); } }
  • 21. 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
  • 23. 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
  • 24. 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$
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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'
  • 29. 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;
  • 30. 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
  • 31. 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
  • 32. Ranges of the FloatingPoint 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
  • 33. Non-numeric Floating-Point Values • Float.NaN • Float.NEGATIVE_INFINITY • Float.POSITIVE_INFINITY • Double.NaN • Double.NEGATIVE_INFINITY • Double.POSITIVE_INFINITY
  • 34. Textual Types: String • Is not a primitive data type • It is a class • Has its literal enclosed in double quotes (" ") • Example: "The quick brown fox jumps over the lazy dog." • Can be used as follows: String greeting = "Good Morning !! n"; String errorMsg = "Record Not Found!";
  • 35. 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
  • 36. Values vs. Objects • Consider the following code fragment: int x = 7; int y = x; String s = "Hello"; String t = s; • Two variables refer to a single object: x y s t 7 7 0x01234567 0x01234567 Heap (dynamic memory) "Hello" 0x01234567
  • 37. 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;
  • 38. 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) { ... }
  • 40. Variables, Declarations, and Assignments • 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 variable int value = 5; // declare and assign variable i = 25; // assign a value to a variable that is already declared
  • 41. Variables, Declarations, and Assignments – 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 ... } }
  • 42. 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
  • 43. Operators Category Operators Unary ++ -- + - ! ~ (type) Arithmetic * / % + - Shift << >> >>> Comparison < <= > >= instanceof == != Bitwise & ^ | Short-circuit && || Conditional ?: Assignment = op=
  • 44. The Ordinal Comparisons Operators: <, <=, >, and >= • The ordinal comparison operators are: • Less than: < • Less than or equal to: <= • Greater than: > • Greater than or equal to: >=
  • 45. The Ordinal Comparisons Operators – Example • int p = 9; • p < q  true • int q = 65; • f < q  true • int r = -12; • f <= c  true • float f = 9.0F; • c > r  true • char c = „A‟; • c >= q  true
  • 46. 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));
  • 47. String Concatenation with + • The + operator: • Performs String concatenation • Produces a new String as a result: String salutation = "Dr. "; String name = "Pete " + "Seymour"; System.out.println(salutation + name + 5); • First argument must be a String object • Non-strings are converted to String objects automatically
  • 48. 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: ()
  • 49. 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);
  • 50. 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;
  • 51. 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;
  • 52. Operator Evaluation Order • In Java, the order of evaluation of operands in an expression is fixed – left to right • Consider this code fragment: int[] a = {4, 4}; int b = 1; a[b] = b = 0; • 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
  • 54. 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;
  • 55. 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)
  • 56. Statements and Blocks • A statement is a single line of code terminated by a semicolon(;) salary = days * daySalary; • A block is a collection of statements bounded by opening and closing braces: { x = x + 1; y = y + 1; } • You can nest block statements
  • 57. Conditional Statements • The if, if-else statements: if (boolean condition) { statement or block; } if (boolean condition) { statement or block; } else { statement or block; }
  • 58. 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!"); } }
  • 59. Conditional Statements • The switch statement switch (expression) { case constant1: statements; break; case constant2: statements; break; default: statements; break; }
  • 60. 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; }
  • 61. 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!")
  • 62. 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); } }
  • 63. 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 }
  • 64. 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); }
  • 65. 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; }
  • 66. 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); }
  • 67. 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; } } }
  • 68. Comments • Three permissible styles of comment in a Java technology program are: // comment on one line /* comment on one or more lines */ /** documenting comment */
  • 70. 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
  • 71. 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);
  • 72. Reading from the Console • First construct a Scanner that is attached to the “standard input stream” System.in Scanner in = new Scanner(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
  • 73. 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
  • 74. 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));
  • 75. Formatting Output • System.out.printf(<format>, <values>) • Like the printf function in C language String name = "Nakov"; int age = 25; System.out.printf( "My name is %s.nI am %d years old.", name, age); • 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
  • 77. Creating Arrays • To create and use an array, follow three steps: 1. Declaration 2. Construction 3. Initialization 4. Access to Elements
  • 78. Array Declaration • Declaration tells the compiler the array‟s 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[];
  • 79. 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 • Declaration and construction may be performed in a single line: int[] ints = new int[25];
  • 80. 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
  • 81. 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
  • 82. Array Elements Initialization • Initial values for the elements can be specified at the time of declaration and initialization: float[] diameters = {1.1f, 2.2f, 3.3f, 4.4f, 5.5f}; • The array size is inferred from the number of elements within the curly braces
  • 83. Access to Elements • Accessing array elements: int[] arr = new int[10]; arr[3] = 5; // Writing element int value = arr[3]; // Reading element • Elements access is range checked int[] arr = new int[10]; int value = arr[10]; // ArrayIndexOutOfBoundsException • Arrays has field length that contains their number of elements
  • 84. 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=%dn", min); System.out.printf("MAX=%dn", max);
  • 85. Multi-dimensional Arrays • Multidimensional arrays in Java are actually arrays of arrays • Defining matrix: int[][] matrix = new int[3][4]; • Accessing matrix elements: matrix[1][3] = 42; • Getting the number of rows/columns: int rows = matrix.length; int colsInFirstRow = matrix[0].length;
  • 86. Multi-dimensional Arrays • Consider this declaration plus initialization: int[][] myInts = new int[3][4]; • It‟s natural to assume that the myInts contains 12 ints and to imagine them as organized into rows and columns, as shown: WRONG!
  • 87. Multi-dimensional Arrays CORRECT! • The right way to think about multidimension arrays
  • 88. Multi-dimensional Arrays • The subordinate arrays in a multidimension 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} };
  • 89. Multi-dimensional Arrays – Example // Finding the sum of all positive // cells from the matrix int[][] 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);
  • 91. 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.
  • 92. 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.
  • 93. 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.
  • 94. 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.
  • 95. 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.
  • 96. 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.