0% found this document useful (0 votes)
64 views86 pages

Introduction To Java Programming

Uploaded by

Ankita Pradhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views86 pages

Introduction To Java Programming

Uploaded by

Ankita Pradhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 86

Introduction To Java Programming

You will learn about the process of


creating Java programs and constructs
for input, output, branching, looping, as
well some of the history behind Java’s
development.

James Tam
Java Vs. Java Script

Java (this is what you need to know for this course)


- A complete programming language developed by Sun
- Can be used to develop either web based or stand-alone software
- Many pre-created code libraries available
- For more complex and powerful programs

Java Script (not covered in this course)


- A small language that’s mostly used for web-based applications (run
through a web browser like Internet Explorer, Firefox, Safari, Chrome)
- Good for programming simple special effects for your web page e.g., roll-
overs

James Tam
Java: History

•Computers of the past

James Tam
Java: History (2)

•The invention of the microprocessor revolutionized


computers

Intel microprocessor

Commodore Pet microcomputer

James Tam
Java: History (3)

•It was believed that the logical next step for microprocessors
was to have them run intelligent consumer electronics

James Tam
Java History (4)

•Sun Microsystems funded an internal research project “Green”


to investigate this opportunity.
- Result: A programming language called “Oak”

Blatant advertisement: James Gosling was a


graduate of the U of C Computer Science
program.

Wav file from “The Simpsons” © Fox, Image from the website of Sun Microsystems James Tam
Java History (5)

- Problem: There was already a programming language called Oak.


- The “Green” team met at a local coffee shop to come up with
another name...
• Java!

James Tam
Java: History (6)

•The concept of intelligent devices didn’t catch


on.
•Project Green and work on the Java language
was nearly canceled.

James Tam
Java: History (7)

•The popularity of the Internet resulted in Sun’s re-focusing of


Java on computers.
•Prior to the advent of Java, web pages allowed you to download
only text and images.

Your computer at home Server containing a


running a web browser web page

User clicks on a link

Images and text get


downloaded

James Tam
Java: History (8)

•Java enabled web browsers allowed for the downloading of


programs (Applets).
•Java is still used in this context today:
- Facebook (older version)
- Hotmail (older version)

Your computer at home Server containing


running a web browser a web page

User clicks on a link

Java Applet downloaded

James Tam
Java: Write Once, Run Anywhere

• Consequence of Java’s history:


platform-independence

Click on link to Applet

Mac user running Safari


Web page stored on Unix server
Virtual machine translates byte code to
native Mac code and the Applet is run Byte code is downloaded

Windows user running Internet Explorer


Byte code
(part of web
page)

James Tam
History

•B led to C, C evolved into C++, and C++ set the stage for Java
•BCPL, developed by Martin Richards.
•BCPL influenced a language called B, invented by Ken
Thompson, which led to the development of C in the 1970s
•Throughout the history of programming, the increasing
complexity of programs has driven the need for better ways to
manage that complexity. C++ is a response to that need, C++ was
invented by Bjarne Stroustrup in 1979.
•Java was conceived by James Gosling, Patrick Naughton , Chris
Warth , Ed Frank, and Mike Sheridan at Sun Microsystems, Inc.
in 1991.
• This language was initially called “Oak” but was renamed “Java”
in 1995.
James Tam
Java and C++

•Java is a pure object-oriented language while C++ is basically C


with object-oriented extension .The major differences are:
•Java does not support operator overloading
•Java does not have template classes as in C++
•Java does not support Multiple inheritance
•Java does not support global variable
•Java does not use pointers
•There are no header file in Java

James Tam
Byte Code
• Byte code is a highly optimized set of instructions designed to
be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM). That is, in its standard form, the
JVM is an interpreter for bytecode.
• Translating a Java program into bytecode helps makes it much
easier to run a program in a wide variety of environments.
• Sun supplies its Just In Time (JIT) compiler for bytecode, which
is included in the Java 2 release. When the JIT compiler is part
of the JVM, it compiles bytecode into executable code.

James Tam
Java Virtual Machine(JVM)

• Programs written in Java are compiled into Java Byte Code, which
is then interpreted by a special Java Interpreter for a specific
platform, which is known as Java Virtual Machine(JVM).
• The Machine language for the Java Virtual Machine is called Java
Byte Code.
• The Java Interpreter running on any machine appears and behaves
like “virtual” processor chip, that is why the name-JVM.
• The JVM is an abstract machine designed to be implemented on the
top of existing processor. It hides the underlying operating system
from Java applications.
• JVM combines with Java API makes java Platform.

James Tam
Java: Write Once, Run Anywhere

• Consequence of Java’s history:


platform-independent

Mac user running Safari


Web page stored on Unix server

Click on link to Applet


Byte code is downloaded

Windows user running Internet Explorer

Virtual machine translates byte code to


native Windows code and the Applet is run

James Tam
Compiled Programs With Different
Operating Systems

Windows
compiler

Executable (Windows)

Mac OS
Computer compiler
program
Executable (Mac)

UNIX
compiler

Executable (UNIX)

James Tam
Java Compiler

•A Java Compiler javac is a computer program or set of programs


which translates java source code into java byte code.
•The output from a Java compiler comes in the form of Java class
files (with .class extension). The java source code contained in files
end with the .java extension.
• The file name must be the same as the class name, as
classname.java. When the javac compiles the source file defined in
a .java files, it generates bytecode for the java source file and saves
in a class file with a .class extension.
• Example: C:\> Javac File1.java

James Tam
Java Interpreter
• Java interpreter translates the Java bytecode into the code that can be
understood by the Operating System.
• Basically, A Java interpreter is a software that implements the Java virtual machine
and runs Java applications. As the Java compiler compiles the source code into the
Java bytecode, the same way the Java interpreter translates the Java bytecode into
the code that can be understood by the Operating System.
• When a Java interpreter is installed on any platform that means it is JVM (Java
virtual machine) enabled platform. It (Java Interpreter) performs all of the
activities of the Java run-time system. It loads Java class files and interprets the
compiled byte-code.
• some web browsers like Netscape and the Internet Explorer are Java enabled. This
means that these browsers contain Java interpreter. With the help of this Java
interpreter we download the Applets from the Internet or an intranet to run within
a web browser.
• The interpreter also serves as a specialized compiler in an implementation that
supports dynamic or "just in time," compilation which turns Java byte-code into
native machine instructions. 
• Example: C:\> Java File1
James Tam
A High Level View Of Translating/Executing Java
Programs

Stage 1: Compilation

Filename.java Java compiler Filename.class


(javac)
Java
Java program bytecode
(generic
binary)

James Tam
A High Level View Of Translating/Executing Java
Programs (2)

Stage 2: Interpreting and executing the byte code


Machine language
instruction (UNIX)

Filename.class Java interpreter Machine language


(java) instruction (Windows)
Java
bytecode
(generic
binary) Machine language
instruction (Apple)

James Tam
Creating, Compiling And Running Java Programs
On The Computer Science Network

Java program Type it in with the text editor of your choice

filename.java
(Unix file)

Java compiler
javac
Java byte code
filename.class
To compile the program at the (UNIX file)
command line type "javac
filename.java"
Java Interpreter
java
To run the interpreter, at
the command line type
"java filename" James Tam
Which Java?

- JDK (Java development kit) – for developing Java software (creating


Java programs.
- JRE (Java Runtime environment) – only good for running pre-created
Java programs.
- Java Plug-in – a special version of the JRE designed to run through web
browsers.
- Java Standard Edition (J2SE) ,J2SE can be used to develop client-side
standalone applications or applets.
- Java Enterprise Edition (J2EE) ,J2EE can be used to develop server-
side applications such as Java servlets and Java ServerPages.
- Java Micro Edition (J2ME).
• J2ME can be used to develop applications for mobile devices such as cell
phones.

James Tam
Structured Programming

• Structured programming is a programming paradigm aimed on improving the clarity,


quality, and development time of a computer program by making extensive use of
subroutines, block structures and for and while loops – in contrast to using simple tests and
jumps such as the goto statement.
• A programming paradigm is a fundamental style of computer programming. There are four
main paradigms: object-oriented, imperative, functional and declarative.
• object-oriented languages (like Simula, Smalltalk, C++, Eiffel and Java). In these languages,
data, and methods of manipulating the data, are kept as a single unit called an object. The
only way that a user can access the data is via the object's 'methods' (subroutines).
• imperative programming is a programming paradigm that describes computation in terms
of statements that change a program state. imperative programs define sequences of
commands for the computer to perform.
• In declarative programming the computer is told what the problem is, not how to solve
the problem - the program is structured as a collection of properties to find in the expected
result, not as a procedure to follow. Given a database or a set of rules, the computer tries to
find a solution matching all the desired properties.
• Functional programming is a subset of declarative programming. Programs written using
this paradigm use functions, blocks of code intended to behave like mathematical functions.

James Tam
Structured Programming

•At a low level, structured programs are often composed of


simple, hierarchical program flow structures. These are
sequence, selection, and repetition:
•"Sequence" refers to an ordered execution of statements.
•In "selection" one of a number of statements is executed
depending on the state of the program. This is usually expressed
with keywords such as if..then..else..endif, switch, or case.
•In "repetition" a statement is executed until the program
reaches a certain state.This is usually expressed with keywords
such as while, repeat, for or do..until.

James Tam
Object-Oriented Programming
•Object-oriented programming organizes a program around its data
(that is, objects) and a set of well-defined interfaces to that data. An
object-oriented program can be characterized as data controlling
access to code
•All object-oriented programming languages provide mechanisms that
help us implement the object-oriented model. They are Abstraction,
encapsulation, inheritance, and polymorphism
•Abstraction: An essential element of object-oriented programming
is abstraction. Abstraction refers to the act of representing essential
features without including the background details or explanations.
• Encapsulation : Encapsulation is the way of combining both data
and the functions that operate on that data under a single unit. So
Encapsulation is the wrapping upof data and function that oprate on
the data into a single unit(called class) is known as Encapsulation.
James Tam
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class. Inheritance supports the concept of hierarchical classification.In OOP
,the concept of Inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it.This is possible by deriving a new
class from the existing one.
Polymorphism:Polymorphism allows one interface to be used for a set of actions i.e. one
name may refer to different functionality. There are two types of polymorphism :
Compile-time polymorphism
Runtime Polymorphism
In compiletime Polymorphism, method to be invoked is determined at the compile time.
Compile time polymorphism is supported through the method overloading concept in java. 
In rumtime polymorphism, the method to be invoked is determined at the run time. The
example of run time polymorphism is method overriding. When a subclass contains a method
with the same name and signature as in the super class then it is called as method overriding.

Object : An object is an identifiable entity having common characteristic and behaviour.The


state of an object is represented through the values/atributes of its charateristics at a given
point of time.Characteristics /attributues are implemented through member variables or data
items of object. Behaviour is implemented through member functions called methods.
Class: A class is a collection of Objects that share common charactersitics and
behaviour.Basically the class is an Object maker or object factory. It contains all the
statements needed to create an object, it attributes as well as the statement to describe the
operations that the object will be able to perform.
James Tam
Getting Started with Java Programming

•Java can be used to create two types of programs: applications


and applets.
•An application is a program that runs on your computer, under
the operating system of that computer,
•An applet is an application designed to be transmitted over the
Internet and executed by a Java-compatible Web browser.
•An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound file,
or video clip

James Tam
Java Program Structure
Documentation Section (Optional)

Package Statement (Optional)

Import Statement (Optional)

Interface Statement (Optional)

Class Definition (Optional)

Main Method class Essential


{
Main Method definition
}

James Tam
• Documentation Section: It comprises a set of comments line giving the name
of the program,and other.
• Package Statement : The first statement allowed in a Java file is a package
statement. this statement declare a package name and informs the compiler that
the classes defined here belong to this package. Ex: package student;
• Import Statement: This statement instruct the interpreter to load the class
contained in the mentioned package followed by the import statement. Ex:
import student.*;
• Interface Statement: An interface is like a class and is used when we wish to
implement the multiple inheritance feature in program.
• Class Definition: A Java program may contain multiple class definition. these
classes are used to map the objects of real-world problem.
• Main Method Class: This class is the essential part of the program. The main
method creates objects of various classes and establish communication between
them.

James Tam
A Simple Application

Example 1.1
//This application program prints Welcome
//to Java!
package student;

public class Welcome {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

James Tam
Program Explanation
• “class Welcome” defines the class Welcome. Here class is a keyword.
The main line Public static void main(String[]args):
• Public: The key word public is an access specifier that declare the main method is
accessible to all other classes.
• Static: The key word static declares this method as one that belongs to the entire class
and not a part of an objects of the class.Interpreter use this method before any objects
are created.
• Void: The type modifier void states that the main method does not return any value.
• main: main( ) is a method,must be declared as public, since it must be called
by code outside of its class when the program is started. The keyword static allows
main( ) to be called without having to instantiate a particular instance of the class. This
is necessary since main( ) is called by the Java interpreter before any objects are made.
• In main( ), there is only one parameter, String args[ ] declares a parameter named
args, which is an array of instances of the class String. args receives any command-
line arguments present when the program is executed.

James Tam
Java Output
• The Output Line: System.out.println(“………….”); The
Println Method is a member of the out object, which is a static
member of System class.
•Format:
System.out.print(<string or variable name one> + <string or variable name
two>..);
OR
System.out.println(<string or variable name one> + <string or variable name
two>..);

•Examples (online program called “OutputExample1.java”)

public class OutputExample1


{
public static void main (String [] args)
{
int num = 123; // More on this shortly
System.out.println("Good-night gracie!");
System.out.print(num);
System.out.println("num="+num);
}
} James Tam
Output : Some Escape Sequences For Formatting

Escape sequence Description

\t Horizontal tab

\r Carriage return

\n New line

\” Double quote

\\ Backslash

James Tam
Example Formatting Codes

•Name of the online example: FormattingExample.java

public class FormattingExample


{
public static void main (String [] args)
{
System.out.print("lol\tz\n");
System.out.println("hello\rworld");
System.out.println("\"Geek\" talk slash (\\) com");
}
}

James Tam
Variables

• A variable is an identifier that denotes a storage location used


to store data value.
•Variable declaration:
- Creates a variable in memory.
- Specify the name of the variable as well as the type of information that it
will store.
- E.g. int num;
•Using variables
- Only after a variable has been declared can it be used.
- E.g., num = 12;

James Tam
Variable Naming Conventions In Java

• Compiler requirements
- Can’t be a keyword nor can the names of the special constants: true,
false or null be used
- Can be any combination of letters, numbers, underscore or dollar sign
(first character must be a letter or underscore)

• Common stylistic conventions


- The name should describe the purpose of the variable
- Avoid using the dollar sign
- With single word variable names, all characters are lower case
• e.g., double grades;
- Multiple words are separated by capitalizing the first letter of each
word except for the first word
• e.g., String firstName = “James”;

James Tam
Declaring Variables: Syntax

•Format:
<type of information> <name of variable>;

•Example:
char myFirstInitial;

•Variables can be initialized (set to a starting value) as they’re


declared:
•Variablename=value;
•Or type variablename=value;
char myFirstInitial = ‘j’;
int age = 30;

James Tam
Location Of Variable Declarations

public class <name of class>


{
public static void main (String[] args)
{
// Local variable declarations occur here

<< Program statements >>


: :

}
}

James Tam
Scope of Variables

• The area of the program where the variable is accessible is


called its scope.
•Java variables are classified into three kinds
•Instance Variable: Instance variables are declared inside a
class.These are created when the objects are instantiated and
therefore they are associated with the Objects.
• Class Variable: Class variables are declared inside a
class.These are global to a class and belong to the entire set of
objects that class creates.
•Local Variable: Variables declared and used inside methods
are called Local variables. They are called so because they are
not available for use outside the method defination.

James Tam
Local Variable
•Local variables :
•Local variables are declared in methods, constructors, or blocks.
•Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor or block.
•Access modifiers cannot be used for local variables.
•Local variables are visible only within the declared method,
constructor or block.
•Local variables are implemented at stack level internally.
•There is no default value for local variables so local variables should
be declared and an initial value should be assigned before the first
use

James Tam
Local Variable Example
Here age is a local variable. This is defined inside pupAge() method
and its scope is limited to this method only.
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[])
{ Test test = new Test();
test.pupAge();
}
} This would produce following result: Puppy age is: 7
James Tam
Instance variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the key word 'new'
and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object through out the class.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
Normally it is recommended to make these variables private (access level).However
visibility for subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values. For numbers the default value is 0, for Booleans it is
false and for object references it is null. Values can be assigned during the declaration or
within the constructor.
• Instance variables can be accessed directly by calling the variable name inside the class.
However within static methods and different class ( when instance variables are given
accessibility) the should be called using the fully qualified name .
ObjectReference.VariableName.

James Tam
Instance Variable Example
• import java.io.*;
public class Employee{
public String name; // this instance variable is visible for any child class.
private double salary; // salary variable is visible in Employee class only.
public Employee (String empName)//The name variable is assigned in the constructor.
{ name = empName; }
public void setSalary(double empSal) // The salary variable is assigned a value.
{ salary = empSal; }
public void printEmp() // This method prints the employee details.
{ System.out.println("name : " + name );
System.out.println("salary :" + salary); }
public static void main(String args[])
{ Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
} } Output: name : Ransika salary :1000.0
James Tam
Class/Static Variable
• Class variables also known as static variables are declared with the static keyword in a
class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
• Static variables are stored in static memory. It is rare to use static variables other than
declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
• Default values are same as instance variables. For numbers the default value is 0, for
Booleans it is false and for object references it is null. Values can be assigned during the
declaration or within the constructor. Additionally values can be assigned in special static
initializer blocks.
• Static variables can be accessed by calling with the class name . ClassName.VariableName.
• When declaring class variables as public static final, then variables names (constants) are all
in upper case. If the static variables are not public and final the naming syntax is the same
as instance and local variables.

James Tam
Class/Static variable example
•import java.io.*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[])
{ salary = 1000;
System.out.println(DEPARTMENT+"average salary:"+salary);
} } This would produce following result:
•Development average salary:1000
•Note: If the variables are access from an outside class the constant
should be accessed as Employee.DEPARTMENT
James Tam
Java Constants

Reminder: constants are like variables in that they have a name


and store a certain type of information but unlike variables they
CANNOT change.
Format:
final <constant type> <CONSTANT NAME> = <value>;

Example:
final int SIZE = 100;

James Tam
Atomic elements(Tokens) of Java

•Java programs are a collection of whitespace, identifiers,


comments, literals, operators, separators, and keywords.
• Whitespace : In Java, whitespace is a space, tab, or newline.
•Identifiers : Identifiers are used for class names, method names,
and variable names. An identifier may be any descriptive sequence
of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. Ex. AvgTemp,count,a4,$test,this_is_ok
•Literals: A constant value in Java is created by using a literal
representation of it.Ex:100,98.6, ‘X’,“This is a test”
•Comments : There are three types of comments defined by Java.
single-line (//), multiline (/*…………….*/)and documentation
comment( /**………….a */).

James Tam
•Separators
In Java, there are a few characters that are used as separators. The
most commonly used separator in Java is the semicolon.
Symbol Name Purpose
() Parentheses Used to contain lists of parameters in method
{} Braces Used to contain the values of automatically
initialized arrays. Also used to define a block
of code, for classes, methods, and local
scopes.
[ ]  Brackets Used to declare array types
; Semicolon Terminates statements.
, Comma Separates consecutive identifiers in a variable
declaration
.  Period Used to separate package names from
subpackages and classes. Also used to separate
a variable or method from a reference variable
James Tam
Java Keywords

abstract boolean break byte case catch char

class const continue default do double else

extends final finally float for goto if

implements import instanceof int interface long native

new package private protected public return short

static super switch synchronized this throw throws

transient try void volatile while

James Tam
Common Java Operators / Operator Precedence

Precedence Operator Description Associativity


level

1 expression++ Post-increment Right to left


expression-- Post-decrement

2 ++expression Pre-increment Right to left


--expression Pre-decrement
+ Unary plus
- Unary minus
! Logical negation
~ Bitwise complement
(type) Cast

James Tam
Common Java Operators / Operator Precedence

Precedence Operator Description Associativity


level

3 * Multiplication Left to right


/ Division
% Remainder/modulus
4 + Addition or String Left to right
concatenation
- Subtraction
5 << Left bitwise shift Left to right
>> Right bitwise shift

James Tam
Common Java Operators / Operator Precedence

Precedence Operator Description Associativity


level

6 < Less than Left to right


<= Less than, equal to
> Greater than
>= Greater than, equal to
7 == Equal to Left to right
!= Not equal to
8 & Bitwise AND Left to right

9 ^ Bitwise exclusive OR Left to right

James Tam
Common Java Operators / Operator Precedence

Precedence Operator Description Associativity


level
10 | Bitwise OR Left to right

11 && Logical AND Left to right

12 || Logical OR Left to right

James Tam
Common Java Operators / Operator Precedence

Precedence Operator Description Associativity


level

13 = Assignment Right to left


+= Add, assignment
-= Subtract, assignment
*= Multiply, assignment
/= Division, assignment
%= Remainder, assignment
&= Bitwise AND, assignment
^= Bitwise XOR, assignment
|= Bitwise OR, assignment
<<= Left shift, assignment
>>= Right shift, assignment

James Tam
Post/Pre Operators
The name of the online example is: Order1.java

public class Order1


{
public static void main (String [] args)
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
}
}
James Tam
Post/Pre Operators (2)

The name of the online example is: Order2.java

public class Order2


{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5;
num2 = ++num1 * num1++;
System.out.println("num1=" + num1);
System.out.println("num2=" + num2);
}
}

James Tam
Conditional(Ternary) Operator

• Java includes a special ternary (three-way) operator that can


replace certain types of if-then-else statements.
Format: expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a
boolean value. If expression1 is true, then expression2 is
evaluated; otherwise, expression3 is evaluated.
• Example:
int x=15;
String a=(x>0)? “positive”: “negative”
System.out.println(a);

James Tam
Data Types

•Data types specify the size and type of values that can be stored.
•Two types : Primitive type(intrinsic,built-in)and Non-
Primitive(derived)
•Primitive type(intrinsic,built-in): Numeric(Integer,Floating),Non-
Numeric(Character,Boolean)
•Non-Primitive(Derived): Classes,Interface,Arrays

James Tam
Primitive Data Types

Data type Range of values

byte -128 .. 127 (8 bits)


short -32,768 .. 32,767 (16 bits)
int -2,147,483,648 .. 2,147,483,647 (32 bits)
long -9,223,372,036,854,775,808 .. ... (64 bits)
float +/-10-38 to +/-10+38 and 0, about 6 digits precision(4
bytes)
double +/-10-308 to +/-10+308 and 0, about 15 digits precision(8
bytes)
char Unicode characters (generally 16 bits per char)
boolean True or false
James Tam
Accessing Pre-Created Java Libraries

•It’s accomplished by placing an ‘import’ of the appropriate


library at the top of your program.
•Syntax:
import <Full library name>;

•Example:
import java.util.Scanner;

James Tam
Control Statement In Java

• programming language uses control statements to cause the


flow of execution to advance and branch based on changes to
the state of a program.
•Java’s program control statements can be put into the following
categories: selection, iteration, and jump.
• Selection Statement: Selection statements allow your program
to choose different paths of execution based upon the outcome
of an expression or the state of a variable .There are three types
of selection statement in Java, such as, if, if-else, switch.
• Iteration statements enable program execution to repeat one or
more statements. Ex. For, While, Do…While
• Jump statements allow your program to execute in a nonlinear
fashion. Ex. Break, Continue, Return.
James Tam
Decision Making: If Statement

1.Simple If Statement
2.If … else Statement
3. Nested if … else statement
4.Else if ladder

James Tam
Simple if Statement
•The if statement is Java’s conditional branch statement. It can be
used to route program execution through two different paths.
•Syntax :
if (condition)
{
     statement1;
}
•When the condition is true the Statement within the if is
executed. After that execution continues with the next statement
after the if statement. 
• If the condition is false then the statement within the if is not
executed and the execution continues with the statement after the
if statement.
James Tam
Example of If Statement
•EX.
import java.util.Scanner;
class larger1
{
        public static void main(String args[])
        {
                int x1,x2,x3,large;
                Scanner s = new Scanner(System.in);
                System.out.println("Enter value for x1 : ");
                x1=s.nextInt();
                System.out.println("Enter value for x2 : ");
                x2=s.nextInt();
               System.out.println("Enter value for x3 : ");
                x3=s.nextInt();
                large = x1;
                if (x2 > large)
                        large = x2;
                if (x3 > large)
                        large = x3;
                System.out.println("\n\n\tLargest number = " + large);
        }
} Output :     Largest number = 20 James Tam
Decision Making: Simple If

Format:
if (test Expression)
{
Body
}
Example:
if (x != y)
{ System.out.println("X and Y are not equal");}

if ((x > 0) && (y > 0))


{
System.out.println("X and Y are positive");
}

James Tam
Decision Making: If, Else

Syntax :
if (condition)
{
    statement1;
}
else If the condition is true, then
{ statement1 is executed. Otherwise,
statement2 is executed. In no case
    statement2;
will both statements be executed.
}
Example:
if (x < 0)
{ System.out.println("X is negative");}
else
{ System.out.println("X is non-negative");}
James Tam
Example Program: If-Else
import java.util.Scanner;
class result
{
        public static void main(String args[])
        {
                Scanner s = new Scanner(System.in);
                System.out.println("Enter marks : ");
                int marks = s.nextInt();
                if (marks<40)
                        System.out.println("\nThe student has failed .. ");
                else
                        System.out.println("\nThe student has Passed .. ");
        }
}

James Tam
Nested –If..Else

•Format:
if(test expression)
{
if(test expression)
{
body;
}
else
{ }
else
{
} James Tam
Else if Ladder

Syntax : The if statements are executed from the top down.


As soon as one of the conditions controlling the if is
if(condition) true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. 
  statements;  
else if(condition) If none of the conditions is true, then the final else
statement will be executed. The final else acts as a
  statemenst; default condition; that is, if all other conditional tests
fail, then the last else statement is performed. 
else if(condition)  
If there is no final else and all other conditions are
  statements; false, then no action will take place.
...
...
else
  statements;
James Tam
Example Else-If Ladder
if (gpa == 4)
System.out.println("A");
else if (gpa == 3)
System.out.println("B");
else if (gpa == 2)
System.out.println("C");
else if (gpa == 1)
System.out.println("D");
else if (gpa == 0)
System.out.println("F");
else
System.out.println("Invalid letter grade");
}
}

James Tam
Switch:
• The switch statement is Java’s is a multiway branch statement. It provides an
easy way to dispatch execution to different parts of your code based on the
value of an expression.
• The expression must be of type byte, short, int, or char; each of the values
specified in the case statements must be of a type compatible with the expression.
• Each case value must be a unique literal (constant, not a variable). Duplicate case
values are not allowed.
• The value of the expression is compared with each ‘case’ values. If a match is
found, the corresponding statement or statements are executed.
• If no match is found, statement or statements in the default case are executed.
Default statement is optional.
• If default statement is absent, then if no matches are found, then the switch
statement completes without doing anything.
• The break statement is used inside the switch to terminate a statement sequence

James Tam
Alternative To Multiple Else-If’s: Switch

Format (character-based switch):


switch (character variable name)
{
case '<character value>':
Body
break;

case '<character value>':


Body
break;
:
default:
Body
}

1 The type of variable in the brackets can be a byte, char, short, int or long

James Tam
Alternative To Multiple Else-If’s: Switch (2)

Format (integer based switch):


switch (integer variable name)
{
case <integer value>:
Body
break;

case <integer value>:


Body
break;
:
default:
Body
}

1 The type of variable in the brackets can be a byte, char, short, int or long

James Tam
Switch: Example

•Name of the online example: SwitchExample.java

import java.util.Scanner;

public class SwitchExample


{
public static void main (String [] args)
{
final int FIRST = 0;
String line;
char letter;
int gpa;
Scanner in = new Scanner (System.in);
System.out.print("Enter letter grade: ");

James Tam
Switch: Example
line = in.nextLine ();
letter = line.charAt(FIRST);
switch (letter)
{
case 'A':
case 'a':
gpa = 4;
break;

case 'B':
case 'b':
gpa = 3;
break;

case 'C':
case 'c':
gpa = 2;
break;

James Tam
Switch: When To Use/When Not To Use (4)
case 'D':
case 'd':
gpa = 1;
break;

case 'F':
case 'f':
gpa = 0;
break;

default:
gpa = -1;

}
System.out.println("Letter grade: " + letter);
System.out.println("Grade point: " + gpa);
}
}

James Tam
Iteration Statement(Loops)

•Loop: The process of repeatedly executing a block of


statements is known as looping.
•In looping ,a sequence of statements are executed until some
conditions for the termination of the loop are satisfied.
•A program loop therefore consists of two segments, body of the
loop, control statement.
•Depending on the position of the control statement in the loop, a
control structure may be classified as
Entry-controlled(Pre-test) loop,
exit-controlled(Post-test) loop.

James Tam
Iteration Statement(Loops)

Entry-controlled(Pre-test) loop:
•The control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, then the body of
the loop will not be executed.
Example: for, while
exit-controlled(Post-test) loop:
• The control conditions are performed at the end of the body of
the loop and therefore the body of the loop executed at least
once.
Example: do-while

James Tam
For Loops
Format:
for (initialization; test condition; update control)
{ Body of the loop;
}

Example:
for (i = 1; i <= 4; i++)
{
// Call function
createNewPlayer();
i = i + 1;
}
Nested for Loop: Format: for(i=0li<10;i++)
{
for(j=0;j<10;j++)
{ }
}
James Tam
For loop variation

•More than one variable can be initialized at a time Ex.


For(a=0,x=10;a<10;a++)
• The increment section may have more than one part. Ex.
For(a=0,x=10;a<10;a++,x--)
•The test condition may have any compound relation.Ex.
For(i=1;i<10 && sum<50;i++)
•One or more section in loop can be omitted. Ex(for(;i<10;)
•If the test condition is omitted, it becomes an infinite loop.Ex .
For(i=1; ; i++)
•We can set up time delay using the null statement., it is done by
giving semicolon at the end.Ex. For(i=1;i<1000;i++); this is also
called empty statement.the loop will execute 1000 times without
producing any output.
James Tam
While Loops

Format: Initialization;
while (test condition)
{
Body of the loop;
updating;
}

Example:
int i = 1;
while (i <= 4)
{
// Call function
createNewPlayer();
i = i + 1;
}

James Tam
Post-Test Loop: Do-While

•Recall: Post-test loops evaluate the text condition after the body
of the loop has executed.
•This means that post test loops will execute one or more times.
•Pre-test loops generally execute zero or more times.

James Tam
Do-While Loops
Format:
Initialization;
do
{
Body of the loop;
updating;
}while (test condition);
Example:
char ch = 'A';
do
{
System.out.println(ch);
ch++;
}
while (ch <= 'K');

James Tam
The Enhanced for Loop
• The enhanced for loop is also called for each loop , is an extended language feature
introduced with the J2SE5.0 release. This feature helps us to retrieve the array of
elements efficiently rather than using array indexes.
Format: for(Type identifier : Expression) { //statements; } where, type represents
the data type or object used, Identifier refers to the name of a variable; and
Expression is an instance of the java.lang.Iterable interface or an array.
• Example: public class Test {
public static void main(String args[])
{ int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ){ System.out.print( x );
System.out.print(","); }
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names )
{ System.out.print( name );
System.out.print(","); } } }

James Tam
Jump Statements

• Java permits a jump from one statement to the end or beginning


of a loop as well as a jump out of a loop.
•Java supports three jump statements: break, continue, and
return.
•Break: When the break statement is encountered inside a loop,
the loop is immediately exited and the program continues with
the statement immediately following the loop. when the loops
are nested, the break would only exit from the loop containing
it.
•Continue: as the name implies, it causes the loop to be
continued with the next iteration after skipping any statements
in between.

James Tam

You might also like