Sie sind auf Seite 1von 70

J2SE Core Java

PG-DESD Aug-2013

Session 2:
Learning Objectives
By the end of this session, you must be able to Explain basic programming constructs of Java Explain Classes and Objects in Java Use instance data and methods Use new operator to create instances Explain Constructors - Overloading

Explain Method overloading


Write programs on Parameter passing object as parameter

Java Programming - Basic Constructs

Identifiers:
Identifiers are the named words a programmer uses in a program An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) They cannot begin with a digit Java is case sensitive, therefore different identifiers Total and total are

Reserved Words
Often we use special identifiers called reserved words that already have a predefined meaning in the language A reserved word cannot be used in any other way default do double else extends false final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient true try var void volatile while

abstract boolean break byte byval case cast catch char class const continue

Variables
Programming languages uses variables to store data To allocate memory space for a variable JVM requires:

1) To specify the data type of the variable 2) To associate an identifier with the variable 3) Optionally, the variable may be assigned an initial value
All done as part of variable declaration.

Basic Variable Declaration


Syntax:

datatype identifier [=value];


Datatype must be
A simple data type User defined datatype (Class type)

Value is an optional initial value.

Basic Variable Declaration


We can declare several variables at the same time:

type identifier [=value][, identifier [=value] ]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x';

Constants
A constant is an identifier that is similar to a variable except that it holds one value for its entire existence The compiler will issue an error if you try to change a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;

Example:

Data Types - Primitive


Java defines eight simple (primitive) types: 1. byte 8-bit integer type 2. short 16-bit integer type
3.
4. 5. 6. 7. 8.

int 32-bit integer type long 64-bit integer type float 32-bit floating-point type double 64-bit floating-point type char symbols in a character set (16-bit Unicode) boolean logical values true and false

Introduction - Data Types

Data type Bytes Min Value byte short int long float double char boolean 1 2 4 8 4 8 2 -27 -215 -231 -263 0 -

Max Value 27 1 215 1 231 1 263 1 216 1 -

Literal Values 123 1234 12345, 086, 0x675 123456 1.0 123.86 a, \n true, false

General rule: Min value = 2(bits 1) Max value = 2(bits-1) 1 (where 1 byte = 8 bits)

10

Operators - Types

Types of operators

Assignment Operators Arithmetic Operators Unary Operators Equality Operators Relational Operators Conditional Operators instaceof Operator Bitwise Operators Shift Operators

11

Operators Assignment Operators/Arithmetic Operators

Assignment Operator

Operator
=

Description
Assignment

Example
int i = 10; int j = i;

Arithmetic Operators Operator + * Description Addition Subtraction Multiplication Example int i = 8 + 9; byte b = (byte) 5+4; int i = 9 4; int i = 8 * 6;

/
%

Division
Remainder

int i = 10 / 2;
int i = 10 % 3;
12

Operators Unary Operators/Equality Operators

Unary Operators Operator + Description Unary plus Example int i = +1;

++ -!

Unary minus
Increment Decrement Logical Not

int i = -1;
int j = i++; int j = i--; boolean j = !true;

Equality Operators Operator Description Example

== !=

Equality Non equality

If (i==1) If (i != 4)

13

Operators Relational Operators/Conditional Operators

Relational Operators Operator Description Example

>
< >= <=

Greater than
Less than Greater than or equal to Less than or equal to

if ( x > 4)
if ( x < 4) if ( x >= 4) if ( x <= 4)

Conditional Operators Operator && || Description Conditional and Conditional or Example If (a == 4 && b == 5) If (a == 4 || b == 5)

14

Operators instanceof Operator/Bitwise Operators/shift operators

instanceof Operator Operator Description Example

instanceof

Instance of

If (john instance of person)

Bitwise Operators Operator & | Description Bitwise and Bitwise or Example 001 & 111 = 1 001 | 110 = 111

^
~

Bitwise ex-or
Reverse

001 ^ 110 = 111


~0 = 1

Shift Operators
Operator >> Description Right shift Example 4 >> 1 = 0100 >> 1 = 0010 = 2

<<
>>>

Left Shift
Unsigned Right shift

4 << 1 = 0100 << 1 = 1000 = 8


4 >>> 1 =0100 >>> 1 =0010 = 2
15

class ArithmeticDemo { public static void main (String[] args){ // result is now 3 int result = 1 + 2; System.out.println(result); // result is now 2 result = result - 1; System.out.println(result);

Arithmetic Example

// result is now 4 result = result * 2; System.out.println(result);


// result is now 2 result = result / 2; System.out.println(result); // result is now 10 result = result + 8; // result is now 3 result = result % 7; System.out.println(result); } }

Logical Example

class BitDemo { public static void main(String[] args) { int bitmask = 0x000F; int val = 0x2222; System.out.println(val & bitmask); } }

Examples

class ConditionalDemo1 { 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"); } }

class ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); } }

Increment/ Decrement Example


class PrePostDemo { public static void main(String[] args){ int i = 3; i++; // prints 4 System.out.println(i); ++i; // prints 5 System.out.println(i); // prints 6 System.out.println(++i); // prints 6 System.out.println(i++); // prints 7 System.out.println(i); } }

Operator Precedence

Selection Statements
Java selection statements allow us to control the flow of programs execution based upon conditions known only during run-time. Java provides four selection statements:

1) 2) 3) 4)

if if-else if-else-if switch

Flow Control if-else if-else

Syntax

Example

if (<condition-1>) { // logic for true condition-1 goes here } else if (<condition-2>) { // logic for true condition-2 goes here } else { // if no condition is met, control comes here }

int a = 10; if (a < 10 ) { System.out.println(Less than 10); } else if (a > 10) { System.out.pritln(Greater than 10); } else { System.out.println(Equal to 10); } Result: Equal to 10s

22

Flow Control switch

switch
Example

Syntax

switch (<value>) { case <a>: // stmt-1 break; case <b>: //stmt-2 break; default:

//stmt-3

int a = 10; switch (a) { case 1: System.out.println(1); break; case 10: System.out.println(10); break; default: System.out.println(None); Result: 10
23

Selection Statements ifelse-if


class IfElseDemo { public static void main(String[] args) { int testScore=78; char grade; if(testScore>=90) grade='A'; else if (testScore>=70) grade='B'; else if(testScore>=50) grade='C'; else grade='D'; System.out.println("Grade="+grade); } }

Selection Statements switch


import java.io.*; class SwitchDemo { public static void main(String[] args) throws Exception { /*BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int color=Integer.parseInt(br.readLine());*/
int color=3; switch(color) { case 1: System.out.println("RED"); break; case 2: System.out.println("BLUE"); break; case 3: System.out.println("YELLOW");break; default: System.out.println(Invalid Color"); } }

class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31;break; case 4: case 6: case 9: case 11: numDays = 30; break case 2: if (year % 4 == 0) numDays = 29; else numDays = 28 break; default: System.out.println("Invalid month."); break; } System.out.println("N umber of Days =+ numDays); } }

Iteration Statements
Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true.

Java provides three iteration statements: 1) do - while 2) while 3) for

Flow Control do-while / while

do-while
Syntax Example

do { // stmt-1 } while (<condition>);

int i = 0; do { System.out.println(In do); i++; } while ( i < 10); Result: Prints In do 11 times

while
Syntax Example

while (<condition>) { //stmt }

int i = 0; while ( i < 10 ) { System.out.println(In while); i++; } Result: In while 10 times


28

Flow Control for loop

for
Syntax Example

for ( initialize; condition; expression) for (int i = 0; i < 10; i++) { { // stmt System.out.println(In for); } } Result: Prints In do 10 times

29

Iteration Statements - while


class WhileDemo { public static void main(String[] args) { int count=1; while(count<=5) { System.out.println("Count="+count); count++; } } }

Iteration Statements do while


class DoWhileDemo { public static void main(String[] args) { int count=1; do { System.out.println("Count="+count); count++; } while(count<=5); } }

Iteration Statements - for


class ForDemo1 { public static void main(String[] args) { for(int i=0;i<=10;i++) { System.out.println("Count="+i); } } }

For-each style
class ForDemo2 // for each style { public static void main(String[] args) { int arr[]={10,20,30,40,50}; for(int i: arr) { System.out.println("Count="+i); } } }

Jump Statements
Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break

2) continue 3) return
In addition, Java supports exception handling that can also alter the control flow of a program.

class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,2000, 8, 622, 127 }; int searchfor = 12; int i; boolean foundIt = false; for (i = 0; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + " not in the array"); } } }

class ContinueDemo { public static void main(String[] args) { String searchMe = "peter piper picked a " + "peck of pickled peppers"; int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { // interested only in p's if (searchMe.charAt(i) != 'p') continue; // process p's numPs++; } System.out.println("Found " + numPs + " p's in the string."); } }

Coding Guidelines

What is an Object?
Real world entities or things which have: 1) State

2) Behavior 3) Identity Example: your dog, your car etc.,


State name, color, breed of a dog Behavior sitting, barking, waging tail, running Indentity your dog A software object is a bundle of variables (state) and methods (operations).

What is a Class?
Class is basis for the Java language. Each concept we wish to describe in Java must be included in a class. Class is a group of set of values and set of operations A class is a template for objects A class is a blueprint / prototype that defines the variables and methods common to all objects of a certain kind. Example: your dog is a object of the class Dog. An object holds values for the variables defined in the class. A class defines a new data type, whose values are objects

An object is an instance of a class

The Class hierarchy


Classes are arranged in a hierarchy The root, or topmost, class is Object Every class but Object has at least one superclass

A class may have subclasses


Each class inherits all the fields and methods of its super classes

Class Definition
A class consists of : Name, Several variable declarations (instance variables) Several method declarations These are called members of the class A Class also consists constructors and blocks General form of a class: class classname { type instance-variable-1; type instance-variable-n; type method-name-1(parameter-list) { }

type method-name-2(parameter-list) { } type method-name-m(parameter-list) { } }

Declaring and creating objects


Declare a reference Example: Person p; String s;
Creating an instance/object Person p = new Person(); String s = new String (India); s The new keyword is used to allocate memory at run-time India

Example Program

Example Program: What happens in the memory

Example Program Anonymous object

Object Destruction
A program accumulates memory through its execution. Two mechanisms to free memory that is no longer needed by the program:

1) Manual in C/C++ 2) Automatic in Java


In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. Garbage collector is parts of the Java Run-Time Environment.

Constructor

A constructor used to initialize the state of an object. It is invoked at the time of object creation It constructs the values (data) for the object Features: 1) It is syntactically similar to a method 2) It has the same name as the name of its class 3) It is written without return type; The default return type is the class

When the class has no constructor, the default constructor automatically supplied the compiler.

Example: Constructor
class Box { double width; double height; double depth; Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } }

Default Constructor

Parameterized Constructor

Constructor Overloading

Constructor Copying values

Constructors vs. Methods

Method Overloading
A class with multiple methods by the same name but different parameters Implements polymorphism in java (static) Three ways: Number of arguments Types of arguments Order and Type of argument

Method Overloading

Method overloading is not possible by changing return types.

Is Overloading main() method possible ?

Overloading main() method


public class Simple /*Whenever your class is public and contains main() method, file name must be same as your class name.*/ { public static void main(String[] args) { System.out.println("Hello World!"); main(10); // main() call } public static void main(int a) // main() method overloading { System.out.println(a); } }

Method Overloading

Method Overloading

Parameter Passing
Only pass-by value or call by value is available in Java. There is no call by reference. Primitive data types and objects can be passed as values

Parameter Passing

Assignment Lab: Get yourself acquainted with java environment. Build a class Emp, which contains details about the Employee and compile and run its instances.
-Create instances ( minimum 3) - Constructors - Methods - Overloaded methods and constructors - Copy objects one to other

Assignments on CCR Assignment Reading:

Study the book Java Complete Reference

Next.
this facility static member, static method and static block JDK and its Usage Garbage Collection

Java Modifiers Modifier


public

Class

Class Variables

Methods

Method Variables

private
protected default final abstract strictfp

transient
synchronized native volatile static

63

Modifiers Class

public

Class can be accessed from any other class present in any package

default
Class can be accessed only from within the same package. Classes outside the package in which the class is defined cannot access this class

final

This class cannot be sub-classed, one cannot extend this class

abstract
Class cannot be instantiated, need to sub-classs/extend.

strictfp
Conforms that all methods in the class will conform to IEEE standard rules for floating points

64

Modifiers Class Attributes

public

Attribute can be accessed from any other class present in any package Attribute can be accessed from only within the class Attribute can be accessed from all classes in the same package and subclasses. Attribute can be accessed only from within the same package. This value of the attribute cannot be changed, can assign only 1 value The attribute value cannot be serialized Thread always reconciles its own copy of attribute with master. Only one value of the attribute per class

private
protected default final transient

volatile
static

65

Modifiers Methods

public

Method can be accessed from any other class present in any package

private

Method can be accessed from only within the class


Method can be accessed from all classes in the same package and sub-classes. Method can be accessed only from within the same package.

protected default final

The method cannot be overridden


Only provides the method declaration Method conforms to IEEE standard rules for floating points Only one thread can access the method at a time Method is implemented in platform dependent language Cannot access only static members.
66

abstract strictfp synchronized native static

Access Levels
Modifier
public protected

Class
Y Y

Package
Y Y

Subclass
Y Y

World
Y N

no modifier
private

Y
Y

Y
N

N
N

N
N

Assignment Lab: Get yourself acquainted with java environment. Build a class Emp, which contains details about the Employee and compile and run its instances.
-Create instances ( minimum 3) - Constructors - Methods - Overloaded methods and constructors - Copy objects one to other

Assignment Reading: Study the book Java FAQ Assignment Tutorial: Compare and contrast C++ and Java

Questions?

Thank You, Sreenivas Sadhu

Das könnte Ihnen auch gefallen