Sie sind auf Seite 1von 55

Core Java

Core Java 55 Pages

Contents
Language Fundamentals Modifiers Flow Control and Exceptions Objects and Classes Converting and Casting Threads The java.lang and java.util Packages
Core Java 55 Pages 2

Language Fundamentals
Source Files
Java source files must end with .java extension Should generally contain at most one toplevel public class definition If a public class is present, the class name should match the un-extended filename Can consists of an unlimited number of nonpublic class definitions
Core Java 55 Pages 3

The source file may consists of


package declaration (Optional) import statements (Optional) class / interface definitions (Required)

Ex:
package A.B.C; import java.awt.Button; import java.util.*; public class Test{ ......} Java 55 Pages Core
4

Keywords & Identifiers

abstract false int throws double short volatile

const final protected case goto static

implements instanceof throw do native void

import private byte for transient class

package this default long try extends

synchronized break float return char new

while continue interface true else null

boolean finally public catch if super

Core Java 55 Pages

Primitive Data Types


boolean char byte short int long float double
Core Java 55 Pages 6

Primitive Data types and Their Sizes


Type
boolean char int float

Size (bits)
8 8 32 32

Type
char char long double

Size (bits)
16 16 64 64

Core Java 55 Pages

Integral Primitive Types


Type
byte

Size
8 bites

Minimum
-27

Maximum
27-1

short

16 bits

-215

215-1

int

32 bits

-231

231-1

long

64 bits

-263

263-1

Core Java 55 Pages

The char type is integral but unsigned Range for char is 0 through 216-1 Java characters are in Unicode, which is a 16-bit encoding

Core Java 55 Pages

The floating-point types are


float double

The range is
Float.MIN_VALUE & Float.MAX_VALUE Double.MIN_VALUE & Double.MAX_VALUE

Follows IEEE 754 specification


Core Java 55 Pages 10

Literals
boolean Literals
true & false

char Literals
c => Refers to c \n => New Line \r => Return \t => Tab \b => Backspace \f => Form Feed \ => Single Quote \ => Double Quote \? => Question Mark

Core Java 55 Pages

11

Integral Literals
28 (Decimal) 034 (Octal) 0x1c (Hexa) 0x1C 0X1C 0X1c

Floating-Point Literals
1.414 4.23E+1 1.929f 1234d

String Literals
Characters in strings are 16-bit Unicode

Core Java 55 Pages

12

Arrays
Declaration
DataType Name[]{[]}; int ints[]; float f[][]

Construction
Name = new DataType[SIZE]{[SIZE]} ints = new int[25]; f = new float[3][5];

Initialization
DataType Name[] = {value1, value2, value3, .... valueN}; int ints[] = {10, 20, 30, 40}; int i[][] = { {1,2,3}, {4,5,6}};
Core Java 55 Pages 13

Array Element Initialization Values

Element Type
byte int float char object reference

Initial Value
0 0 0.0f \u0000 null

Element Type
short long double boolean

Initial Value
0 0L 0.0d false

Core Java 55 Pages

14

Class Fundamentals
The main() method
Normal entry point for Java Applications public static void main(String [] args)

Variables and Initialization


A member variable of a class is created when the instance is created, and is accessible from any method in the class An automatic variable of a method is created on entry to the method, exists only during execution of the method, and is only accessible within the method

Core Java 55 Pages

15

Initialization Values for Member Variables

Element Type
byte int float char object reference

Initial Value
0 0 0.0f \u0000 null

Element Type
short long double boolean

Initial Value
0 0L 0.0d false

Core Java 55 Pages

16

Argument Passing
Primitive values are passed by value public void bumper(int bumpMe){ bumpMe += 25; } itn xx = 12345; bumpMe(xx); System.out.println( Now xx is + xx); Object values are passed by reference TextField tf = new TextField( Yin ); changer(tf); System.out.println(tf.getLabel()); public void changer(TextField changeMe){ changeMe.setText( Yang ); } Core Java 55 Pages

17

Modifiers
The Access Modifiers final abstract static native transient synchronized volatile
Core Java 55 Pages 18

The Access Modifiers


Can be applied to class , class variables , methods and constructor

Modifier
public private protected Friendly *

Class
Yes No No Yes

Variable
Yes Yes Yes Yes

Method/ Constructor
Yes Yes Yes Yes

Core Java 55 Pages

19

Subclasses and Method Privacy

private

Friendly

protected

public

A private method may be overridden by a private, friendly, protected, or public method A friendly method may be overridden by a friendly, protected, or public method A protected method may be overridden by a protected or public method A public method may only be overridden by a public method

Core Java 55 Pages

20

Summary of Access Modes


public: A public feature may be accessed by any class at all protected A protected feature may only be accessed by a subclass of the class that owns the feature or by a member of the same package as the class that owns the feature friendly (*): A friendly feature may only be accessed by a class from the same package as the class that owns the feature private : A private feature may only be accessed by the class that owns the feature

Core Java 55 Pages

21

Other Modifiers final


Can be applied to class, variable, method / variable

final Class may not be sub-classed final variable may not be modified once assigned final methods may not be overridden

Core Java 55 Pages

22

abstract
Can be applied to class, methods

A class that is abstract, may not be initialized An abstract method must be overridden by it s subclasses
Provided the subclasses aren t abstract

Core Java 55 Pages

23

static
Can be applied to variables, methods or free floating point blocks

static variables and methods becomes class variables and methods Can be accessible without the object reference We can have free-floating blocks also,
public CA{ public static int i; static { i = 10;} public static void main(String[]arg){ System.out.println(i); } Core Java 55 Pages }

24

native
Can be applied for methods

Indicates that the body of the method is found outside the Java Virtual Machine, may be in a library class CA{ native void doFun(int i); static{ System.loadLibrary( mylibrary );} public static void main(String[]arg){ CA obj = new CA(); obj.fun(10); } }

Core Java 55 Pages

25

transient
Can be applied for variables Transient variables are not stored as part of it s object s persistent state

synchronized
Can be applied for methods Used for object locking under multi-threaded environment

Core Java 55 Pages

26

Flow Control
Sequence constructs Selection constructs
if, else, else if, switch

Iteration constructs
while, do-while, for

Core Java 55 Pages

27

if (expr) { Statement (s) }[ else { } ] if (expr) { Block 1 } else if (expr) { Block 2 } [ else { }]

Core Java 55 Pages

28

switch (Expr){ case value1: ..... break; case value2: ..... break; case value3: ..... break; case value4: ..... break; ... default: ..... }

Core Java 55 Pages

29

while(Expr){ Statement (s) } do{ Statement(s) }while(Expr); for(;;){ } We can use break to break the loop and continue to continue the loop, advances to the next step

Core Java 55 Pages

30

Exception Handling
Exceptions are abnormal conditions while executing a program If no steps are taken, it abandon's current method execution and jumps to the caller method It continues until execution reaches the top of the affected Thread All exceptions are subclasses of java.lang.Throwable class

Core Java 55 Pages

31

try{ // Block of statements, which may throw some exception }catch(SpecificException se){ // Handles the SpecificException } catch(OtherException oe){ // Handles the OtherException } catch(GenericException ge){ // Handles the GenericExceptoin }[ finally { //This block will be executed at any cost, irrespective of exception handled / not } ]

Core Java 55 Pages

32

Throwing Exceptions
Allows you to create an instance of exception object and throws the exception We can use throw statement to throw the exception objects throw new IOException( Sorry!!! No Such File );

If any method throws an exception, it must be


public void doFun() throws IOException {
throw new IOException( Sorry!!! No Such File );

Core Java 55 Pages

33

Exception Hierarchy
java.lang.Throwable

java.lang.Exception
Checked Exceptions

java.lang.Error

java.lang.RuntimeException
Runtime Exceptions / Bugs
Core Java 55 Pages 34

Checked Exceptions
Describe problems that can arise in a correct program, typically difficulties with the environment like user input or IO problem

Runtime Exceptions
Describe program bugs, like accessing array elements out of its boundary. In a Bug free program, you re not required to handle these exceptions

Errors
Describe sufficiently unusual and sufficient difficult to recover from, that you are not required to handle them

Core Java 55 Pages

35

Exceptions and Overriding


import java.io.IOException; import java.net.MalformedURLException; class A{ public void fun() throws IOException{} // Base Class } class B extends A{ public void fun() throws IOException{} //Derived Class (Legal Overriding) } class C extends A{ public void fun() {} //Derived Class (Legal Overriding) } class D extends A{ //Derived Class (Legal Overriding) public void fun() throws IOException,MalformedURLException{} //MalformedURLException is subclass of IOException } class CB extends A{//Derived Class (ILLegal Overriding) public void fun() throws IOException,java.rmi.RemoteException{} //RemoteException is not subclass of IOException {} } class CA extends A{//Derived Class (ILLegal Overriding) public void fun() throws java.lang.Exception{} //Can t throw the super class of IOException } Core Java 55 Pages 36

Summary of method overriding with exceptions


Any overriding method defined in a subclass, must throw IOException or any object that is a subclass of IOException Overriding methods may not, however, throw any checked exceptions that are not subclasses of IOException

Core Java 55 Pages

37

Object Oriented Java


Relationships
You can have is a and has a

Ex:
A Home is a House which has a family and a Pet

public Home extends House { // is a relation Family myFamily; // has a relation Pet myPet; // has a relation }

Core Java 55 Pages

38

Overloading
If a method name is re-used in the class or a subclass of that class, the method name can be re-used if the argument list differs in terms of the type of at least one argument The return type alone is not sufficient to constitute an overload, it s illegal class A{ public void fun(){} public void fun(int i){} public void fun(float f){} public void fun(int i,float f){} public void fun(float f,int i){} } class Demo{ public static void main(String[]arg){ A obj = new A(); obj.fun(); obj.fun(123); obj.fun(1.23f); obj.fun(123,1.23f); obj.fun(1.23f,123); } Core Java 55 Pages }

39

Overriding
If a method name is reused in the strict subclass, the method name can be reused with identical argument types, order and with identical return type

class CA{ public void fun() { System.out.println( A.fun() ); } } class CB extends CA { public void fun() { System.out.println( B.fun() ); } } class Demo { public static void main(String[]arg){ CA a = new CA(); CA b = new CB(); a.fun(); b.fun(); } } This feature of Java is also known as Late Binding or Virtual Method Invocation Core Java 55 Pages

40

class CA{ public void fun(){ System.out.println( CA::fun() \n ); } } class CB extends CA{ public void fun() { super.fun(); System.out.println( CB::fun() \n ); } public static void main(String[]arg){ CB b = new CB(); b.fun(); } }

Core Java 55 Pages

41

Constructors and Inheritance


class CA{ public void CA(){ System.out.println( CA() \n ); } public void CA(int i){ System.out.println( CA(int) \n ); } } class CB extends CA{ public CB(){ System.out.println( CB()\n ); } public CB(int i){ super(i); System.out.println( CB(int)\n ); } public CB(int i, float f){ super(i); System.out.println( CB(int, float) \n ); } }

Core Java 55 Pages

42

Inner Classes Classes declared in another class


public class Outer { private int x; public class Inner{ private int y; public void fun() {} } public static void main(String[]arg){ Outer.Inner i = new Outer().new Inner(); // or Outer o = new Outer(); Inner i = o.new Inner(); } }

Core Java 55 Pages

43

Static Inner Classes


public class CA{ public static int i = 10; public static class CB{ public void fun(){ System.out.println( + CA.i); } } public static void main(String[]arg){ CA.CB obj = new CA.CB(); obj.fun(); } }

Core Java 55 Pages

44

Classes defined inside Methods


public class Outer{ public static void main(String[]arg){ Outer obj = new Outer(); obj.method(10,20); } public void method(int a, final int b){ int x = a + b; final int y = a - b; class Inner{ public void methodI(){ System.out.println("a " + a); // Illegal System.out.println("b " + b); System.out.println("x " + x); //Illegal System.out.println("y " + y); } } Inner i = new Inner(); i.methodI(); } } Core Java 55 Pages

45

Anonymous Classes
public void aMethod(){ myButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ } } ); }

Core Java 55 Pages

46

Converting & Casting


Conversion of Primitives Casting of primitives Conversion of object references Casting of object references

Core Java 55 Pages

47

Primitive Conversion

char

int

long

float

double

byte

short

Summarize: *A boolean may not be converted to any other type *A non-boolean may be converted to another non-boolean type, provided the conversion is a widening conversion *A non-boolean may not be converted to another non-boolean type, if the conversion would be a narrowing conversion
Core Java 55 Pages 48

Primitive Conversion: Arithmetic Promotion Unary Operators


If the operand is a byte, a short, or a char, it is converted to an int Else if the operand is of any other type, it is not converted

Binary Operators
If one of the operands is a double, the other operand is converted to a double Else if one of the operands is a float, the other operand is converted to a float Else if one of the operands is a long, the other operand is converted to a long Else both operands are converted to ints

Core Java 55 Pages

49

Primitive Casting
You can cast any non-boolean type to any other non-boolean type You cannot cast a boolean to any other type; you cannot cast any other type to a boolean

Core Java 55 Pages

50

Object Reference Conversion


Reference conversion takes place at compile time, because the compiler has all the information it needs to determine whether the conversion is legal It happens when you assign an object reference value to a variable of a different type There are three general kinds of object reference types
A class type An interface type An array type

Ex:
OldType x = new OldType(); NewType y = x;

Core Java 55 Pages

51

The rules for object reference assignment conversion

OldType is a class

Oldtype is an interface

OldType is an array

Newtype is a class Newtype is an interface Newtype is an array

OldType must be a subclass of Newtype Oldtype must implement interface Newtype Compiler error

Newtype must be Object Oldtype must a subinterface of Newtype Compiler error

Newtype must be Object Newtype must be Cloneable Oldtype must be an array of some object reference type that can be converted to whatever Newtype is an array of

Core Java 55 Pages

52

The rules for object reference conversion

An interface type may only be converted to an interface type or to Object. If the new type is an interface, it must be a super interface of the old type A class may be converted to a class type or to an interface type. If converting to a class type, the new type must be a superclass of the old type. If converting to an interface type, the old class must implement the interface An array may be converted to the class Object, to the interface Cloneable, or to an array. Only an array of object reference types may be converted to an array, and the old element type must be convertible to the new element type

Core Java 55 Pages

53

Object

Fruit

Citrus (Implements Squeezable

Lemon

Tangelo

Grapefruit

Core Java 55 Pages

54

Case 1: Tangelo tange = new Tangelo(); Citrus cit = tange; //Legal Conversion Case 2: Citrus cit = new Citrus(); Tangelo tange = cit; //Illegal Conversion, compilation error Case 3: Grapefruit g = new Grapefruit(); Sqeezable squee = g; // No Problem Grapefruit g2 = squee; //Compilation error Case 4: Fruit fruits[]; Lemon lemons[]; Citrus citruses[] = new Citrus[10]; for(int I=0;I<10;I++){ citruses[I] = new Citrus(); } fruits = citruses; // No Problem lemons = citruses; //Compilation eror

Core Java 55 Pages

55

Das könnte Ihnen auch gefallen