You are on page 1of 52

JAVA Basics

Course Objectives
On completion of this course we will be able to:

1.Identify the importance of Java .


2.Identify the additional features of Java compared to C++ .
3.Identify the difference between Compiler and Interpreter .
4.Identify the difference between applet and application .
5.Apply Object Oriented Principles of Encapsulations, Data
abstraction, Inheritance, Polymorphism.
6.Program using java API (Application Programming Interface).
7.Program using Exception Handling, Files and Threads .
8.Program Using applets and swings .

9/6/17 Object Oriented Programming using JAVA 2


Why Java is Important
Two reasons :
Trouble with C/C++ language is that they are not
portable and are not platform independent
languages.
Emergence of World Wide Web, which demanded
portable programs
Portability and security necessitated the
invention of Java
Cont..
Java Editions.
J2SE(Java 2 Standard Edition) - to develop
client-side standalone applications or applets.
J2ME(Java 2 Micro Edition ) - to develop
applications for mobile devices such as cell
phones.
J2EE(Java 2 Enterprise Edition ) - to develop
server-side applications such as Java servlets
and Java ServerPages.
What is java?
A general-purpose object-oriented language.

Write Once Run Anywhere (WORA).

Designed for easy Web/Internet applications.

Widespread acceptance.
How is Java different from C
C Language:
Major difference is that C is a structure oriented language and
Java is an object oriented language and has mechanism to
define classes and objects.
Java does not support an explicit pointer type
Java does not have preprocessor, so we cant use #define,
#include and #ifdef statements.
Java does not include structures, unions and enum data types.
Java does not include keywords like goto, sizeof and typedef.
Java adds labeled break and continue statements.
Java adds many features required for object oriented
programming.
How is Java different from C++
C++ language
Features removed in java:
Java doesnt support pointers to avoid unauthorized access of
memory locations.
Java does not include structures, unions and enum data
types.
Java does not support operator over loading.
Preprocessor plays less important role in C++ and so
eliminated entirely in java.
Java does not perform automatic type conversions that result
in loss of precision.
Cont
Java does not support global variables. Every method and
variable is declared within a class and forms part of that
class.
Java does not allow default arguments.
Java does not support inheritance of multiple super classes
by a sub class (i.e., multiple inheritance). This is
accomplished by using interface concept.
It is not possible to declare unsigned integers in java.
In java objects are passed by reference only. In C++ objects
may be passed by value or reference.
Cont
New features added in Java:

Multithreading, that allows two or more pieces of the same


program to execute concurrently.
C++ has a set of library functions that use a common header
file. But java replaces it with its own set of API classes.
It adds packages and interfaces.
Java supports automatic garbage collection.
break and continue statements have been enhanced in java to
accept labels as targets.
The use of unicode characters ensures portability.
Cont
Features that differ:

Though C++ and java supports Boolean data type, C++ takes
any nonzero value as true and zero as false. True and false in
java are predefined literals that are values for a boolean
expression.
Java has replaced the destructor function with a finalize()
function.
C++ supports exception handling that is similar to java's.
However, in C++ there is no requirement that a thrown
exception be caught.
Characteristics of Java
Java is simple Java is architecture-neutral
Java is object-oriented Java is portable
Java is distributed Javas performance
Java is interpreted Java is multithreaded
Java is robust Java is dynamic
Java is secure
Java is architecture-neutral

JAVA Program Execution

9/6/17 Object Oriented Programming using JAVA 12


WORA(Write Once Run Anywhere)

9/6/17 Object Oriented Programming using JAVA 13


Java Program Java Compiler Virtual Machine

Source Code Bytecode

Process of Compilation

Java Interpreter Machine Code

Virtual Machine Real Machine

Process of Converting bytecode into machine code


9/6/17 Object Oriented Programming using JAVA 15
9/6/17 Object Oriented Programming using JAVA 16
9/6/17 Object Oriented Programming using JAVA 17
9/6/17 Object Oriented Programming using JAVA 18
First Application
/**
*Hello World, first application, only output.
*/
import java.io.*;

public class hello{


public static void main (String [] args) {
System.out.println(Hello World\n);
} //end main
}//end class

Shlomo Hershkop 19
How to get it running
Text in hello.java file
Why?
To compile:
javac hello.java
To run:
java hello

Shlomo Hershkop 20
Variables
Variables:
Name
Type
Value
Naming:
May contain numbers,underscore,dollar sign, or letters
Can not start with number
Can be any length
Reserved keywords
Case sensitive

Shlomo Hershkop 21
Primitive data types
Byte 8 -27 27-1
Short 16 -215 215-1
Int 32 -231 231-1
Long 64
Float 32
Double 64
Boolean 1 0 1
Char 16

Shlomo Hershkop 22
Assignment
=
Example:
int n;
n = 10;
or
int n = 10; //same

Shlomo Hershkop 23
Strings
Not a primitive class, its actually something called a wrapper
class
To find a built in classs method use API documentation.
String is a group of chars
A character has single quotes
char c = h;
A String has double quotes
String s = Hello World;
Method length
int n = s.length;

Shlomo Hershkop 24
Math
Unary
int x = -9;
Regular math (+,-,*,/)
int y = 3+x;

% modulo operator

Shlomo Hershkop 25
Incrementing
Increment and Decrement
i++ equivalent to i = i + 1;
Can also do ++i, which uses i before
incrementing it.
Decrementing: i--;

Shlomo Hershkop 26
Casting
int n = 40;
Wrong : byte b = n;
why??
Right: byte b = (byte) n;

Type casting converts to target type

Shlomo Hershkop 27
Casting II
Type char is stored as a number. The ASCII
value of the character.
A declaration of :
char c = B;
stores the value 66 in location c
can use its value by casting to int
how??

Shlomo Hershkop 28
Conversions and the Cast Operator :
Normally with implicit conversion, the conversion is so natural that you don't even
notice. Sometimes though it is important to make sure a conversion occurs between two
types. Doing this type of conversion requires an explicit cast, by using the cast operator.
The cast operator consists of a type name within round brackets. It is a unary operator
with high precedence and comes before its operand, the result of which is a variable of
the type specified by the cast, but which has the value of the original object. The
following example shows an example of an explicit cast:
float x = 2.0;
float y = 1.7;
x - ( (int)(x/y) * y)
When x is divided by y in this example, the type of the result is a floating-point number.
However, value of x/y is explicitly converted to type int by the cast operator, resulting in
a 1, not 1.2. So the end result of this equation is that x equals 1.7.
Not all conversions are legal. For instance, boolean values cannot be cast to any other
type, and objects can only be converted to a parent class.
Casting and Converting Integers
The four integer types can be cast to any other type except boolean. However, casting
into a smaller type can result in a loss of data, and a cast to a floating-point number
(float or double) will probably result in the loss of some precision, unless the integer is a
whole power of two (for example, 1, 2, 4, 8...).
Assignment
+=
-=
*=
/=
%=

Shlomo Hershkop 30
Boolean Expressions
boolean b
b will be either true (1) or false (0)
Logical operations: !(not), && (and) || (or)
boolean a,b;
a = true;
b = false;
System.out.println (a && b is + (a && b));

Shlomo Hershkop 31
Relational Operators
== equality
!= inequality
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Shlomo Hershkop 32
The Conditional Operator
The conditional operator is the one ternary or triadic operator in Java, and operates as
it does in C and C++. It takes the following form:
expression1 ? expression2 : expression3
In this syntax, expression1 must produce a Boolean value. If this value is true, then
expression2 is evaluated, and its result is the value of the conditional. If expression1 is
false, then expression3 is evaluated, and its result is the value of the conditional.
Consider the following examples. The first is using the conditional operator to
determine the maximum of two values; the second is determining the minimum of two
values; the third is determining the absolute value of a quantity:
BestReturn = Stocks > Bonds ? Stocks : Bonds ;
LowSales = JuneSales < JulySales ? JuneSales : JulySales ;
Distance = Site1-Site2 > 0 ? Site1-Site2 : Site2 - Site1 ;
In reviewing these examples, think about the precedence rules, and convince yourself
that none of the three examples requires any brackets in order to be evaluated
correctly.
Comments in Java
Java supports three types of comment delimiters-the traditional /*
and */ of C, the // of C++, and a new variant that starts with /** and
ends with */.
The /* and */ delimiters are used to enclose text that is to be treated as a
comment by the compiler. These delimiters are useful when you want to
designate a lengthy piece of code as a comment, as shown in the
following:
/* This is a comment that will span multiple source code lines. */
The // comment delimiter is borrowed from C++ and is used to indicate that
the rest of the line is to be treated as a comment by the Java compiler.
This type of comment delimiter is particularly useful for adding comments
adjacent to lines of code, as shown in the following:
Date today = new Date(); // create an object with today's date
System.out.println(today); // display the date

Finally, the /** and */ delimiters are new to Java and are used to indicate that the enclosed text
is to be treated as a comment by the compiler, but that the text is also part of the automatic
class documentation that can be generated using JavaDoc
The Java comment delimiters are summarized in Table 3.1.
Table 3.1. Java comment delimiters.

Start End Purpose

/* */ The enclosed text is treated as a comment.


// (none The rest of the line is treated as a comment.
)
/** */ The enclosed text is treated as a comment by the compiler but is
used by JavaDoc to automatically generate documentation.
Java Control Statements
Control
Statement

Selection Statement Iteration Statement Jump Statement

conti return
if If-else switch break
nue

while do for
Selection Statement : These select one of several control flows. There are three types
of selection statement in Java : if,if-else, and switch.
If statement :
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements. It is a two-way decision statement and is used in
conjunction with an expression. The general form is :
If(test expression)
{
Statement-block;
}
Statement-x;
It allows the computer to evaluate the expression first and then, depending on
whether the value of the expression (relation or condition) is true or false. It
transfers the control to a particular statement.
If the statement is true then the Statement block will be executed;otherwise the
statement-block will be skipped and the execution will jump to the statement-x. It
should be remember that when the condition is true both the statement-block and
statement-x are executed in sequence.
Example :
Class Demo {
public static void main(String args[]) {
If(args.length==0)
System.out.println(You must have command line arguments); }}
If-else statement
if(test expression)
{
True-Block Statement(s);
}
Else
{
False-Block statement(s);
}
Statement-x;
If the test expression is true, then the true-block statement(s) executed immediately
following to the if statement, are executed; otherwise the false statement(s) will be
executed, not both.In both the cases, the control is transferred subsequently to the
statement-x.
Nesting of Ifelse Statement
If(test condition1)
{ if(test condition2) {
Statement-1; }
else {
Statement-2; }
}
else {
Statement-3; }
Statement-x;
If the condition-1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test. If the condition-2 is true, the statement-1 will be
evaluated;otherwise statement-2 will be evaluated and then control is transferred to
the statement-x.
Switch Statement: The Java switch statement is ideal for testing a single expression
against a series of possible values and executing the code associated with the
matching case statement.
Switch(expression) {
Case value-1:
block-1;
break;
Case value-2:
block-2;
break;

default:
default-block;
break; }
Statement-x;
Iteration Statement : These specify how and when looping will take place. There are
three types of Iteration statements: while, do and for
The for Statement
The first line of a for loop enables you to specify a starting value for a loop counter,
specify the test condition that will exit the loop, and indicate how the loop counter
should be incremented after each pass through the loop. This is definitely a statement
that offers a lot of bang for the buck. The syntax of a Java for statement is as follows:
for (initialization; testExpression; incremement)
statement
For example, a sample for loop may appear as follows:
int count;
for (count=0; count<100; count++)
System.out.println("Count = " + count);
In this example, the initialization statement of the for loop sets count to 0. The test
expression, count < 100, indicates that the loop should continue as long as count is less
than 100. Finally, the increment statement increments the value of count by one. As long
as the test expression is true, the statement following the for loop setup will be
executed, as follows:
System.out.println("Count = " + count);
Of course, you probably need to do more than one thing inside the loop. This is as easy
to do as using curly braces to indicate the scope of the for loop.
The while Statement
Related to the for loop is the while loop. The syntax for a while loop is as follows:
while (booleanExpression)
statement
As you can tell from the simplicity of this, the Java while loop does not have the built-
in support for initializing and incrementing variables that its for loop does. Because
of this, you need to be careful to initialize loop counters prior to the loop and
increment them within the body of the while loop. For example, the following code
fragment will display a message five times:
int count = 0;
while (count < 5) {
System.out.println("Count = " + count);
count++;
}
The dowhile Statement
The final looping construct in Java is the dowhile loop. The syntax for a dowhile
loop is as follows:
do {
statement
} while (booleanExpression);
This is similar to a while loop except that a dowhile loop is guaranteed to execute at least
once. It is possible that a while loop may not execute at all depending on the test
expression used in the loop. For example, consider the following method:
public void ShowYears(int year) {
while (year < 2000) {
System.out.println("Year is " + year);
year++;
}
}
This method is passed a year value, then loops over the year displaying a message as long
as the year is less than 2000. If year starts at 1996, then messages will be displayed for the
years 1996, 1997, 1998, and 1999. However, what happens if year starts at 2010? Because
the initial test, year < 2000, will be false, the while loop will never be entered. Fortunately,
a dowhile loop can solve this problem. Because a dowhile loop performs its expression
testing after the body of the loop has executed for each pass, it will always be executed at
least once. This is a very valid distinction between the two types of loop, but it can also be
a source of potential errors. Whenever you use a dowhile loop, you should be careful to
consider the first pass through the body of the loop.
Jumping
Of course, it is not always easy to write all of your for, while and dowhile loops so that
they are easy to read and yet the loops terminate on exactly the right pass through the
loop. Java makes it easier to jump out of loops and to control other areas of program flow
with its break and continue statements.
The break Statement
Earlier in this chapter, you saw how the break statement is used to exit a switch statement.
In a similar manner, break can be used to exit a loop
As an example of this, consider the following code:
int year = 1909;
while (DidCubsWinTheWorldSeries(year) == false) {
System.out.println("Didn't win in " + year);
if (year >= 3000) {
System.out.println("Time to give up. Go White Sox!");
break;
}
}
System.out.println("Loop exited on year " + year);
This example shows a while loop that will continue to execute until it finds a year that
the Chicago Cubs won the World Series. Because they haven't won since 1908 and the
loop counter year starts with 1909, it has a lot of looping to do. For each year they
didn't win, a message is displayed. However, even die-hard Cubs fans will eventually
give up and change allegiances to the Chicago White Sox. In this example, if the year is
3000 or later, a message is displayed and then a break is encountered. The break
statement will cause program control to move to the first statement after the end of
the while loop. In this case, that will be the following line:
System.out.println("Loop exited on year " + year);
The continue Statement
Just as a break statement can be used to move program control to immediately after
the end of a loop, the continue statement can be used to force program control back to
the top of a loop
ARRAYS
One Dimensional Array : is a list of variables of the same type that are accessed
through a common name. An Individual variable in the array is called an array
element. Arrays from a convenient way to handle groups of related data.
To create an array, you need to perform two steps :
1. Declare Array
2. Allocate space for its elements.
General Form for declaring one dimensional array given below :
type varName[];
Here, type is a valid Java data type and varName is the name of the array. Like int a[];
This creates a variable named a that refers to an integer array. But it does not actually
create storage for the array.
Second approach to allocate space for One Dimensional Array is
varName=new type[size];
Here varName is name of the array, type is a valid Java type, and size specifies the
number of elements in the array. You can see that the new operator is used to
allocate memory for the array.
These two steps combines like
type varName=new type[size];
For example consider this declaration and allocation :
Int ia=new int[10];
Represents the structure of a one-dimensional array,here ia is array variable name
that can hold 10 integer values.
Multidimensional Array :
In addition to one dimensional we can create arrays of two or more dimensions. In
Java, Multidimensional array are implemented as arrays of arrays. You need to
perform two steps to work with multidimensional arrays : 1. Declare the array and 2.
allocate space for its elements.
The General form is given below :
Type varname = new type[size1][size2];
float a[][]=new float[2][2];
Here a is two dimensional array having 2 rows and 2 columns. i.e. size is 4, we can
store 4 elements in that array.
classFactorialExample{
publicstaticvoidmain(Stringargs[]){
inti,fact=1;
intnumber=5;//Itisthenumbertocalculatefactorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorialof"+number+"is:"+fact);
}
}

9/6/17 Object Oriented Programming using JAVA 49


publicclassReverseNumber{

publicstaticvoidmain(String[]args){

//originalnumber
intnumber=1234;
intreversedNumber=0;
inttemp=0;

while(number>0){

//usemodulusoperatortostripoffthelastdigit
temp=number%10;

//createthereversednumber
reversedNumber=reversedNumber*10+temp;
number=number/10;

//outputthereversednumber
System.out.println("ReversedNumberis:"+reversedNumber);
}
} 9/6/17 Object Oriented Programming using JAVA 50
public class FindEvenOrOddNumber {

public static void main(String[] args) {

//create an array of 10 numbers


int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};

for(int i=0; i < numbers.length; i++){

/*
* use modulus operator to check if the number is even or odd.
* If we divide any number by 2 and reminder is 0 then the number is
* even, otherwise it is odd.
*/

if(numbers[i]%2 == 0)
System.out.println(numbers[i] + " is even number.");
else
System.out.println(numbers[i] + " is odd number.");

}
}

9/6/17 Object Oriented Programming using JAVA 51


Thank you

9/6/17 Object Oriented Programming using JAVA 52

You might also like