You are on page 1of 56

History of Java

 In the early 1990's, putting intelligence into home appliances was thought to be the
next "hot" technology.
 Examples of intelligent home appliances:
 Coffee pots and lights that can be controlled by a computer's programs.
 Televisions that can be controlled by an interactive television device's programs.
 Anticipating a strong market for such things, Sun Microsystems in 1991 funded a
research project (code named Green) whose goal was to develop software for
intelligent home appliances.
 An intelligent home appliance's intelligence comes from its embedded processor chips
and the software that runs on the processor chips.
 To handle the frequent turnover of new chips, appliance software must be extremely
portable.
 Originally, Sun planned to use C++ for its home appliance software, but they soon
realized that C++ was less than ideal because it wasn't portable enough and it relied
too heavily on hard-to-maintain things called pointers.
 Thus, rather than write C++ software and fight C++'s inherent deficiencies, Sun
decided to develop a whole new programming language to handle its home appliance
software needs.
 Their new language was originally named Oak (for the tree that was outside project
leader James Gosling's window), but it was soon changed to Java.
 When the home appliance software work dried up, Java almost died before being
released.
 Fortunately for Java, the World Wide Web exploded in popularity and Sun realized it
could capitalize on that.
 Web pages have to be very portable because they can be downloaded onto any type of
computer.
 What's the standard language used for Web pages?
 Java programs are very portable and they're better than HTML in terms of providing
user interaction capabilities.
 Java programs that are embedded in Web pages are called applets.
 Although applets still play a significant role in Java's current success, some of the
other types of Java programs have surpassed applets in terms of popularity.
 In this course, we cover Standard Edition (SE) Java applications. They are Java
programs that run on a standard computer – a desktop or a laptop, without the need
of the Internet.

Object Oriented Programming

 When we approach a programming problem is an OOP ( Object Oriented


Programming ), we are no longer ask how the problem will be divided into
functions, but think how it will be divided into objects.
 Thinking in terms of objects rather than functions has a helpful effect on
design process of programs because it’s closed match between objects in
programming sense and objects in real worlds.
 Read world objects are made up of both data and functions. Both are
combined into a single program entity. Where data represents Attribute
(State) and Functions represents = Behavior of an object.
 Data and its functions are said to be encapsulated into a single entity.

Benefits of OOPs Programming


 Readability
 Understandability
 Low Probability of Error.
 Maintenance
 Reusability
 Teamwork

The object-oriented approach

The program is written as a collection of interacting objects.


Why objects?

Because the world is made from distinct objects, which consist of other
objects, etc., and this is often a natural and powerful way of
representing a situation or problem.

 An object represents an individual, identifiable item, unit, or


entity, either real or abstract, with a well-defined role in the
problem domain.
Or
An "object" is anything to which a concept applies.
What is a software object?
An object has two components:
1. State information which describes the current characteristics of
the object and
2. Behaviour which describes how it interacts with other objects.
Why do we care about objects?

 Modularity - large software projects can be split up in smaller


pieces.
 Reusability - Programs can be assembled from pre-written
software components.
 Extensibility - New software components can be written or
developed from existing ones.

Software representation of a cat object

STATE BEHAVIOUR
• Name • Sleeps a lot
• Breed • Scratches
• Weight furniture
• Age • Catches mice
• Asleep • Fights other cats

Examples of OO languages

 C++
Classic example uses C syntax
 Java
Based on C++, often used for Web and graphics
 Visual Basic, Visual C++
Windows programming
Implementation of objects

State is usually held as local


variables (also called properties),
STATE quantities not visible outside the
object (data hiding)

Behaviour controlled by
method functions or
BEHAVIOUR subroutines which act on the
local variables and interface
with the outside.

J Advantage
Objects provide a powerful and natural approach for representing many problems.
Features such as inheritance allow already written objects to be re-used – program
modification in OOP’s is comparatively easier. OOP’s Paradigm (Abstraction,
Encapsulation, data hiding, Inheritance, Polymorphism)

L Disadvantages
Certainly more difficult than conventional programming some concepts are relatively
hard, even for experienced programmers Implementation of objects often use
complicated syntax/semantics OOP is comparatively not famous for efficiency
(memory or execution time).

Why Java?
 It’s the current “hot” language
 It’s almost entirely object-oriented
 It has a vast library of predefined objects and operations
 Its more platforms independent.
 This makes it great for Web programming
 It’s more secure
 It isn’t C++

OOP Paradigm

Paradigm means “Rules and Regulation”. So OOP paradigm means “Object


Oriented Programming” rules and regulation. This can be defined under the certain
points…

 Abstraction = Hiding our irrelevance data


 Encapsulation = Protecting the data
 Data Hiding / Information hiding = Hide the inner data from outer world
 Inheritance = New Classes from existing
 Polymorphism = Different behaviors at diff. Instance.

C++ and Java

 Java is a full object oriented language, all code has to go into classes.

 C++ - in contrast - is a hybrid language, capable both of functional and


objects oriented programming.

The two steps of Object Oriented Programming

 Making Classes: Creating, extending or reusing abstract data types.

 Making Objects interact: Creating objects from abstract data types and
defining their relationships.

 Classes reflect concepts, objects reflect instances that embody those


concepts
Compilation process / Steps of a java program

Editor Program is created in the


Phase 1 Disk
editor and stored on disk.

Compiler Disk Compiler creates bytecodes


Phase 2 and stores them on disk.
Primary
Memory
Class Loader
Phase 3
Class loader puts byte
Disk .. codes in memory.
..
..
Primary
Memory
Bytecode Verifier
Byte code verifier confirms
Phase 4
that all byte codes are
valid and do not violate
Java’s security
.. restrictions.
..
..
Primary
Interpreter Memory
Phase 5 Interpreter reads bytecodes
and translates them into a
language that the computer
..
can understand, possibly
.. storing data values as
.. the program executes.

Java Virtual Machine


How can bytecode be run on any type of computer?
As a Java program’s bytecode runs, the bytecode is translated into object code by the
computer's bytecode interpreter program. The bytecode interpreter program is known as
the Java Virtual Machine or JVM for short. The next slide shows how the JVM
translates bytecode to object code. It also shows how a Java compiler translates source
code to bytecode.
In the Java programming language, all source code is first written in plain text files
ending with the .java extension. Those source files are then compiled into .class
files by the javac compiler. A .class file does not contain code that is native to your
processor; it instead contains bytecodes the machine language of the Java Virtual
Machine (Java VM). The java launcher tool then runs your application with an
instance of the Java Virtual Machine

Compiling and running a java program

Because the Java VM is available on many different operating systems, the same .class
files are capable of running on Microsoft Windows, the Solaris Operating System (Solaris
OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine,
perform additional steps at runtime to give your application a performance boost. This
includes various tasks such as finding performance bottlenecks and recompiling (to native
code) frequently used sections of code.

Through the JVM, the same application is capable of running on multiple platforms.
First Java program:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
} // end class Hello

Class Name / Source Code Filename

 All Java programs must be enclosed in a class. Think of a class as the name of the
program.
 The name of the Java program's file must match the name of the Java program's class
(except that the filename has a .java extension added to it).
 Proper style dictates that class names start with an uppercase first letter.
 Since Java is case-sensitive, that means the filename should also start with an uppercase
first letter.
 Case-sensitive means that the Java compiler does distinguish between lowercase and
uppercase letters.

main() Method Heading

In the Java programming language, every application must contain a main method whose
signature is:

public static void main(String[] args)

 Memorize (and always use) public class prior to your class name. For example:
 public class Hello
 Inside your class, you must include one or more methods.
 A method is a group of instructions that solves one task. Later on, we'll have larger
programs and they'll require multiple methods because they'll solve multiple tasks. But
for now, we'll work with small programs that need only one method - the main method.
 Memorize (and always use) this main method heading:
 public static void main(String[] args)
 When a program starts, the computer looks for the main method and begins execution
with the first statement after the main method heading.

Braces
 Use braces, { }, to group things together.
 For example, in the Hello World program, the top and bottom braces group the
contents of the entire class, and the interior braces group the contents of the main
method.
 Proper style dictates:
 Place an opening brace on a line by itself in the same column as the first character of the
previous line.
 Place a closing brace on a line by itself in the same column as the opening brace.

System.out.print

 To generate output, use System.out.print().


 For example, to print the hello message, we did this:
 System.out.print("Hello, world!");
Note:
 Put the printed item inside the parentheses.
 Surround strings with quotes.
 Put a semicolon at the end of a System.out.println statement.

Compilation and Execution

 To create a Java program that can be run on a computer, submit your Java source code
to a compiler. We say that the compiler compiles the source code. In compiling the
source code, the compiler generates a bytecode program that can be run by the
computer's JVM (Java Virtual Machine).
 Java source code filename = <class-name> + .java
 Java bytecode filename = <class-name> + .class

Identifiers
 Identifier = the technical term for a name in a programming language
 Identifier examples –
 class name identifier: Hello
 method name identifier: main
 variable name identifier: height
 Identifier naming rules:
 Must consist entirely of letters, digits, dollar signs ($), and/or underscore (_) characters.
 The first character must not be a digit.
 If these rules are broken, your program won't compile.

Identifier naming conventions (style rules):

 If these rules are broken, it won't affect your program's ability to compile, but your
program will be harder to understand and you'll lose style points on your homework.
 Use letters and digits only, not $'s or _'s.
 All letters must be lowercase except the first letter in the second, third, etc. words. For
example:
 firstName, x, daysInMonth
 Addendum to the above rule – for class names, the first letter in every word (even the
first word) must be lowercase. For example:
 StudentRecord, WorkShiftSchedule
 Names must be descriptive.

Variables

 A variable can hold only one type of data. For example, an integer variable can hold
only integers, a string variable can hold only strings, etc.
 How does the computer know which type of data a particular variable can hold?
 Before a variable is used, its type must be declared in a declaration statement.
 Declaration statement syntax:
 <type> <list of variables separated by commas>;
 Example declarations:
 String firstName; // student's first name
 String lastName; // student's last name
 int studentId;
 int row, col;

Assignment Statements

 Java uses the single equal sign (=) for assignment statements.
 In the below code fragment, the first assignment statement assigns the value 50000 into
the variable salary.
 int salary;
 String bonusMessage;
 salary = 50000; Commas are not allowed in
numbers.
 bonusMessage = "Bonus = $" + (.02 * salary);

string concatenation
 Note the + operator in the second assignment statement. If a + operator appears
between a string and something else (e.g., a number or another string), then the +
operator performs string concatenation. That means that the JVM appends the item at
the right of the + to the item at the left of the +, forming a new string.
Constants

 A constant is a fixed value. Examples:


 8, -45, 2000000 : integer constants
 -34.6, .009, 8. : floating point constants
 "black bear", "hi" : string constants
 The default type for an integer constant is int (not long).
 The default type for a floating point constant is double (not float).
 This example code generates compilation errors. Where and why?
float gpa = 2.30;
float mpg;
mpg = 28.6;
 Possible Solutions:
Always use double variables instead of float variables.
or
To explicitly force a floating point constant to be float, use an f or F suffix. For example:
float gpa = 2.30f;
float mpg;
mpg = 28.6F;

Program Template

Import java.io.*;
public class Test
{
public static void main(String [ ] args)
{
<method-body>
}
} // end class Test

Initialization Statements

 Initialization statement:
Initialization statement is use to assign a value to a variable as part of the variable's
declaration.
 Initialization statement syntax:
<type> <variable> = <value>;
 Example initializations:
int totalScore = 0; // sum of all bowling scores
int maxScore = 300; // default maximum bowling score
 Example initializations (repeated from previous slide):
int totalScore = 0; // sum of all bowling scores
int maxScore = 300; // default maximum bowling score
 Here's an alternative way to do the same thing using declaration and assignment
statements (instead of using initialization statements):
int totalScore; // sum of all bowling scores
int maxScore; // default maximum bowling score
totalScore = 0;
maxScore = 300;
 It's OK to use either technique and you'll see it done both ways in the real world.

Primitive data types

The Java programming language is strongly typed, which means that all variables must first
be declared before they can be used. This involves stating the variable's type and name, as
you've already seen:

int gear = 1;

Doing so tells your program that a field named "gear" exists, holds numerical data, and has
an initial value of "1". A variable's data type determines the values it may contain, plus the
operations that may be performed on it. In addition to int, the Java programming language
supports seven other primitive data types. A primitive type is predefined by the language
and is named by a reserved keyword. Primitive values do not share state with other
primitive values. The eight primitive data types supported by the Java programming
language are:

Data type No of bits Minimum Value Maximum Value

Byte 8 - 27 = ( - 128 ) 27 – 1 = ( 127 )


15
Short 16 -2 = ( - 32768 ) 215 – 1 = ( 32767 )
31
-2 231 – 1
Int 32
- 2,147,483,648 2,147,483,647
63
Long 64 -2 263
9,223,372,036,854,775,808 9,223,372,036,854,775,808

Float 32 - 231 231 – 1


Double 64 - 263 263 – 1
Boolean 1 0 fasle 1 true

Char 16 '\u0000' '\uffff' or 65535


byte The byte data type is an 8-bit signed two's complement integer. It has a
minimum value of 128 and a maximum value of 127 (inclusive). The byte data type can be
useful for saving memory in large arrays, where the memory savings actually matters. They
can also be used in place of int, where their limits help to clarify your code; the fact that a
variable's range is limited can serve as a form of documentation.

Short The short data type is a 16-bit signed two's complement integer. It has a
minimum value of 32,768 and a maximum value of 32,767 (inclusive). As with byte, the
same guidelines apply: you can use a short to save memory in large arrays, in situations
where the memory savings actually matters.

Int The int data type is a 32-bit signed two's complement integer. It has a minimum
value of 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral
values, this data type is generally the default choice unless there is a reason (like the above)
to choose something else. This data type will most likely be large enough for the numbers
your program will use, but if you need a wider range of values, use long instead.

Long The long data type is a 64-bit signed two's complement integer. It has a
minimum value of 9,223,372,036,854,775,808 and a maximum value of
9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values
wider than those provided by int.

float The float data type is a single-precision 32-bit IEEE 754 floating point. Its range
of values is beyond the scope of this discussion. As with the recommendations for byte and
short, use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. This data type should never be used for precise values, such as currency.
For that, you will need to use the java.math.BigDecimal.

double The double data type is a double-precision 64-bit IEEE 754 floating point. Its
range of values is beyond the scope of this discussion. For decimal values, this data type is
generally the default choice. As mentioned above, this data type should never be used for
precise values, such as currency.

Boolean The boolean data type has only two possible values: true and false. Use this
data type for simple flags that track true/false conditions. This data type represents one bit
of information, but its "size" isn't something that's precisely defined.

Char The char data type is a single 16-bit Unicode character. It has a minimum value
of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

In addition to the eight primitive data types listed above, the Java programming language
also provides special support for character string via the java.lang.String class.
Enclosing your character string within double quotes will automatically create a new
String object;
for example, String s = "this is a string";

String objects are immutable, which means that once created, their values cannot be
changed. The String class is not technically a primitive data type, but considering the
special support given to it by the language.

 Example code for basic string manipulations:

String s1; declaratio


n
String s2 = "and I say hello"; initializatio
assignmen n
s1 = "goodbye";
t
s1 = "You say " + s1; concatenation, then
assignment
s1 += ", " + s2 + '.';
concatenation, then compound
System.out.println(s1); assignment

Operators

Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.

The operators cited below are listed according to precedence order. The closer to the top of
the table an operator appears, the higher its precedence. Operators with higher precedence
are evaluated before operators with relatively lower precedence. Operators on the same line
have equal precedence. When operators of equal precedence appear in the same expression,
a rule must govern which is evaluated first. All binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right to left.

Operator Precedence
Operators Precedence
postfix expr++ expr--

unary ++expr --expr +expr -expr ~ !

multiplicative * / %
additive + -

relational < > <= >= instanceof

equality == !=
Operator Precedence
Operators Precedence
logical AND &&

logical OR ||

ternary ? :

assignment = += -= *= /= %= &= ^= |= <<= >>=

Assignment, Arithmetic, and Unary Operators

The Simple Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator
"=". It assigns the value on its right to the operand on its left:

int cadence = 0;
int speed = 0;
int gear = 1;

This operator can also be used on objects to assign object references

The Arithmetic Operators

The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their
counterparts in basic mathematics. The only symbol that might look new to you is "%",
which divides one operand by another and returns the remainder as its result.

+ additive operator (also used for String concatenation)


- subtraction operator
* multiplication operator
/ division operator
% remainder operator

The Unary Operators

The unary operators require only one operand; they perform various operations such as
incrementing/decrementing a value by one, negating an expression, or inverting the value
of a boolean.

+ Unary plus operator; indicates positive value


(numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean

Equality, Relational, and Conditional Operators

The Equality and Relational Operators

The equality and relational operators determine if one operator is greater than, less than,
equal to, or not equal to another operand. The majority of these operators will probably
look familiar to you as well.

== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to

Example :
class ComparisonDemo {

public static void main(String[] args) {


int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two
boolean expressions. These operators exhibit "short-circuiting" behavior, which means that
the second operand is evaluated only if needed.

&& Conditional-AND
|| Conditional-OR
class ConditionalDemo1 {

Example :

public static void main(String[] args)


{
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2))
System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) || (value2 == 1))
System.out.println("value1 is 1 OR value2 is 1");
}
}

Expressions

An expression is a construct made up of variables, operators, and method invocations,


which are constructed according to the syntax of the language, which evaluates to a single
value.

OR An expression is any valid combination of operators and operands.

 Given these initializations:

int a = 5, b = 2;

double c = 3.0;

 Use Chapter 3's operator precedence table to evaluate the following expressions:

(c + a / b) / 10 * 5

(0 % a) + c + (0 / a)

Statements

Statements are roughly equivalent to sentences in natural languages. A statement forms a


complete unit of execution. The following types of expressions can be made into a
statement by terminating the expression with a semicolon (;).

• Assignment expressions
• Any use of ++ or --
• Method invocations
• Object creation expressions

Such statements are called expression statements. Here are some examples of expression
statements.
aValue = 8933.234; // assignment statement
aValue++; // increment statement
System.out.println("Hello World!"); // method invocation
// statement
Bicycle myBike = new Bicycle(); // object creation
// statement

In addition to expression statements, there are two other kinds of statements: declaration
statements and control flow statements. A declaration statement declares a variable. You've
seen many examples of declaration statements already:

double aValue = 8933.234; // declaration statement

Finally, control flow statements regulate the order in which statements get executed. If, if –
else and switch statements.

Blocks

A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed. The following example, illustrates the use of
blocks:

class BlockDemo {
public static void main(String[] args) {
boolean condition = true;
if (condition)
{ // begin block 1
System.out.println("Condition is true.");
} // end block one
else
{ // begin block 2
System.out.println("Condition is false.");
} // end block 2
}
}

Control Flow Statements

The statements inside your source files are generally executed from top to bottom, in the
order that they appear. Control flow statements, however, break up the flow of execution
by employing decision making, looping, and branching, enabling your program to
conditionally execute particular blocks of code.

The if-then and if-then-else Statements

The if-then Statement


The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to TRue.
General syntax of if statement

If (condition)

Statement(s);

In addition, the opening and closing braces are optional, provided that the "then" clause
contains only one statement:

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the
code more brittle. If a second statement is later added to the "then" clause, a common
mistake would be forgetting to add the newly required braces. The compiler cannot catch
this sort of error; you'll just get the wrong results.

Example :

import java . io . * ;

public class ifstmnt

public static void main(String[] args)


{
int value1 = 1;
if(value1 > 0)
{ System.out.println("value1 is a positive number"); }
if(value1 < 0)
{ System.out.println("value1 is a Negative number"); }
if(value1 == 0)
{ System.out.println("value1 is equal to Zero"); }

}
}

import java . io . * ;

public class oddeven


{

public static void main(String[] args)


{
short no, res;
no = 67;
res = no % 2;
if( res == 0 )
{ System.out.print(“ 67 is an Even Number”);
if( res == 1 )
{ System.out.print(“ 67 is an ODD Number”);

}
}

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false. The execution is purely based on the condition i.e. if the condition is
true then the statements after if will be executed and else clause will be skipped out and if
the condition is false the statements after if will be skipped where as else block will be
executed.

General syntax of if-else

If (condition)

Statement(s);

else

Statement(s);

Example :

import java . io . * ;

public class ifstmnt

{
public static void main(String[] args)
{
int value1 = 1;

if(value1 > 0)
{ System.out.println("value1 is a positive number"); }
else
{ System.out.println("value1 is a Negative number"); }

if(value1 == 0)
{ System.out.println("value1 is equal to Zero"); }

}
}

import java . io . * ;

public class oddeven

public static void main(String[] args)


{
short no, res;
no = 67;
res = no % 2;
if( res == 0 )
{ System.out.print(“ 67 is an Even Number”);
else
{ System.out.print(“ 67 is an ODD Number”);

}
}

class IfElseDemo {
public static void main(String[] args) {

int testscore = 76;


char grade;

if (testscore >= 90) {


grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}

The output from the program is: Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in
the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied,
the appropriate statements are executed (grade = 'C';) and the remaining conditions are
not evaluated.

The switch Statement

Unlike if-then and if-then-else, the switch statement allows for any number of
possible execution paths. A switch works with the byte, short, char, and int primitive
data types. Switch is used for when ever you have multiple selections

General syntax of switch:

Switch(expression)

case 1: statement(s); break;

case 2: statement(s); break;

case n: statement(s); break;

default : statement(s);

Example :

class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
switch (month) {
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.println("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
default: System.out.println("Invalid month.");break;
}
}
}

In this case, "August" is printed to standard output.

The body of a switch statement is known as a switch block. Any statement immediately
contained by the switch block may be labeled with one or more case or default labels.
The switch statement evaluates its expression and executes the appropriate case.

Iteration statements or loops

A statement or group of statements executed repeatedly is called loop. Basically we have 3


types of loops

1. while loop
2. do while loop
3. for loop

The while and do-while Statements:

The while statement continually executes a block of statements while a particular


condition is TRue. Its syntax can be expressed as:

while (expression)
{
statement(s)
}

The while statement evaluates expression, which must return a boolean value. If the
expression evaluates to true, the while statement executes the statement(s) in the while
block. The while statement continues testing the expression and executing its block until
the expression evaluates to false. Using the while statement to print the values from 1
through 10 can be accomplished as in the following WhileDemo program:
Import java . io . * ;
{
class WhileDemo {
public static void main(String[] args)
{
int count = 1;
while (count < 11)
{
System.out.println("Count is: " + count);
count++;
}
}
}

You can implement an infinite loop using the while statement as follows:

while (true)
{
// your code goes here
}

The Java programming language also provides a do-while statement, which can be
expressed as follows:

do
{
statement(s)
}
while (expression);

The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once, as shown in the following DoWhileDemo program:

import java . io . * ;
{
class DoWhileDemo
{
public static void main(String[] args){
int count = 1;
do
{
System.out.println("Count is: " + count);
count++;
}
while (count <= 11);
}
}
The for Statement

The for statement provides a compact way to iterate over a range of values. Programmers
often refer to it as the "for loop" because of the way in which it repeatedly loops until a
particular condition is satisfied. The general form of the for statement can be expressed as
follows:

for (initialization; termination; increment)


{
statement(s)
}

When using this version of the for statement, keep in mind that:

• The initialization expression initializes the loop; it's executed once, as the loop
begins.
• When the termination expression evaluates to false, the loop terminates.
• The increment expression is invoked after each iteration through the loop; it is
perfectly acceptable for this expression to increment or decrement a value.

The following program, ForDemo, uses the general form of the for statement to print the
numbers 1 through 10 to standard output:

import java . io . * ;
{
class ForDemo
{
public static void main(String[] args){
for(int i=1; i<11; i++)
{
System.out.println("Count is: " + i);
}
}
}

Summary of Control Flow Statements

The if-then statement is the most basic of all the control flow statements. It tells your
program to execute a certain section of code only if a particular test evaluates to true.

The if-then-else statement provides a secondary path of execution when an "if" clause
evaluates to false.

Unlike if-then and if-then-else, the switch statement allows for any number of
possible execution paths.
The while and do-while statements continually execute a block of statements while a
particular condition is true.

The difference between do-while and while is that do-while evaluates its expression at
the bottom of the loop instead of the top. Therefore, the statements within the do block are
always executed at least once.

The for statement provides a compact way to iterate over a range of values. It has two
forms, one of which was designed for looping through collections and arrays.

Function / Method:

A function is infect a sub program that can acts on data and return a value. Each and every
java program must be having at least one function that is “main “. main is the entry point
of a java program operating system starts reading a program from main function.
Up until now, the term function has been used to describe a named subroutine. The term
that is more commonly used in Java is method, as in “a way to do something. It’s really
only a syntactic difference, now a days the term “method” is used rather than “function.”

General syntax of a function:

public static return_type Function_name( Parameter list)


e.g
public static void table( int a )

Calling Function:

A function can simply be called by its name and argument list


e.g. function_name(values to be passed if any);
import java.io.*;
public class methods
{
public static void main(String [] arg)
{

System.out.println(" HI THIS IS MY MAIN PROGRAM ");


mymethod();
System.out.println(" HI THIS IS MY MAIN PROGRAM ");
}

public static void mymethod()


{
System.out.println(" HI THIS IS MY METHOD ");
}
}
Output

C:\jdk1.3\bin>java methods
HI THIS IS MY MAIN PROGRAM
HI THIS IS MY METHOD
Passing values to a function:
HI THIS IS MY MAIN PROGRAM

We can simply pass a value from our main program or form one function to another
function this is call argument. General syntax of passing value form our main function to a
user defined function.

Function_name( value / variable );

e.g.

table ( 5 );
import java.io.*;
public class method
{
public static void main(String [] arg)
{
table(5);
} C:\jdk1.3\bin>javac
methods.java
public static void table(int a)
{ C:\jdk1.3\bin>java
for(int b=1; b<=10; b++) method
System.out.println(a+" * "+b+"
5 * 1 ==5" + a*b);
} 5 * 2 = 10
} 5 * 3 = 15
5 * 4 = 20
5 * 5 Output
= 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Returning values through a function:

A function can return any type of values to another function or a main function
General syntax of returning values.

Public static Return_type function_name (parameter list)


import java.io.*;
public class function
{
public static void main(String [] arg)
{
int a,b,c;
a=5;
b=6;
c=func(5,6);
System.out.print(c);
}

public static int func(int a,int b)


{
int c;
c=a+b;
return c;
}
}

Keyboard Input

The most common user interface devices are the CRT display for output and the keyboard
for input. Just as System.out was used to output data on the host system's CRT display,
System.in is used to receive input from the keyboard. To do this, however, the following
initialization is required:
BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));

This statement sets-up System.in as a buffered character input stream. 1 It's a bit messy, but
there are two important services provided. The InputStreamReader class converts raw bytes
arriving from the keyboard into characters. Second, and the BufferedReader class buffers
(temporary stores) the characters to provide efficient reading from the input stream.. The
statement declares and instantiates an object named stdin of the BufferedReader class. This
is analogous to earlier statements that declared and initialized variables. Now, however,
instead of a primitive data type, we have a class (BufferedReader) and instead of a variable,
we have an object (stdin). So an object is "kind of like" a variable, and a class is "kind of
like" a data type. Following the above statement, a line of text is read from the keyboard as
follows:
String line = stdin.readLine();
Think of stdin.readLine() as an expression, which it is. As an expression, it is evaluated and
it yields a value. This value is assigned to the variable line. More precisely, the readLine()
method is called on the stdin object — the keyboard. A string is returned and assigned to
the String variable line. The string contains the characters of a line of text entered on the
keyboard.
A line of input ends when the user presses the Enter key. The Enter key generates an end-
of-line code, but this is not included in the string returned by the readLine() method.
import java.io.*;
System.out.println(line);
public by
Through class input
above statement the input string is printed.
{
If we want thestatic
public user void
to enter a numberargs)
main(String[] on the keyboard,
throws then we must once again
IOException
{
confront(tackle, face) the problem of converting one type to another. For example, if the
user types 3, followed by 5, followed
BufferedReader stdin = by the Enter key, then the String variable line
new BufferedReader(new
contains the character '3' and the characterInputStreamReader(System.in));
'5', as opposed to the integer 35. So before the
value entered can be operated on as an integer,
System.out.print("Please enterthe string
your must");
name: be converting to an int.
String name = stdin.readLine();

System.out.println("Hello your name is….. " + name);

}
Converting String data to integer or double

The main() method is defined with the throws IOException clause. This is required because
certain types of errors, known as exceptions, are possible with keyboard input. A throws
clauseimport java.io.*;
informs the compiler that we are aware of the possibility of such errors and that we
will deal withclass
public theminput
in an appropriate manner.
{
public static void main(String[] args) throws IOException
Converting {
String to integer or float

Java treats each BufferedReader


and every thing as a string
stdin = thus normally for arithmetic operations you
need to convert new BufferedReader(new
that String InputStreamReader(System.in));
into integer or floating point double data types for this java
gives us the support of parseInt() a method
System.out.print("Please of the
enter yourInteger
name:wrapper
"); class to convert the
string to an int. String name
Similarly the =conversion
stdin.readLine();
of a String into floating point is very similar to
that for an int except the parseDouble() method
System.out.print("Please enter of the age:
your Double
"); wrapper class is applied to
convert the stringString s1 = stdin.readLine();
to a double.

System.out.print("Please enter your previous exam average: ");


String s2 = stdin.readLine();

int age = Integer.parseInt(s1); // string to int


double average = Double.parseDouble(s2); // string to double

System.out.println("Hello Mr " + name);


System.out.println("you are " + age + " years old");
System.out.println("Your previous exam average is " + average);
}
}
import java.io.*;

public class input1


{
public static void main(String[] args) throws IOException
{

BufferedReader stdin =
new BufferedReader(new InputStreamReader(System.in));

System.out.print("Please enter your name: ");


String name = stdin.readLine();

System.out.print("Please enter your age: ");


int age = Integer.parseInt(stdin.readLine());

System.out.print("Please enter your previous exam average: ");


double average = Double.parseDouble(stdin.readLine());

System.out.println("Hello Mr " + name);


System.out.println("you are " + age + " years old");
System.out.println("Your previous exam average is " + average);
}
}
MODULE NO 02:
Writing your first Object Oriented Program :

Writing a Java program requires five steps:


Step 1: Analyze
Understand the problem. What are you trying to accomplish?
Step 2: Design
Imagine the solution. What objects will you use? How will they interact?
Step 3: Write
Physically type the source code into an editor, and save the program as a
file on your disk.
Step 4: Compile
Compiling is the act of turning the text file with your source code in to the
byte codes that constitute a java program. Compiling is accomplished by
the java compiler.
Step 5: Test
Testing consists of running the program and making sure it behaves as
intended.

Object oriented programming:


Object oriented languages (referred to as OO or OOP for object oriented
programming) differ significantly from procedural languages. In OOP
programmers solve real world problems by creating objects that interact with
other objects similar to the way they would in the real world. Procedures
(often called methods or member functions in OOP programs) become part of
the object, and provide the object with capabilities. Data is also incorporated
into the object, providing the object with “state” thus a Button class might
have a Draw method, and state variables which determine the text of the
button and its location.
Object oriented programming OOP is one of the most dramatic innovations in
software development from the last decade. Object oriented programming
introduces many new ideas and different approaches to the programming that
were not supported by traditional approach. Following are the key pillars or
heart of object oriented programming
• Object
• Class
• Inheritance
• Polymorphism
• Data hiding
• Encapsulation

Objects:
An object is used to represent real world entities, such as person, place, thing,
concept etc. that has either physical or conceptual existence that we find in
normal day life. E.g. person, car, book, loan etc.
 Tangible Things as a car, printer, ...
 Roles as employee, boss, ...
 Incidents as flight, overflow, ...
 Interactions as contract, sale, ...
 Specifications as colour, shape, …
Every object has certain properties (or attributes or characteristics or features)
on the basis of which we can distinguish one object from another.
For example the person object has certain properties like name, age, date of
birth, gender etc. Also every object performs certain operations. For example
the person object can perform operations like move, listen, speak, sit etc.

Name
gender
speak
listen
n

age
Date of birth

Sit Move
The objects that are used in programming are also designed in the similar manner. They
have certain properties called data member and they perform various operations called
member functions

Data member Member Function


Name Speak
Age Listen
Date of birth Sit
gender Move
Object = Data + Methods
or to say the same differently:
An object has the responsibility to know and the responsibility to do
Object

Identi Beha
State
fier vior
State: - (Properties, attributes, characteristics of an object)
Behavior:- Any method / function or action which can be performed by an
object is called behavior.

State ( Color, Model, No of door etc)


Car
Behavior ( Push Break, Horn, Run, Change Gear )

Class:
Class is a user defined data structure which contains both the attributes and
behavior and unique name.
 Unique:- Every class must be have a unique name because OOPs
provides the concept of inheritance, so we can create more than one
classes with distinct name.
 Behavior: - Any method/ Function which performed some specific
action are known as behavior.
 State: - Attributes/ Characteristics of the class.
General Structure of a Class
Attribute Attribute
-1 -2

Function Function
-1 -2
Function
-3
Class

Header Files

Class className
{
Private :
Attribute1, 2, 3…..
Public:
member function1
member function2
…………………...
}
Public MainClass
{
Main Function
{
instantiation
}
}
Object Vs Classes:
 We can create many objects of a single class but inverse is not
allowed.
 Objects encapsulate the state and behavior of the class but inverse is
not possible.
 Once a class is defined, it will occupy some of the disc space. But
objects can be created and destroyed for many time.
 Object reserves memory space.

Class Example

The very first class “ first” program having one member function mymain the object
for the first class is created by the name of myobj.

class first
{
public void myfunc( )
{
System.out.println(“ hi this is my first class “) ;
}
}

public class mymain


{
public static void main ( String [ ] arg)
{
first myobj = new first ( );
myobj . myfunc ( ) ;
}
}
( A ) Example : using classes write a program to add 64 and 45.
( B ) Example : using classes write a program to add, subtract and
multiply 64 and 45

A class add B
{
class add private int a, b, c , d, e;
{ public void getdata( )
private int a, b, c; {
a = 64 ;
public void getdata( ) b = 45 ;
{ }
a = 64 ;
b = 45; public void sum ( )
} {
c = a+b;
public void showdata( ) System.out.println( “ 64 + 45 is “ + c);
{ }
c = a+b;
System.out.println( “ 64 + 45 is “ + c); public void sub ( )
} {
} d = a+b;
System.out.println( “ 64 - 45 is “ + d);
public class sum }
{
public static void main ( String [ ] arg) public void mul ( )
{ {
add myobject = new add ( ); e = a*b;
myobject . getdate ( 15 , 45 ) ; System.out.println( “ 64 * 45 is “ + e);
}
myobject . getdate ( ) ;
}
}
} public class sum
{
public static void main ( String [ ] arg)
{
add myobject = new add ( );
myobject . getdata ( ) ;
myobject . sum ( ) ;
myobject . sub ( ) ;
myobject . mul ( ) ;

}
}
Sending values from main class to a user defined Class
(Member Function)

class add class add


{ {
private int a, b, c; private int a, b, c , d, e;

public void getdata( int x , int y ) public void getdata( int i , int j)
{ {
a = x; a = i;
b = y; b = j;
} }

public void showdata( ) public void sum ( )


{ {
c = a+b; c = a+b;
System.out.println( “ 64 + 45 is “ + c); System.out.println( “ 64 + 45 is “ + c);
} }
}
public void sub ( )
public class sum {
{ d = a+b;
public static void main ( String [ ] arg) System.out.println( “ 64 - 45 is “ + d);
{ }
add myobject = new add ( );
myobject . getdate ( 8 , 4 ) ; public void mul ( )
{
myobject . getdate ( ) ; e = a+b;
System.out.println( “ 64 * 45 is “ + e);
} }
}
}

public class sum


{
public static void main ( String [ ] arg)
{
add myobject = new add ( );
myobject . getdata ( 16 , 8 ) ;
myobject . sum ( ) ;
myobject . sub ( ) ;
myobject . mul ( ) ;

}
}
Using classes write a program to send a number to a “ Table “class
and over there display the table of that number

import java . io . * ;

class Table
{
private int no , a;

public void getnumber( int x )


{
no = x;
}

public void showTable( )


{
for ( a = 1 ; a < = 10 ; a + + )
System.out.println( no + “ * “ + a + “ = “ + no * a);
}
}

public class zarbezubani


{
public static void main ( String [ ] arg)
{
Table myno = new Table ( );
myno . getnumber ( 8 ) ;
myno . showTable ( ) ;

}
}
Returning values for Sub class to main class

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


class add class add
{ {
private int c; private int plus , minus , zarab ;

public int myfunc( int x , int y ) public void sum ( int x , int y)
{ {
c = x+y; plus = x + y ;
return c ; return plus ;
} }

} public int sub ( int a , int b )


{
public class sum minus = a + b ;
{ return minus ;
public static void main ( String [ ] arg) }
{
int val; public int mul ( int a , int b )
add myobject = new add ( ); {
val = myobject . myfunc( 15 , 45 ) ; zarab = a * b ;
System . out . print ( val ) ; return zarab ;
}
}
} }

public class sum


{
public static void main ( String [ ] arg)
{
add myobject = new add ( );
int mysum, mysub , mymul ;
mysum = myobject . sum ( 15 , 23 ) ;
mysub = myobject . sub ( 100 , 50 ) ;
mymul = myobject . mul ( 4 , 3 ) ;

System . out . print (mysum);


System . out . print (mysub);
System . out . print (mymul);

}
}
Constructors :

Constructors are special methods that create an instance of your class . A


constructor is responsible for initializing your class with valid values.
Constructors always shares same name as the class itself e.g A constructor
for Test class will be named as Test().
A constructor like other methods may take parameters however constructors
are never marked with a return type, not even void. The java virtual machine
will call your constructor each time an object of your class is created
( instantiated ). i.e. constructors are called automatically when an object of
the class is instantiated.
So shortly
• Constructors are special methods like other member functions.
• Constructors are having same name as that of the class.
• Constructors can take any number of parameters but can not return a
value even void.
• Constructors are called automatically when an object is created.
• Constructors can be overloaded i.e. a single class may have more
then one constructors.

class test
{
public test ( )
{
//body of constructor ;
}

Public void myfunc( )


{
// body of member functions ;
}

Other member functions.


}
import java . io . * ; import java . io . * ;
class test class add
{ {
private int c; private int a , b , c ;

public test ( ) public add ( int x , int y)


{ {
System . out . print (“this is constructor); a = x ;
} b = y ;
}
}
public void sum ( )
public class constructors {
{ c= a+b;
public static void main ( String [ ] arg) System.out.print( a+“+”+b +”=”+c);
{ }

test myobject = new test ( ); }


val = myobject . myfunc( 15 , 45 ) ;
System . out . print ( val ) ; public class sum
{
} public static void main ( String [ ] arg)
} {
add myobject = new add ( 34 , 65 );

int mysum, mysub , sum ;

}
}
import java . io . * ;

class Table
{
private int no , a;

public Table( int x )


{
no = x;
}

public void showTable( )


{
for ( a = 1 ; a < = 10 ; a + + )
System.out.println( no + “ * “ + a + “ = “ + no * a);
}
}

public class zarbezubani


{
public static void main ( String [ ] arg)
{
Table myno = new Table ( 8 );
myno . showTable ( ) ;

}
}
POLYMORPHISM
POLYMORPHISM

Poly means “ MANY ” morph means “ FORMS ” polymorphism refers to the


same name taking many forms. Polymorphism means “having many forms”.
It allows different objects to respond the same message in different ways,
the response specific to the type of the object. Polymorphism means “many-
formed” the idea is that an object can take many forms.
One form of polymorphism is function polymorphism or method / function
overloading. The idea of method / function overloading is that a method can
have many forms i.e. we can create/declare more then one function with a
single name inside a single class. But both of the functions will be different
either with the number or type of parameters.
e.g.

class test
{
member variables ;

public void myfunc( )


{
//body of the functions ;
}

public void myfunc( int a , int b )


{
//body of the function ;
}

}
import java . io . * ; import java . io . * ;
class add class Table
{ {
private int a , b , c; private int a , no;

public void getdata( int x , int y ) public Table( int x )


{ {
a = x; no = x ;
b = y; }
}
public void ShowTable( )
public void sum( ) {
{ for ( a = 1 ; a < = 10 ; a + + )
c = a+b; System.out.println(no+“* “+a+“=”+no*a);
System.out.println(a+“+ “+b+“=”+c); }
}
public void ShowTable( int n )
public void sum( int i , int j ) {
{ for ( a = 1 ; a < = 10 ; a + + )
c = i+j; System.out.println(n+“* “+a+“=”+no*a);
System.out.println(i+“+ “+j+“=”+c); }
}
}
}
public class myTable
public class mysum {
{ public static void main ( String [ ] arg)
public static void main ( String [ ] arg) {
{
Table obj = new Table ( 8 );
add myobject = new add ( );
myobject.getdata( 5,7) ; obj . showTable( ) ;
myobject.sum() ;
myobject.sum ( 56 , 67 ) ; obj . showTable( 13 ) ;

} }
} }
INHERITANCE
Inheritance is one of the important pillars of object oriented
programming. Inheritance is the process of creating new classes from the
exiting class without modifying the existing one. Generally inheritance
means taking the behavior and characteristics of the original (bass class) in
an extended new class (derived class). Inheritance supports a number of
design goals in java i.e. inheritance enables us to reuse code that we know
works (code reuse). The process of inheritance is also known as ‘derivation’.
Simply inheritance is the method of creating new classes from existing/old
one. The new class is called derived class/ subclass/ child class or
descendent class and the exiting/old class is called base class/ super
class/ parent class or ancestor class.
The derived class can inherit some or all features (data and functions) of the
base class and can add its own features to extend the functionality of the
base class. But in this whole procedure the base class does not get
affected.

Feature-1 Super class or parent class or ancestor


Feature-2 class

Class-
B
Feature-1
Feature-2 Subclass or child class or descendent
Feature-3 class
Daily life Example (1/2)

• Here these three classes have certain data functions in common.


• The common data is - emp_id, ename and salary.
• The common functions are - get_data ( ) and put_data ( ).
• If we make these three classes as the way they are, then we will have
to write, debug and compile common data and functions again and again
and it will result in wastage of resources and time.
Daily life Example (2/2)

Now if we have to add any new feature, like address, that is common to all
three classes, which will be putted into employee class instead of adding
separately to worker, manager and clerk classes. Only distinct features are
required to be added separately to these classes.

INHERITANCE BASICS

To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how. Let’s begin with a short
example, the following program creates a super class A and a sub class
called B. Notice how the keyword extends is used to create a sub class of A
class A
{
int i , j ;

public void showij ( )


{

System . out . println ( “ i and j : “ + i + “ “ + j ) ;

class B extends A
{

int k ;

public void showk ( )


{

System . out . println ( “ k : “ + k ) ;

public void sum ( )


{

System.out .println( “ i + j + k : “ + (i+j+k) ) ;

public class inheritance


{
public static void main( String [] arg )
{
B obj = new B ( ) ;

obj . showij ( ) ;
obj . showk ( ) ;
obj . sum ( ) ;
}
}
import java.io.*;
class father
{
String name;
int age;

public void getdata(String nm , int ag )


{
name = nm;
age = ag;
}

public void fatherdata( )


{
System.out.println(" Fathers name is : " + name );
System.out.println(" Fathers age is : " + age );
}
}

class son extends father


{

public void sondata( )


{
System.out.println(" son's name is : " + name );
System.out.println(" Son's age is : " + age );
}
}

public class record


{
public static void main( String [] arg )
{

son obj = new son();

obj.getdata("Raheem",56);
obj.fatherdata( );

obj.getdata("Sultan",23);
obj.sondata( );

}
Super and this key words
The super key word is use for two specific purposes. The first calls the super
class constructor. The second is use to access a member of the super class
that has been hidden by a member of a sub class.
Using super to access super class member variables:-
Through super keyword inside into a sub class we can call super class
member variables e.g.
super . member_variable ;
Using super to call super class constructors:-
A sub class can call a constructor method defined by its superclass by use
of the following form of super.
super( parameter_list ) ;

This

some time a method will need to refer to the object that invoked it. To allow
this java defines this keyword. this can be used inside any method to refer to
the current object. That is “this” keyword is always a reference to the object
on which the method was invoked.
e.g. this. member_variable ;
import java.io.*;

class A
{
int i;
}

class B extends A
{
int i;

public B(int a, int b)


{
super.i=a;
this.i=b;
}

public void show()


{
System.out.println( " i in super class is " + super.i);
System.out.println( " i in subclass is " + this.i);
}

public class test1


{
public static void main(String [] arg)

{
B obj=new B(5,10);
obj.show();

}
}
import java.io.*;

class A
{
int i,j;

public A(int x, int y)


{
i=x;
j=y;
}
public void show()
{
System.out.println( i + " + " + j + " = " + (i+j) );
}

class B extends A
{

int k;

public B(int a, int b, int c)


{
super(a,b);
k=c;
}
public void show()
{
super.show();
System.out.println( i + " + " + j + " + " + k + " = " + (i+j+k) );
}

public class test2


{
public static void main(String [] arg)

{
B obj=new B(5,10,15);
obj.show();

}
}

You might also like