Java Sonnet
Java is a software having three things,Language, virtual machine and API set.
In the software sky, flying with OOP wings
Creating magic all over the net.
James Gosling along with his colleagues wrote
This new language that he named it as 'OAK'
With fantastic concepts only to quote
naming it 'Java' for web to invoke.
From Java 1 to 8 ; many versions released
4500 pre-written classes already existing
Being open source everyone is pleased
It makes the approach easy for coding.
Java is surely the coding future,
Its going to stay for long; for ever.
Java JVM Sonnet
Java writes Machine independent code
That can run on different OS platforms
From one to other this technique flowed
And made java famous for coding norms
Firstly the code is written in plain text
That gets saved as a .java extension
Secondly compiler runs and see next
it returns .class ; its a compiled version.
This file has no code but bytecodes
That is difficult for machine to read
Thirdly it needs a JVM to decode the codes
Then java launcher tool displays the feed
JVM is ad hoc for Windows, Unix or Mac
where the same .class file runs without a crack
Polymorphism Sonnet
A person has many roles to play
He is a husband, brother and son too
Likewise the polymorphism concept blew
to let class in many ways to portray
The overloading method in a class
With vivid arguments and the same name
gives practical example of the same
The polymorphism makes this all to pass
The overriding method is where super -
And a subclass both can have same method
It shows how same arguments same method
Used in different places like trooper
Polymorphism makes the coding simpler
Its many examples shows its sprinkler
Java Objects Sonnet
Objects are key to understand ; infer
The Object Oriented technology
Look around and you'll find and discover
many cases of real-world thingy.
Like your dog, your desk, your TV or bicycle.
All have state and behavior icicle
Dogs have state like name, color, breed, hungry,
Behavior as barking and wagging tail
Tracing in real-world object sundry
Is great way to begin thinking OOP trail
"What viable states for an object can be?"
"What possible behaviors it can flex?"
some objects in turn have other objects
Real-world cases show the world of OOP
Java Buzzwords Sonnet
In the white paper that was written by,
two great ; James Gosling and Henry McGilton
Who explained buzzwords that are very nigh
To Java Language Environment one.
This is great Java programming language
That's high-level language for all to use
This has been characterized and to gauge
with many wonderful names and buzzwords
Its Simple, Robust , Object oriented,
Architecture neutral, Portable with
Secure, Dynamic, and Distributed,
High performance, Multithreaded -- a pith
These buzzwords describe this language Java
Bringing flavor of Java's Baklava
Java Coding Sonnet
Java can help us in following ways
While we write the programs in this language
To write better programs in our voyage
With very less effort; efficient ways
Getting started quickly than native C++ and C
Writing lesser ; better code with API
Writing once running anywhere thereby
Coding with platform Independency
You can develop the code twice faster
Than other languages of programming
It too helps vividly to reuse coding
By using many OOP concepts; ever
Finally deploying and distributing
Also is very simple in dealing
Java Features Sonnet
The high-level Java language program
Is very powerful software platform.
Full implementation of this Platform
It gives us many features to perform
First the development tools like javac -
to compile, java launcher to run -
monitor, debug, javadoc is key
for documenting the application.
The API provides classes like GUI, Swing
Networking, Remote-MI, XML generation
And JDBC, Java FX, Java IDL API, having
JNDI - all this is for easy creation
Deployment by ;Java Web Start software
For end users - Java Plug-In software
Java Class Sonnet
In this world we see same kind of objects
With the same make and also same model
Thousands of objects made from single specs
Blue print with same components sans dawdle
The syntax of the Java programming
Will certainly look new and different;
But the design of the class is saying
Objects are created - vociferant
The fields examples cadence, speed, and gear
All represent the bicycles state, and -
Methods like changeCadence, changeGear
Is interaction with the outside world.
A class therefore also called a blueprint
From which Its many objects you can mint
Inheritance Sonnet
Different kinds of objects have often
Amongst each other some things in common
Like a tree of family called Dhava
That is called Inheritance in Java
The Mountain and road and tandem bikes,
All share characteristics of bikes
Yet each define additional feature
that makes them different from each other
Bicycle now becomes the superclass
of MountainBike, RoadBike, and TandemBike.
Java's single Inheritance ; each class -
Is allowed only one superclass ; bike
But each superclass has the potential -
For unlimited list of subclass tail
Interface Sonnet
The Interaction with the outside world
Are the Objects, through their written methods -
That they are exposed with - and these methods
Form object's interface with outside world;
Like buttons of your television set
Are interface between you and wiring
on the other side of plastic casing.
Press "power" button to on - off your set
Interface is more formal behavior,
Interfaces form a contract with class -
and outside world, while build by compiler.
All methods ;must for compile to pass
To implement interface and to use
the implements keyword you should induce
Packages Sonnet
A package is namespace and folder
having same classes and interfaces.
like HTML in one; for images another,
apps in other; other folder for scripts.
Software written in the Java thereby
Composed of many different classes,
it helps to organized in packages.
This library also known as API
Packages solves tasks ; file object ; like
Modify file system - with object dike
The classes allows to focus design
Rather than the infrastructure spine
As programmer, API will be single -
reference doc of Java; us to mingle
Variables Sonnet
There are different kinds of Variables
Instance, class , local and parameters
Each one has a different role to play
We will see each one in a detailed way
Instance Variables the Non-Static Fields
Objects store their unique states into that,
Class Variables called the Static Fields
With static word; only one copy of that
Local Variables will often store its
Temporary state - local variables.
Syntax stating local variable
is similar to stating field label
Parameters are method arguments
Like args in public static void main(String[] args).
Naming Sonnet
Every language of program has its own
Defined set of rules and the convention
Kinds of names used for utilization
The Java language is not left alone.
The rules for naming the variables are -
Names are always in case-sensitive mode,
A name can be legal identifier —
Unlimited-length sequence - Unicode -
Letters, digits, beginning with letter -
Dollar sign or underscore character.
But per convention begin with letter
Auto-generated may have dollar char
Finally White space is not permitted.
These are naming conventions accepted.
Naming Continued Sonnet
Subsequent characters may be letters
Or digits, dollar signs, or underscore.
When choosing a name for your variables,
Use full words instead of abbreviations.
Doing so will make your code easier
to read , understand and to use better
while documenting; fields like cadence, speed,
Are more logical than c , s abbreviated ,
The name mustn't be keyword or reserved word.
If name is one word, start with lowercase
Caps the first letter if more than one word,
like the gearRatio and currentGear names
Constant value is caps every letter
along with the underscore character
Primitive Data Types Sonnet
Let us now move and get on to the trip
To see primitive data types world
Primitive type is predefined to grip
This type is named by a reserved keyword
There are eight primitive types supported
They are the - byte, short, int, long,float, double,
boolean, char - and in that String is added
For String object, that are immutable
Every data type has default value
Its not needed to assign a value
accordingly the datatype is set
Either zero or null value to let
This is the magic of primitive type
In a great way it helps without a gripe
Literals Sonnet
The "new" isn't used while Initializing
A variable of primitive type
Primitive types are special data type;
they are not objects ; class is creating.
A literal represents fixed value;
literals don't require computation.
It can assign literal dimension
To variable of primitive type.
Yes, there are different literals like
Integer and floating point Literals
And Character and the String Literals
To use them in program and take a pike
From Java 7 onwards its allowed to use
Underscore to help the code to conduce
Array Sonnet
An array is a container object
Fixed number of one type of value ranges
The length of it when created is set
And then array value never changes
Each item in array is element
Numeric index is given to it
It starts with zero of each element
The 9th element, would be at index eighth.
But in the real-world situation,
You would use one of the looping program
To iterate through each one to action
Rather than writing each line one by one
The loops can be for , while and or do-while
This will help us to use arrays in style
Array Declaring Sonnet
The way; declaring other variables;
Array declaration too has two parts:
The array's name and also array's type
An array's type is written as this type[],
data type of elements is the type;
Brackets are the symbols showing array.
The size of array is not part of type
that's why brackets are empty in the way
An array's name can be by anything
As per rules in the section of naming
As with variables of other types this,
Declaration does not create array;
it simply tells the compiler that this
Variable will only hold array.
Array Accessing Sonnet
There is one way to create an array
It is to use the "new" operator.
If this statement is not written this way
then the compilation fails with error
Then assign values to the array's
Elements by numerical Index
Else by using the shortcut syntax
to create and initialize an array
The length of the array is determined
by the number of values provided
You can declare an array of arrays
by using two or more sets of brackets
Multidimensional array is array
whose components itself is an array
Copying Arrays Sonnet
The System class has important method
"arraycopy" can be directly used
Efficiently to copy one array's
Data into another new array
The two Object arguments specify
Array to copy from and copy to
Three integer arguments specify
the starting position in the source clue
the start point in destination array,
and number of elements to copy.
Following is statement, arraycopy
(Object src, for source;int srcPos the source point
Object dest, int destPos, for destination
int length) for total numbers to copy
Array Manipulations Sonnet
Arrays are a powerful and useful -
Concept in programming are museful -
Has methods for array manipulation
Like "arraycopy" copies one array
Elements in to another array
This is done "behind the scenes" action
"java.util.Arrays" class, many methods
Like "copyOfRange" , "arraycopy" feathers
"Searching" array for specific value
To get index at which it is searching.
checking the two arrays and their value
if equal or not method "comparing"
"Filling" an array ; "sorting" an array
forming a "stream" ;and "tostring" from array
Operators Sonnet
Operators are the special symbols
That perform specific operations
On one or two or three operands
And then they finally return results
Operators are evaluated firstly
that are having higher precedence
then operators with lower precedence.
same line enjoy equal priority
Same priority ops in same expression,
Rule is to govern to evaluate this one
Binary operators from left to right;
assignment operators are right to left.
Most common is assignment operator "="
Than the unsigned right shift operator ">>>".
ESB Sonnet
With variables and the operators
we can form expressions, statements, and blocks.
Operators can form expressions and
Calculate ; compute the values to send.
Expressions are very core components
of all written and created statements;
Statements that relate to another one
Usually grouped into blocks as one
Expressions may contain variables With -
assignment operators to assign
The values to that variables - forthwith
to use it later in our program line
So all the expressions, statements, and blocks
And with all these three things our Java walks
Expression Sonnet
An expression is a construct made of
variables, operators like a glove
Method invocations, made according
To syntax of Java language coding.
The expression when its formed finally
Evaluates to single val duly
The data type of the value returned
by an expression depends on concerned
Elements that used in the expressions.
The Java programming language allows
You to construct the compound expressions
As long as the data type matches bows
Expression behaves by parenthesis
Else is determined by the precedence
Statements Sonnet
Statements are like English sentences made;
A statement is unit of execution.
All the statements can be terminated
With expression of a semicolon (;).
Assignment , increment, and Method calls
Object creation are expression statements
And two other kinds of more statements:
declaration and control flow statements.
A declaration statement declares
Variable like string="Java Nation"
And finally its control flow statements
regulating order of execution
These statements help us to create logics
And create our Java programs to fix.
Blocks Sonnet
A block is group of multiple statements
Can be zero too; in balanced braces
And can be used anywhere in program
where with a single statement it can jam
One class , one method or one condition
All this can be classified as one block
Specific logic should be in fusion
To complete the one particular block.
Like - the if condition that is one block
else condition forms the another one
For loop created makes up other block
and one method - its a more enclosed one
Sometimes the entire class can be a block
That can be called in another class block
Control Flow Sonnet
The statements in source files go line by line -
And mostly goes from top to down like pine
The Control flow statements, they however,
break up flow of execution going
by using decision making, looping
Branching, enabling program used ever
Conditionally execute proper
Blocks of codes that are to particular
now let's see decision-making statements
Like if-then ; if-then-else and switch keywords
And three most important looping statements
for loop and while loop and do-while loop verbs
Branching statements - break and continue and -
Return ; supported by Java lang hand.
Declaring Classes Sonnet
class Person { } is a class declaration
The entire class body is area
between the braces { } contains all action
Provides the life cycle of aquaria
Of objects that are created from class:
The constructors for "init" the new objects,
declarations for the fields that render
state of the class and also its objects,
and methods to implement behavior
Of the class and also all their objects.
You can add the modifiers like public
Or private at the very start of class
You would use the extends and implements
Based on interface or super-class you pick
Declaring Variables Sonnet
Member variables - called fields; Variables
in method or block - local variables.
Method declarations - parameters.
The field's type; name; no or more modifiers;
There are public and private modifiers
For encapsulation, it's private class
Means only directly accessed from class.
We still need access to all these values
It's done indirectly by public methods
All the variables should have a type.
The primitive types or reference types
All variables, follow same naming rules
The first letter of class - capitalized
The first word in a method - verbified
Defining Methods Sonnet
Elements of method declaration -
are the method's return type, method's name,
Along with a pair of parentheses, (),
Finally a body between braces, {}.
Method declaration - six components
Modifiers— public, private, and others
Return type or void; basis val to return
The method name—according to the rules
The param list in brackets() or empty
An exception list will discuss later
The method body, enclosed in braces
The method's code, with variables, goes here.
Method signature made up of two thing
The method's name and parameter types.
Naming Methods Sonnet
Method name is legal identifier,
The code conventions restrict method names.
By convention, method names are verb-ier
In the lowercase or multi-word names
It begins with a verb in lowercase,
followed by the adjectives, and nouns
In multi-word names, the first letter face
of the second and next words should be caps
like runFast; getNum; getFinalData;
run; closeTo;setX; isEmptyData;
A method always has a unique name -
within its class. Yet many method names
might also consists of same name - owing
To implementing method overloading
Overloading Methods Sonnet
Java supports overloading methods,
and It can distinguish between methods
with different method signatures.
This means that the methods within a class
Be same name with other parameters
If there is a calligraphy draw class
To draw strings, integers; contains method
for drawing each data type is clumsy
This class might declare -named draw - four methods,
each with distinct parameter list duly
Methods with same arguments, throws error
With different return type - throws error
Overloaded methods - use sparingly,
It has code much less readability
Constructors Sonnet
Class has constructors that are evoked in;
To create objects from the class blueprint.
Constructor declarations just look like -
method declarations except they use
the name of the class and no return type.
Example, Bicycle has one constructor:
Create new Bicycle object - myBike,
Constructor is called by new operator:
Bicycle myBike = new Bicycle(30, 0, 8);
Above creates space in memory in use
Object and initializes fields infact;
Although Bicycle has one constructor,
it can have no-argument constructor:
Both constructors declared this way like
Constructors Continued Sonnet
As with the methods, the Java platform
differentiates constructors on the firm
basis of the number of arguments
In the list and in different types.
In Java you cant write two constructors
with same number; type of arguments tone
for the same class, because the platform is
Not able to tell error will be thrown
You don't need provide any constructors;
but you must be careful when doing this.
The compiler does this by no-argument
default constructor if none in the class
This default will call the no-argument
constructor of the above superclass.
Constructor 03 Sonnet
Continuing the constructor-02 Sonnet
Superclass constructor situation
if superclass has a no-argument
constructor; The compiler will complain
so you must first verify that it does.
If class has no explicit superclass,
then implicit superclass of Object,
That has a no-argument constructor.
You can use a superclass constructor
The MountainBike class has used that object
Use access modifiers - curb constructor
Cant call constructor - cant make objects
To understand this properly and fine
Read all three constructors sonnets in line
Passing Information Sonnet
For declaring method or constructor
We need number and type of arguments
Example, method that computes for
The monthly payments for the home loan,
based on amount of loan, interest rates,
length of the loan ;future value of loan:
It has four parameters: loan amount,
Int rate, future val and periods numbers
First three are double or floating numbers,
Fourth is integer . - The parameters
Used in method body and runtime count
will take on - pass values of arguments
Parameters are list; Arguments values
Passed when method's invoked, it should match hues
Parameter Types
You can use any of data type for -
Parameter of method / constructor.
This includes the primitive data types,
Such as the doubles, floats, and integers,
Here's an example of a method that
accepts an array as an argument.
In this example, the method creates -
New Polygon object - initiates boom
From an array of Point objects assume
that Point is a class that it represents
x, y coordinate like public Polygon -
polygonFrom(Point[] corners) {} - is drawn.
Note: To pass a method in method thence
Use lambda expr or method reference.
Arbitrary Number of Arguments Sonnet
You can use a construct called "varargs" to -
pass arbitrary number of vals to -
method. "varargs" is used when we dont know
how many same type of argument will
be passed to the method. to make it dill
Shortcut to create array manually though
In method we could have used in a way
varargs rather than create an array.
To use varargs, follow type ellipsis way
then a space, and the parameter name.
Method called with any params or none
In method, corners treated like array.
The method can be called with an array
Code will treat parameter as array.
Object Concepts Sonnet
Java program creates many objects,
That interact by invoking methods.
And Through all these object interactions,
Program can carry out various tasks,
such as implementing a GUI, running
an animation, or send - receiving
Of information over a network.
Once an object has completed the work
for which it's created, its resources
are recycled for use by other objects.
Learn how to write the code that creates and
uses these objects in its own programs.
how the system then cleans up after an
object's life in the specific place ends.
Creating Objects Sonnet
A class provides the blueprint for objects
Create object from class definition
Each has three parts to it - Declaration;
Instantiation; Initialization
Declaration sets var to declare and
Link var name with object type like guava
Instantiation: "new" keyword in Java
The Operator creates the object.
Initializing the constructor band
which initializes the new object.
A primitive var reserves memory
"new" operator instantiates the deck
and invokes constructor "emery"
"instantiating class" is "creating object."
Using Objects Sonnet
Once that you have created an object,
then you will have to use that for something.
You may need to use field's value aspect
Or change one of field values for using
or calling one of the objects method
to perform an action and get a nod
The Object fields are accessed by their names.
You must use the name that's unambiguous.
And code outside the object's class can use
an object with dot and a simple name
To access field use return reference
New operator returns and will yield
To an object; you could use the value
returned from new to access a new field
Calling Methods Sonnet
Use an object reference to invoke -
An object's method - append the method's
simple name to the object reference,
with our common dot operator (.) folk;
Within parentheses, any arguments
No arguments, empty parentheses.
As with instance fields, objectReference
must be reference to an object ; pods
Variable name, but also expression
that too returns an object reference.
new oper returns object reference,
To invoke a new object's methods:
Invoking method on specific object
is same - sending message to that object.
The Garbage Collector Sonnet
Some OO languages need to track objects -
Create ; explicitly kill when never -
needed. Coping the memory ever
Explicitly Error- Prone - Tedious ;
It allows ; create as many objects
limited, by system can handle them
and don't worry about destroying them.
JRE is capable of deleting objects
when it's no longer being used- action
This process is called garbage collection.
Or explicitly drop all reference
by setting 'null' to the variable
GC periodically frees the memory
GC does when time is right absolutely
Returning a Value/Class/Interface from a Method Sonnet
Method returns to code that invoked it
when it completes all written statements
in the method, reaches return statement
Or throws exception whichever comes first.
Return type in method declaration
Use return statement to return value.
No value return - void declaration
The data type must match return value
When the method uses name of a class
Return type should be the class or subclass
Override method - return subclass stripe
Technique called covariant return type
Note: interface names as return types.
Object returned must implement interface.
Java "This" Sonnet
Within instance method or constructor,
'this' is reference to current object —
the object whose method or constructor
is called; refer any member by "this" - sect
'this' keyword is used for field is shadowed for
by method - constructor. Each argument
shadows one fields — inside the constructor
A copy of constructor's argument.
From constructor, you can use 'this' to call
other constructor in same class ; in all
Called explicit constructor invocation.
Check example in objects section
Invocation of another constructor
must be the first line in the constructor.
Access Modifiers Sonnet
Yes to all ; Yes to World is public mode
Yes to all ; No to world - protected code
Yes to class ; yes to package is default
Yes to class ; No to others - private road
If other programmers use your classes,
Ensure errors from misuse don't occur
Use Private access modifier Unless
you have very good reason not to blur
Avoid public fields except constants; for
They tend to link you to particular
Implementation and to limit your
flexibility in code to alter
Following above are tips to use them
Use it wisely for Java to muse them
Static Variables Sonnet
The static keyword creates fields - methods
Belonging to class, not instance of class.
Objects created from same class blueprint,
Instance vars has memory that's distinct
But some vars are common to all objects.
This is achieved by static modifier.
Any object can change value of this var
But these static variables can be changed
without creating an instance of class.
ex. numberOfBicycles created
Java also supports static methods
Like it supports static variables gauge.
Let us see how these static methods
In next ; supported by Java Language
Static Methods Sonnet
Static methods, with static modifier -
Are invoked with the class name and without
creating any instance of the class
Some combinations of instance and class
variables and methods are too allowed:
Instance methods can read instance and class
variables & instance methods directly.
The class methods can only access class -
variables and class methods directly.
The class methods cannot access instance -
variables-methods directly but require —
To use for these - an object reference.
Class methods cannot use the 'this' keyword;
There's no instance for this to be referred.
Constants Sonnet
Static modifier, with final modifier,
Is also used to define the constants.
Constants in this way can't be reassigned as,
It will throw the compile-time error
By convention, the names of constant are
spelled in uppercase letters. If names are
Having more than one word, then the words are
separated by underscore letter (_).
If primitive type or string as constant
And value is known at compile time,
Compiler replaces name of constant
everywhere in the code with its value.
If constant in the outside world changes
recompile classes ; using its values
Initializing Fields Sonnet
We can give Initial value for the
field in declaration and this works fine
when we have the 'init' value and then the
initialization can be one line.
This form of initialization has
limitations due to simplicity.
If the "init" needs some logic ; like in case
Error handling or for ability
Of the loop to fill a complex array,
simple assignment impossible that way.
Instance vars initialized in constructors,
where exceptions ; other logics be used.
Its only that they be declared like czars
and initialized before they are used.
Static Initialization Blocks Sonnet
A static initialization block
is a normal block of code in braces, { },
Preceding by the static keyword lock
Here is an example for the same case
There can be in class as many number;
Of the static "init" blocks, and anywhere
In the entire class they can all appear
The runtime guarantees static "init" blocks
are called in the order that they appear .
There is an alternative to static blocks —
you can write a private static method:
Advantage of private static methods
is that they can always be reused later
And reinitialize the class var ever
No comments:
Post a Comment