Você está na página 1de 37

Java Tutorial

JAVA BASICS
SESSION - I

Contents

JAVA Overview
OOPS Concepts in Java
Class Fundamentals
Classes
Principles of OOP
Simple Class and Method
Methods
Public/private
Using objects
Primitive Types and Variables
Initialisation
Declarations
Assignment

Basic Mathematical Operators


Statements & Blocks
Flow of Control
If The Conditional Statement
Relational Operators
If else
Nested if else
else if
The Switch Statement
The for loop
while loops
Continue
Constructors

December 16, 2015

Java Overview
Java is:
platform independent programming language
similar to C++ in syntax

Java has some interesting features:


automatic garbage collection,
simplifies pointers; no directly accessible pointer to memory,
multi-threading!

December 16, 2015

Java Prog

Java Prog

Java Prog

Java Prog

JVM(win)

JVM(Sol)

JVM(Lin)

JVM(XXX)

Windows

Solaris

Linux

XXX

Platform Dependent JVM and Platform Independent Program


December 16, 2015

How it works!
Java Compiler converts Java Source
code to intermediate instruction set
called byte code.

Create/Modify Source Code

Source Code

byte code is instruction set to a


virtual machines called JVM Java
Virtual Machine
JVM will convert byte instruction to
underlying machine instruction during
run time i.e. when program is running.
Thus byte code remains platform
independent and JVM is platform
specific.

Compile Source Code


i.e. javac Welcome.java
If compilation errors

Bytecode

Run Byteode
i.e. java Welcome

Result

If runtime errors or incorrect result

December 16, 2015

Object-Oriented Programming
Java supports OOD
Encapsulation
Polymorphism
Inheritance
Java programs contain nothing but definitions and instantiations of
classes
Everything is encapsulated in a class!

December 16, 2015

Principles of OOP
Encapsulation
Objects hide their
functions (methods)
and data (instance
variables)
Inheritance
Each subclass inherits
all variables of its
superclass
Polymorphism
Interface same despite
different data types

Superclass

car

manual

draw()

auto
matic

Subclasses

draw()

December 16, 2015

Classes
OOP - object oriented programming code built from objects are
called classes
Each class definition is coded in a separate .java file
Name of the object must match the class/object name

December 16, 2015

Simple Class and Method


A class typically has two parts data and action.
Data is represented by variables within the class.
Action represented by methods (functions in C).
Methods manipulate data.
Thus class typically encapsulates data and methods.

December 16, 2015

Using objects
Here, code in one class creates an instance of another class and does
something with it
Fruit plum=new Fruit();
int cals;
cals = plum.total_calories();

Dot operator allows you to access (public) data/methods inside Fruit


class

December 16, 2015

Methods
A method is a named sequence of code that can be invoked by other
Java code.
A method takes some parameters, performs some computations and
then optionally returns a value (or object).
Methods can be used as part of an expression statement.
public float convertCelsius(float tempC)
{
return( ((tempC * 9.0f) / 5.0f) + 32.0 );
}
December 16, 2015

Simple class
Class Fruit{
int grams;
int cals_per_gram;
int total_calories() {
return(grams*cals_per_gram);
}
}
December 16, 2015

Primitive Types and Variables


Boolean, char, byte, short, int, long, float, double etc.
These basic (or primitive) types are the only types that are not objects.
This means that you dont use the new operator to create a primitive
variable.
Declaring primitive variables:
float a;
int b, index = 2;
double c = 1.2;
boolean valueOk = false;
December 16, 2015

Initialisation
If no value is assigned prior to use, then the compiler will give an
error
Java sets primitive variables to zero or false in the case of a boolean
variable
All object references are initially set to null
An array of anything is an object
Set to null on declaration
Elements to zero false or null on creation

December 16, 2015

Declarations
int a = 1.2;

// compiler error

boolean b = 1;

// compiler error

double c = 5 / 4;

// no error!

float d = 5.8f;

// correct

double e = 5.0 / 4.0; // correct


1.2f is a float value accurate to 7 decimal places.
1.2 is a double value accurate to 15 decimal places.

December 16, 2015

Assignment
All Java assignments are right associative
int a = 1, b = 2, c = 5
a=b=c
System.out.print(a= + a + b= + b + c= + c)

What is the value of a, b & c


Done right to left: a = (b = c);

December 16, 2015

Basic Mathematical Operators


* / % + - are the mathematical operators
* / % have a higher precedence than + or double myVal = a + b % d c * d / b;
Is the same as:
double myVal = (a + (b % d)) ((c * d) / b);

December 16, 2015

Relational Operators
==

Equal (careful)

!=

Not equal

>=

Greater than or equal

<=

Less than or equal

>

Greater than

<

Less than

December 16, 2015

Statements & Blocks


A simple statement is a command terminated by a semi-colon:
name = Tina;
A block is a compound statement enclosed in curly brackets:
{
name1 = Tina; name2 = Mehta;
}
Blocks may contain other blocks

December 16, 2015

Flow of Control
Java executes one statement after the other in the order they are
written
Many Java statements are flow control statements:
Alternation:

if, if else, switch

Looping:

for, while, do while

Escapes:

break, continue, return

December 16, 2015

If The Conditional Statement


The if statement evaluates an expression and if that evaluation is true
then the specified action is taken
if ( x < 10 ) x = 10;
If the value of x is less than 10, make x equal to 10
It could have been written:
if ( x < 10 )
x = 10;
Or, alternatively:
if ( x < 10 ) { x = 10; }
December 16, 2015

If else
The if else statement evaluates an expression and performs one
action if that evaluation is true or a different action if it is false.
if (x != oldx) {
System.out.print(x was changed);
}
else {
System.out.print(x is unchanged);
}

December 16, 2015

Nested if else
if ( myVal > 100 ) {
if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(myVal is in range);
}
December 16, 2015

else if
Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute code block #3
}
December 16, 2015

The Switch Statement


switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
break;
}

//execute code block #4

December 16, 2015

The for loop


Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// i from 0 to n-1
}
Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200 times
}
}

December 16, 2015

while loop
int response=10;

while (response < 1) {


System.out.println(response);
response++;
}

December 16, 2015

do { } while loops
int response=10;
do {
System.out.println(response);
response++;
}while (response < 1);

December 16, 2015

Break
A break statement causes an exit from the innermost containing
while, do, for or switch statement.
for ( int i = 0; i < maxID, i++ ) {
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break

December 16, 2015

Continue
Can only be used with while, do or for.
The continue statement causes the innermost loop to start the next
iteration immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( UserID + i + : + userID);
}

December 16, 2015

Constructors

A special method that is invoked while object is being created.


It MUST have same name as class name and does not have return type
It can be parameterized
When no constructor is defined java compiler provides a default
constructor

invokes a constructor method with which you can set the initial data
of an object
You may choose several different type of constructor with different
argument lists

December 16, 2015

public class book1


{
String title;
String author;
double price ;
int percentDiscount;
public book1(String tit, String auth,double prc,int perDisc)
{
title = tit;
author = auth;
price = prc;
percentDiscount = perDisc;
}
double getDiscountedPrice()
{
return price - (price*percentDiscount/100);
}
public static void main(String args[])
{
book1 b1 = new book1("Java 2","Herbert",435,14);
book1 b2 = new book1("Ajax Project in Java Technology",
"Smith",300,30);
System.out.println(b1.getDiscountedPrice());
System.out.println(b2.getDiscountedPrice());
}

December 16, 2015

Packages
In java application there can not be two classes with same
name.
When application involves 100s of classes and 10s of third
party library being used, it is very difficult to come out with
unique meaningful name
This can be achieved in java using packages.
A package is name space within which each class has
unique name
A package can also be used as access control it is possible
to define a class or member of a class which is visible only
within a specified package.

December 16, 2015

Packages Syntax
package x
public class a
{
}
package x.y
public class a
{
}

Class a belongs to package x

Class a belongs to package x.y. This


is fine as both class belong to
different package

package com.bredge.sample
public class b
{
}

Class b belongs to package


com.bredge.sample

December 16, 2015

Access Specifiers
There are three access Specifiers namely public, private and
protected and four access levels(including default).
Members of a class can be public, private or protected.
That basically means member variables and methods can either be
public, private or protected.
Public members are accessible within and outside class.
Private members are accessible only within class.
The protected modifier specifies that the member can only be
accessed within its own package (as with package-private) and, in
addition, by a subclass of its class in another package.
When neither public nor private or protected mentioned, default
access will be considered.
Class can be public or default only.
December 16, 2015

Access Specifiers
Default access specifier, i.e. when there is no public, private
or protected is mentioned, has package level visibility.
Default class members are visible to all other classes which
belong to same package

private protected public default


Same class
Y
Y
Y Y
Same package sub-class
N
Y
Y Y
Same package non-subclass
N
Y
Y Y
Dif erent Package subclass
N
Y
Y N
Dif erent Package non-subclass N
N
Y N
December 16, 2015

Thank You

Você também pode gostar