SlideShare ist ein Scribd-Unternehmen logo
1 von 59
Core Java Basics
www.harshithatechnologies.com
info@harshithatechnologies.com
mhtspvtltd@gmail.com
040-42020378, 9989630313
Software Training || Consulting || OutSourcing
Data Types
Data Types
Primitive Types
Type Representation Range
byte 8-bit, signed -128 to 127
short 16-bit, signed -32768 to 32767
int 32-bit, signed -2147483648 to 2147483647
long 64-bit, signed -9223372036854775808 to
9223372036854775807
char 16-bit, unsigned, Unicode
float 32-bit 1.40239846e-45 to 3.40282347e+38
double 64-bit 4.94065645841246544e-324 to
1.79769313486231570e+308
boolean
Java Operators
Precedence Operator Description
1 ++, -- Increment and decrement
1 +, - Unary plus and minus
1 ~ Bitwise complement
1 ! Boolean
2 *, /, % Multiplication, division, remainder
3 +, - Addition and subtraction
3 + String
4 << Left shift
4 >> Right shift with sign extension
4 >>> Right shift with no extension
5 <, <=, >, >= Numeric comparison
5 instanceof Type comparison
6 ==, != Equality and inequality of value
6 ==, != Equality and inequality of reference
7 & Bitwise AND
8 ^ Bitwise XOR
9 | Bitwise OR
10 && Conditional AND
11 || Conditional OR
12 ?: Conditional ternary operator
13 = *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |=
Assignment
Keywords
abstract default goto null synchronized
boolean do if package this
break double implements private throw
byte else import protected throws
case extends instanceof public transient
catch false int return true
char final interface short try
class finally long static void
const float native super volatile
continue for new switch while
Comments
Java supports three styles of comments:
•A standard C-style comment, where all of the characters between
/* and */ are ignored.
•A single-line comment, where all of the characters from
// to the end of the line are ignored.
•A documentation comment that begins with
/** and ends with */.
Literals
Integer literals
Integer literals can be specified in octal (base 8), decimal (base 10), or
hexadecimal (base 16).
int i = 1230;
int i = 01230; // i = 664 decimal
int i = 0xFFFF;
Floating-point literals
Floating-point literals are of type double unless they are suffixed
with an f denoting that they are to be produced as a float value:
double d = 8.31;
double e = 3.00e+8;
float f = 8.31F; float g = 3.00e+8F;
Character literals
A literal character value can be specified either as a single-quoted
character or as an escaped ASCII or Unicode sequence:
char a = 'a';
char newline = 'n';
char ch = 88 ; //code for X
Boolean Literals
It can have only one of two possible values, true or false
boolean b = false;
Type Conversion and Casting
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if
• The two types are compatible
• The destination type is larger than the source type.
Casting Incompatible Types
To create a conversion between two incompatible types, you must
use a cast.
(target-type) value;
Casting
1) int a;
a = 10;
byte b;
b = (byte) a;
2) byte b;
int i = 257;
b = (byte) i; // 1
3) double d = 223.22;
int i = (int) d; // 223
Automatic Type Promotion in Expressions
Java automatically promotes each byte type or short operand to int
when evaluating an expression.
byte b= 50;
b = b * 2; // Error. Cannot assign an int to a byte
b = (byte) (b*2); // valid
Array Creation and Initialization
As in C, array indices start with zero.
After creation, the array elements are initialized to the default values for
their type.
For numeric types, this means the elements are initially zero:
int [] grades = new int [30];
grades[0] = 99;
grades[1] = 72;
Java supports the C-style curly braces {} construct for creating an
array and initializing its elements when it is declared:
int [] primes = { 1, 2, 3, 5, 7, 7+4 };
An array object of the proper type and length is
implicitly created.
Comparing C++ and Java
The important features that distinguish Java from C++.
1. The biggest potential stumbling block is speed: interpreted Java runs
in the range of 20 times slower than C.
2. Everything must be in a class. There are no global functions or global
data. If you want the equivalent of globals, make static methods
and static data within a class.
3. There are no structs or enumerations or unions, only classes.
4. All method definitions are defined in the body of the class. Thus, in
C++ it would look like all the functions are inlined, but they’re not.
5. Class definitions are roughly the same form in Java as in C++, but
there’s no closing semicolon. There are no class declarations of the
form class foo; , only class definitions.
6. There’s no scope resolution operator :: in Java.
7. In addition, package names are established using the dot, and to
perform a kind of C++ #include you use the import keyword.
For example: import java.awt.*;.
8. Java, like C++, has primitive types for efficient access. All the
primitive types have specified sizes that are machine independent for
portability.
9. Type-checking and type requirements are much tighter in Java.
For example:
1. Conditional expressions can be only boolean, not integral.
2. The result of an expression like X + Y must be used;
10. The char type uses the international 16-bit Unicode character set, so
it can automatically represent most national characters.
11. Static quoted strings are automatically converted into String
objects. There is no independent static character array string like there is
in C and C++.
12. Java adds the triple right shift >>> to act as a “logical” right shift by
inserting zeroes at the top end;
13. Although they look similar, arrays have a very different structure and
behavior in Java than they do in C++. There’s a read-only length
member that tells you how big the array is, and run-time checking throws
an exception if you go out of bounds.
All arrays are created on the heap, and you can assign one array to
another (the array handle is
simply copied). The array identifier is a an object
14. All objects of non-primitive types can be created only via new.
There’s no equivalent to creating non-primitive objects “on the stack” as
in C++.
15. All primitive types can be created only on the stack, without new.
There are wrapper classes for all primitive classes so that you can create
equivalent heap-based objects via new.
17. Java has no preprocessor. There are no preprocessor-like macros.
18. Initialization of class data members is guaranteed in Java; if you
don’t explicitly initialize them they get a default value (a zero or
equivalent). You can initialize them explicitly, either when you define
them in the class or in the constructor.
19. There are no Java pointers in the sense of C and C++.
20. There are no destructors in Java. The lifetime of an object is
determined instead by the garbage collector.
There is a finalize( ) method that’s a member of each class, something
like a C++ destructor, but finalize( ) is called by the garbage collector
and is supposed to be responsible only for releasing "resources" (such as
open files, sockets, ports, URLs, etc).
21. Java does not support default arguments.
22. Java uses a singly-rooted hierarchy, so all objects are ultimately
inherited from the root class Object.
In C++, you can start a new inheritance tree anywhere, so you end up
with a forest of trees. In Java you get a single ultimate hierarchy.
23. Garbage collection means memory leaks are much harder to cause in
Java, but not impossible.
24. No inline methods. The Java compiler might decide on its own to
inline a method, but you don’t have much control over this. You can
suggest inlining in Java by using the final keyword for a method.
25. Java has method overloading, but no operator overloading.
Generally, Java is more robust, via:
– Object handles initialized to null (a keyword)
– Handles are always checked and exceptions are thrown for failures
– All array accesses are checked for bounds violations
– Automatic garbage collection prevents memory leaks
– Clean, relatively fool-proof exception handling
– Simple language support for multithreading
– Bytecode verification of network applets
HelloWorld.java
public class HelloWorld
{ public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
C:> javac HelloWorld.java
//produces the HelloWorld.class
C:> java HelloWorld //when you invoke the
interpreter, you do not supply the .class extension
System class has several fields, and if you select
out you’ll discover that it’s a static PrintStream object.
Since it’s static you don’t need to create anything.
The out object is always there and you can just use it.
println( ), method prints to the console and end with a new line.
class P
{
public static void main(String args[])
{ int x =34;
int y =42;
System.out.println("X = " + x);
System.out.println("y = " + y);
int z = x+y;
System.out.println("z = " + z);
}
}
All local variables has to be initialized before using.
Arithmetic Operators and Logical Operators
are same as that of C Programming Language.
The Left Shift operator
int i;
byte a = 256,b;
i = a<< 2;
b = (byte) (a<<2);
System.out.println(“ i and b : “ + i + “ “ + b);
// i and b : 256 and 0
a is promoted to int for the purpose of evaluation, left shifting the value
64 twice results in I containing the value 256
0100 0000
0000 0001 0000 0000
The Right Shift operator
int a =32 ;
a = a >> 1; // a now contains 16
int x = 35;
x = x >> 2; // x contains 8
0010 0011 35
>>2
0000 1000 8
---------------------------------------------------
11111000 -8
>>1
11111100 -4
The Unsigned Right Shift operator
>>> shifts zero’s into the high-order bit.
int a = -1 ;
a = a >>> 24;
11111111 11111111 11111111 11111111 // -1 in binary
>>> 24
00000000 00000000 00000000 11111111 // 255 in binary
Boolean Logical Operators
& Logical AND
| Logical OR
^ Logical XOR
&& Short- Circuit Logical AND
|| Short- Circuit Logical OR
If you use the || and && forms rather than | and & forms , Java
will not bother to evaluate the right hand operand when the outcome of
the expression can be determined by the left operand alone.
if( denom != 0 && num /denom >10) // if denom =0 short circuit
if( c = =1 & e++ <100) d= 100;
Single & ensures that the increment operation will be applied whether c
is equal to 1 or not.
Classes and Objects
A Class is a template for an object,
And an object is an instance of a class.
These characteristics represent a pure approach to object-oriented
programming:
1. Everything is an object.
2. A program is a bunch of objects telling each other
what to do by sending messages.
3. All objects of a particular type can receive the same
messages.
4. Tight Cohesion within an object and Loose coupling
among objects.
The Class of Circles
public class Circle
{
public double x, y; // The coordinates of the center
public double r; // The radius
// Method that returns the area of the circle
public double area( )
{
return 3.14159 * r*r;
}
}
Objects Are Instances of a Class
We can declare variables of that type:
Circle c;
But this variable c is simply a name that refers to a circle object; it
is not an object itself.
In Java, all objects must be created dynamically. This is almost
always done with the new keyword:
c = new Circle();
Now we have created an instance of our Circle class--a circle
object--and have assigned it to the variable c, which is of type
Circle.
Accessing Object Data
c.x = 2.0; // Initialize our circle to have center (2, 2) and radius 1.0.
c.y = 2.0; c.r = 1.0;
Using Object Methods
double a;
a = c.area();
How can a method that takes no arguments know what
data to operate on?
In fact, the area() method does have an argument!
area() is implemented with an implicit argument that is not
shown in the method declaration.
The implicit argument is named this, and refers to "this
object"-- the Circle object through which the method is
invoked.
The implicit this argument is not shown in method
signatures.
We can use the this keyword explicitly.
Constructor
public class Circle
{
public double x, y, r; // The center and the radius of the circle
// The constructor method.
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r; } …………
With this new constructor the initialization becomes part of the
object creation step:
Circle c = new Circle(1.414, -1.0,1 .25);
There are two important notes about naming and declaring
constructors:
•The constructor name is always the same as the class name.
Multiple Circle Constructors
public class Circle {
public double x, y, r;
// Initializing constructors
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r; }
public Circle(double r) { x = 0.0; y = 0.0; this.r = r; }
// Copy Constructor
public Circle(Circle c) { x = c.x; y = c.y; r = c.r; }
//Default Constructor
public Circle() { x = 0.0; y = 0.0; r = 1.0; }
this Again
There is a specialized use of the this keyword that arises when a class
has multiple constructors
--it can be used from a constructor to invoke one of the other
constructors of the same class.
public Circle(double x, double y, double r)
{ this.x = x; this.y = y; this.r = r; }
public Circle(double r) { this(0.0, 0.0, r); }
public Circle(Circle c) { this(c.x, c.y, c.r); }
public Circle() { this(0.0, 0.0, 1.0); }
This would be a more impressive example, of course, if the first
constructor that we were invoking did a more significant amount of
initialization.
Class Variables
Java uses the static keyword to indicate that a particular variable is a
class variable rather than an instance variable.
That is, that there is only one copy of the variable, associated with the
class, rather than many copies of the variable associated with each
instance of the class.
The one copy of the variable exists regardless of the number of instances
of the class that are created--it exists and can be used even if the class is
never actually instantiated.
Static Variable Example
public class Circle
{ static int num_circles = 0; // class variable: how many circles
created public double x, y, r; // instance vars: the center and
the radius
public Circle(double x, double y, double r)
Accessing Class Variables
Because static variables are associated with the class rather than with an
instance, we access them through the class rather than through the
instance
System.out.println("Number of circles created: " +
Circle.num_circles);
Constants: Another Class Variable Example
When computing the area and circumference of circles, we use the value
pi. Since we use the value frequently, we don't want to keep typing
out 3.14159, so we'll define it as a class variable that has a convenient
name:
public class Circle
{
public static final double PI = 3.14159;
public double x, y, r;
// ... etc....
}
Besides the static keyword that we've already seen, we use the final
keyword, which means that this variable can never have its value
changed.
static Methods
Class methods are like class variables in a number of ways:
•Class methods are declared with the static keyword.
•Class methods are invoked through the class rather than
through an instance.
•Class methods are the closest Java comes to "global"
methods. Because they must be referred to by the class
name, there is no danger of name conflicts.
•Class methods differ from instance methods in one
important way: they are not passed an implicit this
reference.
A Class Method and an Instance Method
public class Circle
{ public double x, y, r;
// An instance method. Returns the bigger of two circles.
public Circle bigger(Circle c)
{ if (c.r > r) return c;
else return this;
}
// A class method. Returns the bigger of two circles.
public static Circle bigger(Circle a, Circle b)
{ if (a.r > b.r) return a;
else return b;
}
. . // Other methods omitted here. . }
You would invoke the instance method like this:
Circle a = new Circle(2.0);
Circle b = new Circle(3.0);
Circle c = a.bigger(b); // or, b.bigger(a);
And you would invoke the class method like this:
Circle c = Circle.bigger(a,b);
Object Destruction
How do you destroy objects when they are no longer needed?
The answer is: You don't!
Garbage Collection
The technique Java uses to get rid of objects once they are no longer
needed is called garbage collection.
The Java interpreter knows what objects it has allocated.
It can figure out when an allocated object is no longer referred to by any
other object or variable. When it finds such an object, it knows that it can
destroy it safely, and does so.
The Java garbage collector runs as a low-priority thread, and does most
of its work when nothing else is going on.
The only time the garbage collector must run while something high-
priority is going on is when the interpreter has run out of memory.
Object Finalization
Just as a constructor method performs initialization for an
object, a Java finalizer method performs finalization for an
object.
Garbage collection automatically frees up the memory
resources used by objects.
But objects may hold other kinds of resources, such as file
descriptors or sockets, as well.
The garbage collector can't free these resources up for you, so
you should write a finalizer method that takes care of things
like closing open files, terminating network connections, and
so on.
A finalizer is an instance method (i.e., non-static),
takes no arguments, returns no value (i.e., void), and must be
named finalize().
Ex:
protected void finalize() throws IOException
{
……
}
There are some additional things to be aware of about
finalizers:
•If an object has a finalizer, that method is invoked before
the system garbage collects the object.
•The Java interpreter may exit without garbage collecting
all outstanding objects, so some finalizers may never be
invoked. In this case, though, any outstanding resources are
usually freed by the operating system.
•Java makes no guarantees about when garbage collection
will occur, or what order objects will be collected in.
Java access specifiers
The Java access specifiers public, protected and private are placed
in front of each definition for each member in your class, whether it’s a
data member or a method.
Each access specifier controls the access for only that particular
definition.
“Friendly”
The default access has no keyword, but it is commonly referred to as
“friendly.”
It means that all the other classes in the current package have access to
the friendly member, but to all the classes outside of this package the
member appears to be private.
Since a compilation unit – a file – can belong only to a single package,
all the classes within a single compilation unit are automatically friendly
with each other.
public:
When you use the public keyword, it means that the member
declaration that immediately follows public is available to everyone,
private:
The private keyword that means no one can access that member except
that particular class, inside methods of that class.
protected: “sort of friendly”
Can be accessed from subclass in different package
A class cannot be private or protected.
So you have only two choices for class access: “friendly” or public.
Class Member Accessibility
Accessible to: public protected package private
Same class yes yes yes yes
subClass in same yes yes yes no
package
Subclass in yes yes no no
different package
Non-subclass,
different package yes no no no
Examples on
Objects as arguments
Object Reference
String & StringBuffer class
Inheritance : Extending a Class
class A
{ int i; }
class B extends A // B is a subclass of A
{ int j; }
class I1{
public static void main(String args[])
{ B ob = new B();
ob.i=10;
ob.j=20;
System.out.println("ob's value =" + ob.i +"," + ob.j);
}}
class Rect { private int w,h;
void set(int x,int y)
{ w=x; h=y;
}
int area()
{ return w*h; }
void disp()
{
System.out.println("Width =" +w +", Height = " + h + "Area ="
+area());
}
}
Example 2
class Box extends Rect {
int d;
void set(int x,int y,int z)
{ set(x,y);
d=z;
}
void put()
{ disp();
System.out.println("Depth =" + d);
}
}
class I3
{
public static void main(String args[])
{
Box ob = new Box();
ob.set(10,20,15);
ob.put();
}
}
Constructor Chaining
class A
{ int i;
public A()
{ // Implicit call to super(); here.
i = 3; }
}
class B extends A
{
// Default constructor:
public B() { super(); }
}
More on super …
Shadowed Variables
class A { int x=10; }
class B extends A { int x=20; }
class C extends B { int x=30;
void disp()
{ // Variable x in class C.
System.out.println("x in C is :" + x);
// Variable x in class B.
System.out.println("x in B is :" + super.x);
System.out.println("x in B is :" + ((B)this).x);
// Variable x in class A.
System.out.println("x in A is :" + ((A)this).x);
public static void main(String args[])
{
C obj = new C();
obj.disp();
}
}
Overriding Is Not Shadowing
Method overriding is not like variable shadowing at all:
You can refer to shadowed variables simply by casting an object to the
appropriate type.
You cannot invoke overridden methods with this technique.
Method Overriding versus Variable Shadowing
class A {
int i = 1;
int f() { return i; }
}
class B extends A
{
int i = 2; // Shadows variable i in class A.
int f() { return -i; } // Overrides method f in class A.
}
public class override_test
{ public static void main(String args[]) {
B b = new B();
System.out.println(b.i); // Refers to B.i; prints 2.
System.out.println(b.f()); // Refers to B.f(); prints -2.
A a = (A) b; // Cast b to an instance of class A.
System.out.println(a.i); // Now refers to A.i; prints 1;
System.out.println(a.f()); // Still refers to B.f(); prints -2; } }
Core Java Basics
www.harshithatechnologies.com
info@harshithatechnologies.com
mhtspvtltd@gmail.com
040-42020378, 9989630313
Software Training || Consulting || OutSourcing

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Identifiers, keywords and types
Identifiers, keywords and typesIdentifiers, keywords and types
Identifiers, keywords and types
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Aspdot
AspdotAspdot
Aspdot
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
ScalaTrainings
ScalaTrainingsScalaTrainings
ScalaTrainings
 
Java
Java Java
Java
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)Under the hood of scala implicits (Scala eXchange 2014)
Under the hood of scala implicits (Scala eXchange 2014)
 
Dr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot netDr archana dhawan bajaj - c# dot net
Dr archana dhawan bajaj - c# dot net
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Java String
Java String Java String
Java String
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
 

Andere mochten auch

Andere mochten auch (20)

Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java basic
Java basicJava basic
Java basic
 
Intro to C++ Basic
Intro to C++ BasicIntro to C++ Basic
Intro to C++ Basic
 
Introduction to basics of java
Introduction to basics of javaIntroduction to basics of java
Introduction to basics of java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Course 3: OOP
Java Course 3: OOPJava Course 3: OOP
Java Course 3: OOP
 
PALASH SL GUPTA
PALASH SL GUPTAPALASH SL GUPTA
PALASH SL GUPTA
 
Java Course 2: Basics
Java Course 2: BasicsJava Course 2: Basics
Java Course 2: Basics
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Java basics
Java basicsJava basics
Java basics
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
2. Basics of Java
2. Basics of Java2. Basics of Java
2. Basics of Java
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 

Ähnlich wie Core Java Basics Guide

Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).pptAlok Kumar
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxchapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxnafsigenet
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfssusera0bb35
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training pptvibrantuser
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Courseparveen837153
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in javaShashwat Shriparv
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introductionchnrketan
 

Ähnlich wie Core Java Basics Guide (20)

Java unit i
Java unit iJava unit i
Java unit i
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxchapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Cpprm
CpprmCpprm
Cpprm
 
CSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdfCSharpCheatSheetV1.pdf
CSharpCheatSheetV1.pdf
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Online java training ppt
Online java training pptOnline java training ppt
Online java training ppt
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Fundamental programming structures in java
Fundamental programming structures in javaFundamental programming structures in java
Fundamental programming structures in java
 
C#
C#C#
C#
 
Java programing language unit 1 introduction
Java programing language unit 1 introductionJava programing language unit 1 introduction
Java programing language unit 1 introduction
 

Kürzlich hochgeladen

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Core Java Basics Guide

  • 3. Data Types Primitive Types Type Representation Range byte 8-bit, signed -128 to 127 short 16-bit, signed -32768 to 32767 int 32-bit, signed -2147483648 to 2147483647 long 64-bit, signed -9223372036854775808 to 9223372036854775807 char 16-bit, unsigned, Unicode float 32-bit 1.40239846e-45 to 3.40282347e+38 double 64-bit 4.94065645841246544e-324 to 1.79769313486231570e+308 boolean
  • 4. Java Operators Precedence Operator Description 1 ++, -- Increment and decrement 1 +, - Unary plus and minus 1 ~ Bitwise complement 1 ! Boolean 2 *, /, % Multiplication, division, remainder 3 +, - Addition and subtraction 3 + String 4 << Left shift 4 >> Right shift with sign extension 4 >>> Right shift with no extension
  • 5. 5 <, <=, >, >= Numeric comparison 5 instanceof Type comparison 6 ==, != Equality and inequality of value 6 ==, != Equality and inequality of reference 7 & Bitwise AND 8 ^ Bitwise XOR 9 | Bitwise OR 10 && Conditional AND 11 || Conditional OR 12 ?: Conditional ternary operator 13 = *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |= Assignment
  • 6. Keywords abstract default goto null synchronized boolean do if package this break double implements private throw byte else import protected throws case extends instanceof public transient catch false int return true char final interface short try class finally long static void const float native super volatile continue for new switch while
  • 7. Comments Java supports three styles of comments: •A standard C-style comment, where all of the characters between /* and */ are ignored. •A single-line comment, where all of the characters from // to the end of the line are ignored. •A documentation comment that begins with /** and ends with */.
  • 8. Literals Integer literals Integer literals can be specified in octal (base 8), decimal (base 10), or hexadecimal (base 16). int i = 1230; int i = 01230; // i = 664 decimal int i = 0xFFFF; Floating-point literals Floating-point literals are of type double unless they are suffixed with an f denoting that they are to be produced as a float value: double d = 8.31; double e = 3.00e+8; float f = 8.31F; float g = 3.00e+8F;
  • 9. Character literals A literal character value can be specified either as a single-quoted character or as an escaped ASCII or Unicode sequence: char a = 'a'; char newline = 'n'; char ch = 88 ; //code for X Boolean Literals It can have only one of two possible values, true or false boolean b = false;
  • 10. Type Conversion and Casting When one type of data is assigned to another type of variable, an automatic type conversion will take place if • The two types are compatible • The destination type is larger than the source type. Casting Incompatible Types To create a conversion between two incompatible types, you must use a cast. (target-type) value;
  • 11. Casting 1) int a; a = 10; byte b; b = (byte) a; 2) byte b; int i = 257; b = (byte) i; // 1 3) double d = 223.22; int i = (int) d; // 223
  • 12. Automatic Type Promotion in Expressions Java automatically promotes each byte type or short operand to int when evaluating an expression. byte b= 50; b = b * 2; // Error. Cannot assign an int to a byte b = (byte) (b*2); // valid
  • 13. Array Creation and Initialization As in C, array indices start with zero. After creation, the array elements are initialized to the default values for their type. For numeric types, this means the elements are initially zero: int [] grades = new int [30]; grades[0] = 99; grades[1] = 72; Java supports the C-style curly braces {} construct for creating an array and initializing its elements when it is declared: int [] primes = { 1, 2, 3, 5, 7, 7+4 }; An array object of the proper type and length is implicitly created.
  • 14. Comparing C++ and Java The important features that distinguish Java from C++. 1. The biggest potential stumbling block is speed: interpreted Java runs in the range of 20 times slower than C. 2. Everything must be in a class. There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class. 3. There are no structs or enumerations or unions, only classes. 4. All method definitions are defined in the body of the class. Thus, in C++ it would look like all the functions are inlined, but they’re not. 5. Class definitions are roughly the same form in Java as in C++, but there’s no closing semicolon. There are no class declarations of the form class foo; , only class definitions.
  • 15. 6. There’s no scope resolution operator :: in Java. 7. In addition, package names are established using the dot, and to perform a kind of C++ #include you use the import keyword. For example: import java.awt.*;. 8. Java, like C++, has primitive types for efficient access. All the primitive types have specified sizes that are machine independent for portability. 9. Type-checking and type requirements are much tighter in Java. For example: 1. Conditional expressions can be only boolean, not integral. 2. The result of an expression like X + Y must be used; 10. The char type uses the international 16-bit Unicode character set, so it can automatically represent most national characters.
  • 16. 11. Static quoted strings are automatically converted into String objects. There is no independent static character array string like there is in C and C++. 12. Java adds the triple right shift >>> to act as a “logical” right shift by inserting zeroes at the top end; 13. Although they look similar, arrays have a very different structure and behavior in Java than they do in C++. There’s a read-only length member that tells you how big the array is, and run-time checking throws an exception if you go out of bounds. All arrays are created on the heap, and you can assign one array to another (the array handle is simply copied). The array identifier is a an object 14. All objects of non-primitive types can be created only via new. There’s no equivalent to creating non-primitive objects “on the stack” as in C++.
  • 17. 15. All primitive types can be created only on the stack, without new. There are wrapper classes for all primitive classes so that you can create equivalent heap-based objects via new. 17. Java has no preprocessor. There are no preprocessor-like macros. 18. Initialization of class data members is guaranteed in Java; if you don’t explicitly initialize them they get a default value (a zero or equivalent). You can initialize them explicitly, either when you define them in the class or in the constructor. 19. There are no Java pointers in the sense of C and C++. 20. There are no destructors in Java. The lifetime of an object is determined instead by the garbage collector. There is a finalize( ) method that’s a member of each class, something like a C++ destructor, but finalize( ) is called by the garbage collector and is supposed to be responsible only for releasing "resources" (such as open files, sockets, ports, URLs, etc).
  • 18. 21. Java does not support default arguments. 22. Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object. In C++, you can start a new inheritance tree anywhere, so you end up with a forest of trees. In Java you get a single ultimate hierarchy. 23. Garbage collection means memory leaks are much harder to cause in Java, but not impossible. 24. No inline methods. The Java compiler might decide on its own to inline a method, but you don’t have much control over this. You can suggest inlining in Java by using the final keyword for a method. 25. Java has method overloading, but no operator overloading.
  • 19. Generally, Java is more robust, via: – Object handles initialized to null (a keyword) – Handles are always checked and exceptions are thrown for failures – All array accesses are checked for bounds violations – Automatic garbage collection prevents memory leaks – Clean, relatively fool-proof exception handling – Simple language support for multithreading – Bytecode verification of network applets
  • 20. HelloWorld.java public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } C:> javac HelloWorld.java //produces the HelloWorld.class C:> java HelloWorld //when you invoke the interpreter, you do not supply the .class extension
  • 21. System class has several fields, and if you select out you’ll discover that it’s a static PrintStream object. Since it’s static you don’t need to create anything. The out object is always there and you can just use it. println( ), method prints to the console and end with a new line.
  • 22. class P { public static void main(String args[]) { int x =34; int y =42; System.out.println("X = " + x); System.out.println("y = " + y); int z = x+y; System.out.println("z = " + z); } } All local variables has to be initialized before using.
  • 23. Arithmetic Operators and Logical Operators are same as that of C Programming Language.
  • 24. The Left Shift operator int i; byte a = 256,b; i = a<< 2; b = (byte) (a<<2); System.out.println(“ i and b : “ + i + “ “ + b); // i and b : 256 and 0 a is promoted to int for the purpose of evaluation, left shifting the value 64 twice results in I containing the value 256 0100 0000 0000 0001 0000 0000
  • 25. The Right Shift operator int a =32 ; a = a >> 1; // a now contains 16 int x = 35; x = x >> 2; // x contains 8 0010 0011 35 >>2 0000 1000 8 --------------------------------------------------- 11111000 -8 >>1 11111100 -4
  • 26. The Unsigned Right Shift operator >>> shifts zero’s into the high-order bit. int a = -1 ; a = a >>> 24; 11111111 11111111 11111111 11111111 // -1 in binary >>> 24 00000000 00000000 00000000 11111111 // 255 in binary
  • 27. Boolean Logical Operators & Logical AND | Logical OR ^ Logical XOR && Short- Circuit Logical AND || Short- Circuit Logical OR If you use the || and && forms rather than | and & forms , Java will not bother to evaluate the right hand operand when the outcome of the expression can be determined by the left operand alone. if( denom != 0 && num /denom >10) // if denom =0 short circuit if( c = =1 & e++ <100) d= 100; Single & ensures that the increment operation will be applied whether c is equal to 1 or not.
  • 28. Classes and Objects A Class is a template for an object, And an object is an instance of a class. These characteristics represent a pure approach to object-oriented programming: 1. Everything is an object. 2. A program is a bunch of objects telling each other what to do by sending messages. 3. All objects of a particular type can receive the same messages. 4. Tight Cohesion within an object and Loose coupling among objects.
  • 29. The Class of Circles public class Circle { public double x, y; // The coordinates of the center public double r; // The radius // Method that returns the area of the circle public double area( ) { return 3.14159 * r*r; } }
  • 30. Objects Are Instances of a Class We can declare variables of that type: Circle c; But this variable c is simply a name that refers to a circle object; it is not an object itself. In Java, all objects must be created dynamically. This is almost always done with the new keyword: c = new Circle(); Now we have created an instance of our Circle class--a circle object--and have assigned it to the variable c, which is of type Circle. Accessing Object Data c.x = 2.0; // Initialize our circle to have center (2, 2) and radius 1.0. c.y = 2.0; c.r = 1.0;
  • 31. Using Object Methods double a; a = c.area(); How can a method that takes no arguments know what data to operate on? In fact, the area() method does have an argument! area() is implemented with an implicit argument that is not shown in the method declaration. The implicit argument is named this, and refers to "this object"-- the Circle object through which the method is invoked. The implicit this argument is not shown in method signatures. We can use the this keyword explicitly.
  • 32. Constructor public class Circle { public double x, y, r; // The center and the radius of the circle // The constructor method. public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } ………… With this new constructor the initialization becomes part of the object creation step: Circle c = new Circle(1.414, -1.0,1 .25); There are two important notes about naming and declaring constructors: •The constructor name is always the same as the class name.
  • 33. Multiple Circle Constructors public class Circle { public double x, y, r; // Initializing constructors public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public Circle(double r) { x = 0.0; y = 0.0; this.r = r; } // Copy Constructor public Circle(Circle c) { x = c.x; y = c.y; r = c.r; } //Default Constructor public Circle() { x = 0.0; y = 0.0; r = 1.0; }
  • 34. this Again There is a specialized use of the this keyword that arises when a class has multiple constructors --it can be used from a constructor to invoke one of the other constructors of the same class. public Circle(double x, double y, double r) { this.x = x; this.y = y; this.r = r; } public Circle(double r) { this(0.0, 0.0, r); } public Circle(Circle c) { this(c.x, c.y, c.r); } public Circle() { this(0.0, 0.0, 1.0); } This would be a more impressive example, of course, if the first constructor that we were invoking did a more significant amount of initialization.
  • 35. Class Variables Java uses the static keyword to indicate that a particular variable is a class variable rather than an instance variable. That is, that there is only one copy of the variable, associated with the class, rather than many copies of the variable associated with each instance of the class. The one copy of the variable exists regardless of the number of instances of the class that are created--it exists and can be used even if the class is never actually instantiated. Static Variable Example public class Circle { static int num_circles = 0; // class variable: how many circles created public double x, y, r; // instance vars: the center and the radius public Circle(double x, double y, double r)
  • 36. Accessing Class Variables Because static variables are associated with the class rather than with an instance, we access them through the class rather than through the instance System.out.println("Number of circles created: " + Circle.num_circles);
  • 37. Constants: Another Class Variable Example When computing the area and circumference of circles, we use the value pi. Since we use the value frequently, we don't want to keep typing out 3.14159, so we'll define it as a class variable that has a convenient name: public class Circle { public static final double PI = 3.14159; public double x, y, r; // ... etc.... } Besides the static keyword that we've already seen, we use the final keyword, which means that this variable can never have its value changed.
  • 38. static Methods Class methods are like class variables in a number of ways: •Class methods are declared with the static keyword. •Class methods are invoked through the class rather than through an instance. •Class methods are the closest Java comes to "global" methods. Because they must be referred to by the class name, there is no danger of name conflicts. •Class methods differ from instance methods in one important way: they are not passed an implicit this reference.
  • 39. A Class Method and an Instance Method public class Circle { public double x, y, r; // An instance method. Returns the bigger of two circles. public Circle bigger(Circle c) { if (c.r > r) return c; else return this; } // A class method. Returns the bigger of two circles. public static Circle bigger(Circle a, Circle b) { if (a.r > b.r) return a; else return b; }
  • 40. . . // Other methods omitted here. . } You would invoke the instance method like this: Circle a = new Circle(2.0); Circle b = new Circle(3.0); Circle c = a.bigger(b); // or, b.bigger(a); And you would invoke the class method like this: Circle c = Circle.bigger(a,b);
  • 41. Object Destruction How do you destroy objects when they are no longer needed? The answer is: You don't! Garbage Collection The technique Java uses to get rid of objects once they are no longer needed is called garbage collection. The Java interpreter knows what objects it has allocated. It can figure out when an allocated object is no longer referred to by any other object or variable. When it finds such an object, it knows that it can destroy it safely, and does so. The Java garbage collector runs as a low-priority thread, and does most of its work when nothing else is going on. The only time the garbage collector must run while something high- priority is going on is when the interpreter has run out of memory.
  • 42. Object Finalization Just as a constructor method performs initialization for an object, a Java finalizer method performs finalization for an object. Garbage collection automatically frees up the memory resources used by objects. But objects may hold other kinds of resources, such as file descriptors or sockets, as well. The garbage collector can't free these resources up for you, so you should write a finalizer method that takes care of things like closing open files, terminating network connections, and so on.
  • 43. A finalizer is an instance method (i.e., non-static), takes no arguments, returns no value (i.e., void), and must be named finalize(). Ex: protected void finalize() throws IOException { …… }
  • 44. There are some additional things to be aware of about finalizers: •If an object has a finalizer, that method is invoked before the system garbage collects the object. •The Java interpreter may exit without garbage collecting all outstanding objects, so some finalizers may never be invoked. In this case, though, any outstanding resources are usually freed by the operating system. •Java makes no guarantees about when garbage collection will occur, or what order objects will be collected in.
  • 45. Java access specifiers The Java access specifiers public, protected and private are placed in front of each definition for each member in your class, whether it’s a data member or a method. Each access specifier controls the access for only that particular definition. “Friendly” The default access has no keyword, but it is commonly referred to as “friendly.” It means that all the other classes in the current package have access to the friendly member, but to all the classes outside of this package the member appears to be private. Since a compilation unit – a file – can belong only to a single package, all the classes within a single compilation unit are automatically friendly with each other.
  • 46. public: When you use the public keyword, it means that the member declaration that immediately follows public is available to everyone, private: The private keyword that means no one can access that member except that particular class, inside methods of that class. protected: “sort of friendly” Can be accessed from subclass in different package A class cannot be private or protected. So you have only two choices for class access: “friendly” or public.
  • 47. Class Member Accessibility Accessible to: public protected package private Same class yes yes yes yes subClass in same yes yes yes no package Subclass in yes yes no no different package Non-subclass, different package yes no no no
  • 48. Examples on Objects as arguments Object Reference String & StringBuffer class
  • 49. Inheritance : Extending a Class class A { int i; } class B extends A // B is a subclass of A { int j; } class I1{ public static void main(String args[]) { B ob = new B(); ob.i=10; ob.j=20; System.out.println("ob's value =" + ob.i +"," + ob.j); }}
  • 50. class Rect { private int w,h; void set(int x,int y) { w=x; h=y; } int area() { return w*h; } void disp() { System.out.println("Width =" +w +", Height = " + h + "Area =" +area()); } } Example 2
  • 51. class Box extends Rect { int d; void set(int x,int y,int z) { set(x,y); d=z; } void put() { disp(); System.out.println("Depth =" + d); } }
  • 52. class I3 { public static void main(String args[]) { Box ob = new Box(); ob.set(10,20,15); ob.put(); } }
  • 53. Constructor Chaining class A { int i; public A() { // Implicit call to super(); here. i = 3; } } class B extends A { // Default constructor: public B() { super(); } }
  • 55. Shadowed Variables class A { int x=10; } class B extends A { int x=20; } class C extends B { int x=30; void disp() { // Variable x in class C. System.out.println("x in C is :" + x); // Variable x in class B. System.out.println("x in B is :" + super.x); System.out.println("x in B is :" + ((B)this).x); // Variable x in class A. System.out.println("x in A is :" + ((A)this).x);
  • 56. public static void main(String args[]) { C obj = new C(); obj.disp(); } }
  • 57. Overriding Is Not Shadowing Method overriding is not like variable shadowing at all: You can refer to shadowed variables simply by casting an object to the appropriate type. You cannot invoke overridden methods with this technique. Method Overriding versus Variable Shadowing class A { int i = 1; int f() { return i; } }
  • 58. class B extends A { int i = 2; // Shadows variable i in class A. int f() { return -i; } // Overrides method f in class A. } public class override_test { public static void main(String args[]) { B b = new B(); System.out.println(b.i); // Refers to B.i; prints 2. System.out.println(b.f()); // Refers to B.f(); prints -2. A a = (A) b; // Cast b to an instance of class A. System.out.println(a.i); // Now refers to A.i; prints 1; System.out.println(a.f()); // Still refers to B.f(); prints -2; } }