際際滷

際際滷Share a Scribd company logo
Basic JAVA
Write once run any where
Basic Language Elements
Identifiers, Keywords, Literals, White Spaces and Comments
Identifiers
 A name in a program is called an identifier.
 An identifier in java is composed of a sequence of characters, where
each character can be either a letter or digit or connecting symbol($,_).
 The first character in an identifier cant be a digit.
 Identifiers in java are case sensitive.
Keywords
 Key words are reserved identifiers.
 In java, all keywords are in lower case.
Literals
A literal denotes a constant value of a particular data type, the value a
literal represents remains unchanged in the program.
Primitive Data Types
DataType Bit Depth
1. boolean jvm specific
2. byte 8 bits
3. short 16 bits
4. int 32 bits
5. long 64 bits
6. char 16 bits
7. float 32 bits
8. double 64 bits
 All numeric data types except char are
signed data types.
 The default data type of an integer
(byte, short, int, long) literal is always
int.
long can be specified by appending L
or l as a suffix.Theres no way to
represent a byte or short literal.
 The dafault data type of floating point
literal is double.
float can be specified by appending F
or f as a suffix.
Javas Keywords
boolean byte char short int long float double
public private protected abstract static final native synchronized
transient volatile strictfp if else do while for
switch case default break continue assert class interface
extends implements import package new instanceof super this
try catch finally throw throws void return enum
Javas Reserved words
const goto
Javas reserved Literals
true false null
丱Java doesnt allow us to use any of the above as an identifier.
Q] /* // */ is it legal ?
Q] which of the following are keywords in java ?
a) instaceof b) object c) void d) main e) String f) enum g) null h) thrown
i)finalize j) native
Java Source file structure
損 An optional package declaration
損 Zero or more import declarations
損 Any no.of top level classes and interface declarations
 At the most one public class definition per source class can be defined.
If a public class is defined, the file name must match this class name.
 Except for package and import statements, all code is encapsulated in
classes and interfaces.
 like any other method, the main method can also be overloaded and
overrided.
Q] which of the following are valid main() method declarations in order to
start the execution of java application ?
a) Public static void main(String args) throws Exception
b) static public void main(String[] args)
c) final public static void main(String args[])
Class (a user defined data type)
 class is a logical construct upon which the entire java language is built.
 Objects are basic run time entities in java. class acts as a blue print for
similar type of objects.
 when you design a class, think about the objects that will be created from
that class, think about
1. Things the object knows (state)
2. Things the object does (behavior)
Alarm
alarmTime
setAlarmTime()
getAlarmTime()
isAlarmSet()
Things an object knows itself are called
instance variables.
Things an object can do are called
methods.
 classes give modularity in java.
[class modifiers] class <class name> [extends clause] [implements clause]
{
[variable declarations]
[method declarations]
[constructor declarations]
[initializer blocks]
[nested class declarations]
[nested interface declarations]
}
class Syntax
Java Variables
 A variable stores a value of a particular type.
 in java variables come in two flavors
1. primitive
2. reference
Variables that store references to objects are called reference variables.
 java has three types of variables
1. instance variables
2. static variables
3. local variables
Instance variables
損 Every object of the class will have its own copies of these variables, which
are local to object
損 The values of these variables at any given time constitute the state of the
object
損 Instance variables exist as long as object they belong to exist
Static variables
損 Belong only to the class, but not created for only object of the class
損 All objects of the class share the same copy of this variable
損 Class variables exist as long as class exist
Local Variables
損 Variables declared in methods including parameters or blocks are called
Local variables
損 After execution of the method or block completes local variables are no
longer accessible
 Local variables must be explicitly initialized before being used.
The compiler will report attempt to use un initialized local variables.
 if no initialization is provided for static or instance variable they
are initialized by default value of their type.
Default values of static/instance variables
Data Type Default Value
boolean false
char u0000
int or short or byte 0
long 0L
float 0.0f
double 0.0
reference types null
Java operators
() [] .
++ -- ~ !
* / %
+ -
<< >> >>>
>= < <=
== !=
&
^
|
&&
||
?:
= op=
Precedence table
Precedence rules are used to determine which
operator should be applied first if there are two
operators with different precedence.
The associative rules are used to determine
which operator should be applied first if there are
more than one operand with the same precedence.
the precedence and associative rules together
determine the evolution order of operators in an
expression.
All binary operators, except for the assignment
operator associate from left to right
Except for unary postfix increment and
decrement operators, all unary operators, all
assignment operator and ternary conditional
operator associate from right to left.
new operator is used to create objects and declare array
sizes.
 instanceof operator is used to test an objects type.
<source reference type> instanceof <destination type>
Q] int x=3;
x<<4;
s.o.p(x);
Q] int i=--4*2--;
s.o.p(i);
Type Conversions
 Java being a strongly typed language , checks for compatibility at compile
time. How ever some checks are only possible at runtime.
 Java demands that a cast be used to explicitly indicate the
type conversion (narrowing or downcasting)
(<type>) expression;
 Casting the value of a super class reference to a subclass type is
downcasting and the reverse is called upcasting.
Casting between primitive types and reference types is not possible
Boolean values cant be cast to other data types and vice versa
Widening and upcasting are implicit conversions
Narrowing typically requires explicit casting.
widening
byte short char int long float double
Numeric promotions
 Numeric promotion is implicitly applied on the operands to convert them
to permissible types.
Unary numeric promotion
 if the single operand of the operator has a type narrower than int, it is
converted to int by an implicit widening primitive conversion;
Binary numeric promotion
 Given T to be the broadest numeric type of two operands the operands are
promoted as follows
If( T is broader than int)
both operands are converted to T
else
both operands are converted to int
Implicit narrowing conversions
implicit narrowing conversions on assignment can occur in cases where all
of the following conditions are full filled
1. The source is a constant expression of either byte, short, char, or int type
2. The destination type is either byte, short or char type
3. The value of the source is determined to be in the range of the destination
type at compile time
Type conversion contexts
 Assignments
 Method invocation involving parameters
 Arithmetic expression involving numeric types
 String Concatenation involving String objects and other data types
Q] byte b=17;
b=b+2; //illegal
b+=2; //legal
Arrays
 In java, arrays are objects
Array declaration
<element type>[] <array name>
(or)
<element type> <array name>[]
<array name> =new <element type>[size];
 when the array is constructed, all its elements are initialized to the default
value of their element type. This is true for both members and local arrays.
 Java supports declaring , constructing, and explicitly initializing an array
in one stmt.
eg: int[] a={4,3,78,3};
Anonymous array
new <element type>[] {array list}
eg:new int[] {4,7,3,8,9};
Multi dimensional arrays
Method
[method modifiers] <return type> <method name> ([formal parameters]) [throws
clause]
{
[local variable declarations]
[statements]
[nested class declarations]
}
Parameter passing
 The parameter strategy in java is pass-by-value regardless of the type of
the parameter.
 The order of the evolution in actual parameter list is always from left to
right.
 if the actual parameter is a reference to an object then the reference value is
passed and not the object itself.
Method Over Loading
Several methods may have the same name, as long as the method
signatures differ.
For the over loading method,
 The arguments list must be different
 The return types can be different
 You can vary access levels in any direction
<Theres no polymorphism with over loading methods>
Method Overriding
For the overriding method ,
 Signature must be same as original method.
 Return type must be compatible with original method return type
 The new method definition cant narrow the accessibility
 The new method definition can only specify all or none or a subset of
exception classes in the throws clause.
 An instance method in a sub class cant override a static method in the
super class and vice versa.
 We cant override static methods rather we can hide them
Interfaces
[access modifier] interface <interface name> <extends interface clause>
{
[constant declarations]
[method prototype declarations]
}
 The methods in an interface are implicitly abstract and public and the
constants are implicitly public, static and final.
 An interface can extend other interfaces
 An interface which has no methods to implement is known as Marker or
tag or ability interface.
Inheritance
 It allows new classes to be derived from existing classes. And it is the
main thing in Java for code reuse.
 private members of a class are not inherited and also members that have a
package accessibility in the super class are also not inherited by sub classes
in other packages.
 Since constructors and initializer blocks are not members of a class they
are not inherited by a sub class.
 To avoid D3(Deadly Diamond of Death) problem java doesnt support
multiple inheritance. So a class in java can extend at most one other class.
 java gives multiple interface inheritance through interfaces. So a class can
implement many interfaces.
Any class that doesnt explicitly extend another class, implicitly extends
<Object> class.
So any class in java, either directly or indirectly extends Object class.
 classes up the inheritance hierarchy are more generalized and classes down
the hierarchy are more specialized.
Inheritance defines the is-a relationship between a super class and its sub
class. This means that an object of a sub class can be used where ever an
object of the super class can be used.
 It is not possible for two classes to be the super classes of each other
If A extends B then A is-a B
Aggregation
Aggregation defines has-a relationship between objects.
If A has a reference to B then A has-a B
Polymorphism
The ability of a super class or super type reference to denote objects of its
own class and its sub classes at runtime is called polymorphism.
 polymorphism is achieved through inheritance and interface
implementation
 The instance method invocation is dependent on the type of the actual
object denoted by the reference at runtime.
 Field access and static method access is determined by the reference
type not by the actual object.
 you can call a method on an object only if the class of the reference
variable has that method.
Static Block
static
{
//code
}
 The code in a static block is executed once only when the class is loaded .
 These are primarily used for initializing static fields.
 Static block is not contained in any method
 A class can have more than one static block. In this case the blocks are
executed in the order of their declarations in the class.
Instance Block
{
//code
}
 The code in an instance block is executed every time an object is created.
 Instance block is not contained in any method
 A class can have more than one instance block. In this the blocks are
executed in the order of their declarations in the class.
 An instance initializer block can be used to factor out common
initialization code that will be executed regardless of which constructor is
invoked.
Control Flow stmts
Control flow statements govern the flow of control in a program during
execution.
There are three categories of control flow stmts
1. Selection stmts [if, if-else, switch]
2. Iteration stmts [for, while, do-while]
3. Transfer stmts [break, continue, return, throw, try-catch-flow and
assert]
Packages
A package in java is an encapsulation mechanism that can be used to group
related classes, interfaces and sub packages.
package <fully qualified package name>
 At most one package declaration can appear in a source file, and it must
be the first statement.
 The package name is saved in java byte code for the types contained in
the package.
 If a package stmt is omitted in a source file, then respective class files
are placed in a unnamed package (current working directory)
 packages prevent class name conflicts.
 (java convention) preface your packages with your reverse domain name
to prevent package name conflicts.
 To put your class in package, The package hierarchy must match the
directory structure
Using packages,
we can use the existing package in two ways
1. Using the fully qualified name of the type.
2. Using import declarations.
Import
import <fully qualified name> // single type import
import <fully qualified name>.* //import on demand
 An import declaration doesnt recursively import sub packages.
Modifiers
1. Access modifiers
 public
 protected
 no modifier (package access)
 private
2. static
3. final
4. abstract
5. synchronized
6. native
7. transient
8. volatile
9. threadsafe
Top level classes and
interfaces
public, no modifier
abstract and final
Inner classes All Access modifiers
abstract, static and final
Fields All access modifiers
static, final, transient and volatile
Methods All access modifiers
abstract, static, final, synchronized and native
Member Type Possible modifiers
Modifier Class Package Sub class
(out side
package)
World
public Y Y Y Y
protected Y Y Y N
default Y Y N N
private Y N N N
Access modifiers
 Use most restrictive access level that makes sense for a particular
member.
 Avoid public fields accept for constants
public fields limit your flexibility in changing your code.
Abstract method
 An abstract method has no implementation (no body) it just specifies
method prototype
 You cant have an abstract method in a non abstract class
 If you put even a single abstract method in a class, you have to make the
class abstract.
 Only an instance method can be declared as abstract (we cant override a
static method)
 A final method cant be abstract
Abstract class
 Abstract class means, The class which is partially implemented
 We cant instantiate an abstract class. We can still use the abstract type as
a reference type, for the purpose of polymorphism
 If you put even a single abstract method in a class you have to make the
class abstract.
 Even if there are no abstract methods you can declare class as abstract
just make it as a non concrete class.
 You can mix both abstract and non-abstract methods in an abstract class.
 The sub class which extends abstract class must implement all the
abstract methods or declare it also as abstract.
static
 Static members belong to the class in which they are declared.
 We can access static members through class name or through object
reference of that class.
 We cant access non-static members in static context.
Static context =>static initializer expression
static initializer blocks
static methods
static inner classes
 Object neednt be instantiated to access its static members.
 Only inner classes can be declared as static
 static variables are not part of a object state
 we cant override static methods in sub classes, rather we can hide them
Final variable
 A final variable of primitive data type cant change its value
once it has been initialized
 A final variable of a reference type cant change its reference
value once it has been initialized but the state of the object it
denotes can still be changed.
 Applicable to instance, static, and local variables.
 Blank finals
Final method
 We cant override a final method in sub classes.
Final class
 A Final class cant be extended
 only a class whose definition is complete can be declared final.
 Make a class that doesnt extends any thing when your new classes
doesnt passes is-a test for any other type.
 Make a sub class only when you need to make a more specific version
of a class and need to override or add new behavior
 Use an abstract class when you want to define a template for a group
classes and at least you have some implementation that all classes could
use.
Use an interface when you want to define a role that other classes can
play regardless of where those classes are in the inheritance tree.
This was my first KT.
Given in honing solutions in 2006.

More Related Content

What's hot (20)

7.data types in c#
7.data types in c#7.data types in c#
7.data types in c#
Zeeshan Ahmad
Java Methods
Java MethodsJava Methods
Java Methods
OXUS 20
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
Strings in java
Strings in javaStrings in java
Strings in java
Kuppusamy P
Java basic
Java basicJava basic
Java basic
Sonam Sharma
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
Savitribai Phule Pune University
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
NewCircle Training
Java Array String
Java Array StringJava Array String
Java Array String
Manish Tiwari
Java tokens
Java tokensJava tokens
Java tokens
shalinikarunakaran1
Core java
Core javaCore java
Core java
Shivaraj R
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
Python
PythonPython
Python
Gagandeep Nanda
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
Java program structure
Java program structure Java program structure
Java program structure
Mukund Kumar Bharti
Chapter 13 - Recursion
Chapter 13 - RecursionChapter 13 - Recursion
Chapter 13 - Recursion
Adan Hubahib
Methods in java
Methods in javaMethods in java
Methods in java
chauhankapil
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
kunal kishore
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch

Viewers also liked (9)

Java session01
Java session01Java session01
Java session01
Niit Care
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
sshhzap
Introduction to java technology
Introduction to java technologyIntroduction to java technology
Introduction to java technology
Indika Munaweera Kankanamge
Jena A Semantic Web Framework for Java
Jena  A Semantic Web Framework for JavaJena  A Semantic Web Framework for Java
Jena A Semantic Web Framework for Java
Aleksander Pohl
Intuit commissions manager
Intuit commissions managerIntuit commissions manager
Intuit commissions manager
sshhzap
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
Jong Soon Bok
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
Danairat Thanabodithammachari
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady Booch
Sorina Chiril
Java session01
Java session01Java session01
Java session01
Niit Care
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
sshhzap
Jena A Semantic Web Framework for Java
Jena  A Semantic Web Framework for JavaJena  A Semantic Web Framework for Java
Jena A Semantic Web Framework for Java
Aleksander Pohl
Intuit commissions manager
Intuit commissions managerIntuit commissions manager
Intuit commissions manager
sshhzap
Chapter 1. java programming language overview
Chapter 1. java programming language overviewChapter 1. java programming language overview
Chapter 1. java programming language overview
Jong Soon Bok
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
Object-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady BoochObject-Oriented Analysis And Design With Applications Grady Booch
Object-Oriented Analysis And Design With Applications Grady Booch
Sorina Chiril

Similar to Java Basics (20)

Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
Rakesh Madugula
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
SaqlainYaqub1
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
Java Basics
Java BasicsJava Basics
Java Basics
Emprovise
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
Archana Gopinath
Java Programming
Java Programming Java Programming
Java Programming
RubaNagarajan
Data types ^J variables and arrays in Java.pptx
Data types ^J variables and arrays in Java.pptxData types ^J variables and arrays in Java.pptx
Data types ^J variables and arrays in Java.pptx
sksumayasumaya5
JAVA Basics Presentation for introduction to JAVA programming languauge
JAVA Basics Presentation for introduction to JAVA programming languaugeJAVA Basics Presentation for introduction to JAVA programming languauge
JAVA Basics Presentation for introduction to JAVA programming languauge
lakshyajain0740
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
BG Java EE Course
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
Shashwat Shriparv
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
rnkhan
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
rnkhan
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
Java Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer ScienceJava Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer Science
AnezkaJaved
Learning core java
Learning core javaLearning core java
Learning core java
Abhay Bharti
JAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf VsjsjsnhehehJAVA Class Presentation.pdf Vsjsjsnheheh
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
Lecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptxLecture2_MCS4_Evening.pptx
Lecture2_MCS4_Evening.pptx
SaqlainYaqub1
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
manish kumar
Java Basics
Java BasicsJava Basics
Java Basics
Emprovise
PCSTt11 overview of java
PCSTt11 overview of javaPCSTt11 overview of java
PCSTt11 overview of java
Archana Gopinath
Java Programming
Java Programming Java Programming
Java Programming
RubaNagarajan
Data types ^J variables and arrays in Java.pptx
Data types ^J variables and arrays in Java.pptxData types ^J variables and arrays in Java.pptx
Data types ^J variables and arrays in Java.pptx
sksumayasumaya5
JAVA Basics Presentation for introduction to JAVA programming languauge
JAVA Basics Presentation for introduction to JAVA programming languaugeJAVA Basics Presentation for introduction to JAVA programming languauge
JAVA Basics Presentation for introduction to JAVA programming languauge
lakshyajain0740
Introduction to-programming
Introduction to-programmingIntroduction to-programming
Introduction to-programming
BG Java EE Course
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
Shashwat Shriparv
C# language basics (Visual Studio)
C# language basics (Visual Studio) C# language basics (Visual Studio)
C# language basics (Visual Studio)
rnkhan
C# language basics (Visual studio)
C# language basics (Visual studio)C# language basics (Visual studio)
C# language basics (Visual studio)
rnkhan
classes-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptxclasses-objects in oops java-201023154255.pptx
classes-objects in oops java-201023154255.pptx
janetvidyaanancys
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
Raja Sekhar
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
Tushar B Kute
Java Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer ScienceJava Basic Elements Lecture on Computer Science
Java Basic Elements Lecture on Computer Science
AnezkaJaved

Java Basics

  • 1. Basic JAVA Write once run any where
  • 2. Basic Language Elements Identifiers, Keywords, Literals, White Spaces and Comments Identifiers A name in a program is called an identifier. An identifier in java is composed of a sequence of characters, where each character can be either a letter or digit or connecting symbol($,_). The first character in an identifier cant be a digit. Identifiers in java are case sensitive. Keywords Key words are reserved identifiers. In java, all keywords are in lower case. Literals A literal denotes a constant value of a particular data type, the value a literal represents remains unchanged in the program.
  • 3. Primitive Data Types DataType Bit Depth 1. boolean jvm specific 2. byte 8 bits 3. short 16 bits 4. int 32 bits 5. long 64 bits 6. char 16 bits 7. float 32 bits 8. double 64 bits All numeric data types except char are signed data types. The default data type of an integer (byte, short, int, long) literal is always int. long can be specified by appending L or l as a suffix.Theres no way to represent a byte or short literal. The dafault data type of floating point literal is double. float can be specified by appending F or f as a suffix.
  • 4. Javas Keywords boolean byte char short int long float double public private protected abstract static final native synchronized transient volatile strictfp if else do while for switch case default break continue assert class interface extends implements import package new instanceof super this try catch finally throw throws void return enum Javas Reserved words const goto Javas reserved Literals true false null 丱Java doesnt allow us to use any of the above as an identifier. Q] /* // */ is it legal ? Q] which of the following are keywords in java ? a) instaceof b) object c) void d) main e) String f) enum g) null h) thrown i)finalize j) native
  • 5. Java Source file structure 損 An optional package declaration 損 Zero or more import declarations 損 Any no.of top level classes and interface declarations At the most one public class definition per source class can be defined. If a public class is defined, the file name must match this class name. Except for package and import statements, all code is encapsulated in classes and interfaces. like any other method, the main method can also be overloaded and overrided. Q] which of the following are valid main() method declarations in order to start the execution of java application ? a) Public static void main(String args) throws Exception b) static public void main(String[] args) c) final public static void main(String args[])
  • 6. Class (a user defined data type) class is a logical construct upon which the entire java language is built. Objects are basic run time entities in java. class acts as a blue print for similar type of objects. when you design a class, think about the objects that will be created from that class, think about 1. Things the object knows (state) 2. Things the object does (behavior) Alarm alarmTime setAlarmTime() getAlarmTime() isAlarmSet() Things an object knows itself are called instance variables. Things an object can do are called methods. classes give modularity in java.
  • 7. [class modifiers] class <class name> [extends clause] [implements clause] { [variable declarations] [method declarations] [constructor declarations] [initializer blocks] [nested class declarations] [nested interface declarations] } class Syntax
  • 8. Java Variables A variable stores a value of a particular type. in java variables come in two flavors 1. primitive 2. reference Variables that store references to objects are called reference variables. java has three types of variables 1. instance variables 2. static variables 3. local variables
  • 9. Instance variables 損 Every object of the class will have its own copies of these variables, which are local to object 損 The values of these variables at any given time constitute the state of the object 損 Instance variables exist as long as object they belong to exist Static variables 損 Belong only to the class, but not created for only object of the class 損 All objects of the class share the same copy of this variable 損 Class variables exist as long as class exist Local Variables 損 Variables declared in methods including parameters or blocks are called Local variables 損 After execution of the method or block completes local variables are no longer accessible
  • 10. Local variables must be explicitly initialized before being used. The compiler will report attempt to use un initialized local variables. if no initialization is provided for static or instance variable they are initialized by default value of their type. Default values of static/instance variables Data Type Default Value boolean false char u0000 int or short or byte 0 long 0L float 0.0f double 0.0 reference types null
  • 11. Java operators () [] . ++ -- ~ ! * / % + - << >> >>> >= < <= == != & ^ | && || ?: = op= Precedence table Precedence rules are used to determine which operator should be applied first if there are two operators with different precedence. The associative rules are used to determine which operator should be applied first if there are more than one operand with the same precedence. the precedence and associative rules together determine the evolution order of operators in an expression. All binary operators, except for the assignment operator associate from left to right Except for unary postfix increment and decrement operators, all unary operators, all assignment operator and ternary conditional operator associate from right to left.
  • 12. new operator is used to create objects and declare array sizes. instanceof operator is used to test an objects type. <source reference type> instanceof <destination type> Q] int x=3; x<<4; s.o.p(x); Q] int i=--4*2--; s.o.p(i);
  • 13. Type Conversions Java being a strongly typed language , checks for compatibility at compile time. How ever some checks are only possible at runtime. Java demands that a cast be used to explicitly indicate the type conversion (narrowing or downcasting) (<type>) expression; Casting the value of a super class reference to a subclass type is downcasting and the reverse is called upcasting. Casting between primitive types and reference types is not possible Boolean values cant be cast to other data types and vice versa Widening and upcasting are implicit conversions Narrowing typically requires explicit casting. widening byte short char int long float double
  • 14. Numeric promotions Numeric promotion is implicitly applied on the operands to convert them to permissible types. Unary numeric promotion if the single operand of the operator has a type narrower than int, it is converted to int by an implicit widening primitive conversion; Binary numeric promotion Given T to be the broadest numeric type of two operands the operands are promoted as follows If( T is broader than int) both operands are converted to T else both operands are converted to int
  • 15. Implicit narrowing conversions implicit narrowing conversions on assignment can occur in cases where all of the following conditions are full filled 1. The source is a constant expression of either byte, short, char, or int type 2. The destination type is either byte, short or char type 3. The value of the source is determined to be in the range of the destination type at compile time Type conversion contexts Assignments Method invocation involving parameters Arithmetic expression involving numeric types String Concatenation involving String objects and other data types Q] byte b=17; b=b+2; //illegal b+=2; //legal
  • 16. Arrays In java, arrays are objects Array declaration <element type>[] <array name> (or) <element type> <array name>[] <array name> =new <element type>[size]; when the array is constructed, all its elements are initialized to the default value of their element type. This is true for both members and local arrays. Java supports declaring , constructing, and explicitly initializing an array in one stmt. eg: int[] a={4,3,78,3}; Anonymous array new <element type>[] {array list} eg:new int[] {4,7,3,8,9}; Multi dimensional arrays
  • 17. Method [method modifiers] <return type> <method name> ([formal parameters]) [throws clause] { [local variable declarations] [statements] [nested class declarations] } Parameter passing The parameter strategy in java is pass-by-value regardless of the type of the parameter. The order of the evolution in actual parameter list is always from left to right. if the actual parameter is a reference to an object then the reference value is passed and not the object itself.
  • 18. Method Over Loading Several methods may have the same name, as long as the method signatures differ. For the over loading method, The arguments list must be different The return types can be different You can vary access levels in any direction <Theres no polymorphism with over loading methods>
  • 19. Method Overriding For the overriding method , Signature must be same as original method. Return type must be compatible with original method return type The new method definition cant narrow the accessibility The new method definition can only specify all or none or a subset of exception classes in the throws clause. An instance method in a sub class cant override a static method in the super class and vice versa. We cant override static methods rather we can hide them
  • 20. Interfaces [access modifier] interface <interface name> <extends interface clause> { [constant declarations] [method prototype declarations] } The methods in an interface are implicitly abstract and public and the constants are implicitly public, static and final. An interface can extend other interfaces An interface which has no methods to implement is known as Marker or tag or ability interface.
  • 21. Inheritance It allows new classes to be derived from existing classes. And it is the main thing in Java for code reuse. private members of a class are not inherited and also members that have a package accessibility in the super class are also not inherited by sub classes in other packages. Since constructors and initializer blocks are not members of a class they are not inherited by a sub class. To avoid D3(Deadly Diamond of Death) problem java doesnt support multiple inheritance. So a class in java can extend at most one other class. java gives multiple interface inheritance through interfaces. So a class can implement many interfaces. Any class that doesnt explicitly extend another class, implicitly extends <Object> class. So any class in java, either directly or indirectly extends Object class.
  • 22. classes up the inheritance hierarchy are more generalized and classes down the hierarchy are more specialized. Inheritance defines the is-a relationship between a super class and its sub class. This means that an object of a sub class can be used where ever an object of the super class can be used. It is not possible for two classes to be the super classes of each other If A extends B then A is-a B Aggregation Aggregation defines has-a relationship between objects. If A has a reference to B then A has-a B
  • 23. Polymorphism The ability of a super class or super type reference to denote objects of its own class and its sub classes at runtime is called polymorphism. polymorphism is achieved through inheritance and interface implementation The instance method invocation is dependent on the type of the actual object denoted by the reference at runtime. Field access and static method access is determined by the reference type not by the actual object. you can call a method on an object only if the class of the reference variable has that method.
  • 24. Static Block static { //code } The code in a static block is executed once only when the class is loaded . These are primarily used for initializing static fields. Static block is not contained in any method A class can have more than one static block. In this case the blocks are executed in the order of their declarations in the class.
  • 25. Instance Block { //code } The code in an instance block is executed every time an object is created. Instance block is not contained in any method A class can have more than one instance block. In this the blocks are executed in the order of their declarations in the class. An instance initializer block can be used to factor out common initialization code that will be executed regardless of which constructor is invoked.
  • 26. Control Flow stmts Control flow statements govern the flow of control in a program during execution. There are three categories of control flow stmts 1. Selection stmts [if, if-else, switch] 2. Iteration stmts [for, while, do-while] 3. Transfer stmts [break, continue, return, throw, try-catch-flow and assert]
  • 27. Packages A package in java is an encapsulation mechanism that can be used to group related classes, interfaces and sub packages. package <fully qualified package name> At most one package declaration can appear in a source file, and it must be the first statement. The package name is saved in java byte code for the types contained in the package. If a package stmt is omitted in a source file, then respective class files are placed in a unnamed package (current working directory) packages prevent class name conflicts. (java convention) preface your packages with your reverse domain name to prevent package name conflicts. To put your class in package, The package hierarchy must match the directory structure
  • 28. Using packages, we can use the existing package in two ways 1. Using the fully qualified name of the type. 2. Using import declarations. Import import <fully qualified name> // single type import import <fully qualified name>.* //import on demand An import declaration doesnt recursively import sub packages.
  • 29. Modifiers 1. Access modifiers public protected no modifier (package access) private 2. static 3. final 4. abstract 5. synchronized 6. native 7. transient 8. volatile 9. threadsafe
  • 30. Top level classes and interfaces public, no modifier abstract and final Inner classes All Access modifiers abstract, static and final Fields All access modifiers static, final, transient and volatile Methods All access modifiers abstract, static, final, synchronized and native Member Type Possible modifiers
  • 31. Modifier Class Package Sub class (out side package) World public Y Y Y Y protected Y Y Y N default Y Y N N private Y N N N Access modifiers Use most restrictive access level that makes sense for a particular member. Avoid public fields accept for constants public fields limit your flexibility in changing your code.
  • 32. Abstract method An abstract method has no implementation (no body) it just specifies method prototype You cant have an abstract method in a non abstract class If you put even a single abstract method in a class, you have to make the class abstract. Only an instance method can be declared as abstract (we cant override a static method) A final method cant be abstract
  • 33. Abstract class Abstract class means, The class which is partially implemented We cant instantiate an abstract class. We can still use the abstract type as a reference type, for the purpose of polymorphism If you put even a single abstract method in a class you have to make the class abstract. Even if there are no abstract methods you can declare class as abstract just make it as a non concrete class. You can mix both abstract and non-abstract methods in an abstract class. The sub class which extends abstract class must implement all the abstract methods or declare it also as abstract.
  • 34. static Static members belong to the class in which they are declared. We can access static members through class name or through object reference of that class. We cant access non-static members in static context. Static context =>static initializer expression static initializer blocks static methods static inner classes Object neednt be instantiated to access its static members. Only inner classes can be declared as static static variables are not part of a object state we cant override static methods in sub classes, rather we can hide them
  • 35. Final variable A final variable of primitive data type cant change its value once it has been initialized A final variable of a reference type cant change its reference value once it has been initialized but the state of the object it denotes can still be changed. Applicable to instance, static, and local variables. Blank finals Final method We cant override a final method in sub classes. Final class A Final class cant be extended only a class whose definition is complete can be declared final.
  • 36. Make a class that doesnt extends any thing when your new classes doesnt passes is-a test for any other type. Make a sub class only when you need to make a more specific version of a class and need to override or add new behavior Use an abstract class when you want to define a template for a group classes and at least you have some implementation that all classes could use. Use an interface when you want to define a role that other classes can play regardless of where those classes are in the inheritance tree.
  • 37. This was my first KT. Given in honing solutions in 2006.