8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
1/34
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
2/34
Java
The Fast Way
The Ultimate, Quick and Easy
Java Programming Guide
Eng. Alexander Mosgov
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
3/34
Chapter 1:
Data Typesva provides a rich set of data types. Every variable declared or defined has a particular data
e assigned data type specifies the size and the type of values that a variable can store.
ovides a number of data types which have their particular significant in deciding the approp
e by the programmer while programming.
ere are mainly two basic types of data types:
Primitive
Non- primitive
imitive data types
mitive data types are also known as built-In data types. These data types are predefined b
guage. Java provides the following primitive data types in Java :
te
8 bit signed integer
Rang e is -128 to 127
Used in arrays w
memory significantly matters.
Integer Data type are 32 bit signed integer
Minimum value is - 2,147,483,648.(-2^31) and Maximum value is 2,147,483,647
Default value is zero.
ort
16 bit signed integer
Range -32,768 to 32,767
Used in larger arrays to save memory space
ng
64 bit signed integer
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
4/34
Minimum value is -9,223,372,036,854,775,808 and Maximum value
9,223,372,036,854,775,807
This data type is used if there is a need of higher range than Int.
Default value for Long data type is 0L
oat
Single precision 32bit IEEE 754 floating point.
Float is used to deal with larger array of floating point numbers to sav
memory.
Default value for Float data type is 0.0f.
ubleDouble precision 64 bit IEEE 754 floating point.
Default data type / choice for decimal values
Default value for Double data type is 0.0d.
olean
Boolean data types represent 1 bit information
There are only two possible values for Boolean data types i.e true and false
Boolean data types are mainly used in condition checking.
Default value for Boolean data type is false.
arSingle 16 bit Unicode Character
Range is '\u0000' - '\uffff'
Used to store a character
Range
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
5/34
ta Type
Size Default Value
32-bit 0 -2,147,483,648 to 2,147,483,647
ort 16-bit 0 -32,768 to 32,767
ng 64-bit 0L -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
te 8-bit 0 -128 to 127
at 32-bit 0.0f 1.40129846432481707e-45 to 3.40282346638528860e+38
uble 64-bit 0.0d 4.94065645841246544e-324d to
1.79769313486231570e+308d
ar 16-bit '\u0000' 0 to 65,535
olean 1-bit False True or False only
on-Primitive data types
n-primitive data types are not predefined data type in any programming language. They are cr
the programmer for their use and efficiency of a program. These variables are also know
erence variables.
n-primitive data types in Java include Arrays, Interfaces and class.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
6/34
Chapter 2:
Operators and Expressionsva is a very rich language in terms of operators it has. Java operators can be classified int
lowing categories:
Arithmetic Operator Relational operator
Logical operator
Assignment operator
Increment-decrement operator
Conditional operator
Bitwise operator
Other special operators
rithmetic operators
ese operators are used in constructing mathematical expressions. Java provides all the com
thmetic operators used algebra including +,-,/,*,% . All these operators have the
nctionalities as in other languages.
perator Meaning
Unary plus or addition operator
Unary minus or subtractionoperator
Division operator
Multiplication
Modulo Division (Remainder
Operator)
me example of arithmetic operators are as shown below:
q P-q p*q p/q p%q -p/q
the above given examples, p and q are known as operands and these p and q can be variab
nstants.
eger arithmetic
hen all the operands in the expression are integers then the expression is known as in
pression and the operations in this expression are known as integer arithmetic. The output
eger arithmetic is always an integer value. For the above given example in Arithmetic opera
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
7/34
we take p=14 and q=4,
+ q=18
q =10
q= 56
q = 3
% q=2
l the results are very easy to understand except / and %.
we know an integer expression results in an integer, therefore results of p/q is 3 where de
rt is truncated. Also modulo operator results in remainder thus provides 2 as result.
case of Modulo division operator , the sign assigned to result is the sign of the first operan
vidend.
%4 =2
%-4=2
8%4=-2
8%-4= -2
al Arithmetic
real arithmetic involves real operands. In real arithmetic, operands are either in expontation or decimal notation. As we know, in floating point, values are rounded-off to the perm
mbers of digits.
xed Mode arithmetic
expression having operands of both types as integers and real is known as mixed mode arith
pression. If one operand is real and other is integer then the integer operator is itself convert
l and after conversion, real arithmetic is performed.
. 25/10.0= 2.5 whereas 25/10 produces 2.
elational Operator
hen there is a need to compare two quantities, relational operators are used. An expression
q or p>=30 having a relational is known as relational expression. The output of a relat
pression is either TRUE or FALSE. There are 6 relational operators in Java which are given i
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
8/34
lowing table.
perator Meaning
= Is equal to
= Not equal to
Less than
= Less than or equal to
Greater than
= Greater than or equal to
ample to demonstrate the relational operators:
blic class Test {
blic static void main(String args[]) {
int p = 10;
int q = 20;
System. out. println ("p == q = " + (p == q) );
System.out.println ("p != q = " + (p != q) );
System.out.println ("p > q = " + (p > q) );
System.out.println ("p < q = " + (p < q) );
System.out.println ("q >= p = " + (q >= p) );
System.out.println ("q
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
9/34
ntrol in a program.
ogical Operators
ere are three logical operators in Java. These operators are logical AND, logical OR and lo
OT. The logical operators logical AND ,logical OR are used when there is a need to fo
mpound condition with a combination of two or more relational expressions.
perator Meaning and Description
&
This operator is known as Logical AND
operator. When both operand are true or
non-zero, then the condition is true
otherwise false
This operator is known as Logical OR
operator. When at least one operand is
true or non-zero, then the condition is true
otherwise false
This operator is known as Logical NOT
operator and Used to reverse the logical
state of any operand. If a condition is false
then this operator will make it true and if
true then it will make false.
signment Operator
signment operators come in existence when there is a need of assigning value of a spec
pression to a given variable.
tead of assignment operator, java also provides shorthand assignment operators with the follo
ntax:riable operator = expression;
e above expression is equivalent to variable=variable operator (expression)
orthand Assignment Operator
tatement with simple assignment
perator
Corresponding statements with
shorthand operator =p+1 P+=1
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
10/34
=p-1 p-=1
=p*(n+1) P*=n+1
=p/(n+1) p/=n+1
=p%q P%=q
blic class Demo1
public static void main(String args[])
{
t value = 10;
System. out .println( "value is " +value);
// Shorthand assignment operators
int a1 = 4;
int a2 = 8;
a2 += a1;
System. out .println( "a1 is " +a1);
System. out .println( "a2 is " +a2);
a1 = 4;
a2 = 8;
a2 -= a1;
System. out .println( "a1 is " +a1);
System. out .println( "a2 is " +a2);
a1 = 4;
a2 = 8;
a2 *= a1;
System. out .println( "a1 is " +a1);
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
11/34
System. out .println( "a2 is " +a2);
System. out .println( "********** /= Assignment Operator*********" );
a1 = 4;
a2 = 8;
a2 /= a1;System. out .println( "a1 is " +a1);
System. out .println( "a2 is " +a2);
a1 = 4;
a2 = 8;
a2 %= a1;
System. out .println( "a1 is " +a1);
System. out .println( "a2 is " +a2);
}
ue is 10
is 4
is 12
is 4
is 4
is 4
is 32
is 4
is 2
is 4
is 0
ncrement and Decrement Operator
va provides two very important operators i.e increment and decrement operators having synta
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
12/34
d – respectively.
hese operators are specific types of assignment operators with following features
Unary operators working with a single operand.
Increment operator increases the value of the operator to which it is
applied by 1
Decrement operator decreases the value of the operator to which it is
applied by 1
here are two versions of these operators:
Preincrement and predecrement operator
Postincrement and postdecrement operator
e-increment operator
Preincrement operator “++” is applied to a Variable by writing it
before the variable’s name. Preincrement operator firstly increases the value of variable by 1 a
then that incremented value is used in that expression.
We can’t apply this operator with final variables or constants.
Pre- decrement Operator
Predecrement operator “--” is applied to a Variable by writing it
before the vatiable’s name. Predecrement operator firstly decreases the value of variable by 1
then that decremented value is used in that expression.
We can’t apply this operator with final variables or constants.
ost-increment operator
Postincrement operator “++” is applied to a Variable by writing it
the variable’s name. Postincremnt operator firstly use the same non-incremented value
that expression and after that increases that variable by 1.
We can’t apply this operator with final variables or constants.
ost- decrement Operator
Postdecrement operator “--” is applied to a Variable by writing it a
the vatiable’s name.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
13/34
Postdecrement operator firstly use the same non-decremented valu
that expression and after that decreases that variable by 1.
We can’t apply this operator with final variables or constants.
xample:
ass Increment {public static void main (String args[]) {
int p = 1;
int q = 2;
int r;
int s;
r = ++q;
s =p++;
r++;System.out.println(“p = “ + p);
System.out.println(“q= “ + q);
System.out.println(“r = “ + r);
System.out.println(“s = “ +s);
}
he output of this program follows:
p = 2
q = 3
r= 4
s = 1
you are well understood with the above program,, then you please try decremenerator yourself. It works in the same way as increment with a single difference t
decreases value by 1 instead of increasing.
onditional Operatorrnary operator is a very important conditional operator provided by Java. It has the conditiona
tements of following form:
pression 1 ? expression 2 : expression 3
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
14/34
the above conditional statement, firstly expression 1 is calculated and the result of the conditio
pression depends on its result whether it is true or false.
expression 1 is true then expression 2 is evaluated and it becomes the resultant or final value o
ove given conditional statement.
expression 1 is false then expression 3 is evaluated and it becomes the resultant or final value
above given conditional statement. Always remember, only one of the both expression 2 and
pression 3 is calculated depending of expression1’s result.
= 10;
= 15;
( p > q ) ? p : q ;
the above given example, r is assigned the same value as q.
is operator behaves same as if-else. Above program in if-else
p>q)
r=p;
eq;
itwise operators
va provides a rich set of bitwise operators which operate on individual bits of an integer. In c
erand is shorter than int then before applying bitwise operations that is converted into int. The
erators can’t be applied to double or float.
stly an integer is represented in binary form and after that bitwise operators are applied on the
dividual bits of the binary forms of the corresponding operands. For example 6 is represented
nary as 110 . 2’s complement is used for storing negative numbers.
blic class Bitwise {
ublic static void main(String args[]) {
int p = 60; /* Binary representation 60 = 0011 1100 */int q = 13; /* Binary representation 13 = 0000 1101 */
int r = 0;
r = p & q; /* Binary representation 12 = 0000 1100 */
System.out.println("p & q = " + r );
r = p | q; /* Binary representation 61 = 0011 1101 */
System.out.println("p | q = " + r );
r = p ^ q; /* Binary representation 49 = 0011 0001 */
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
15/34
System.out.println("p ^ q = " + r );
r = ~p; /* Binary representation -61 = 1100 0011 */
System.out.println("~p = " + r );
r = p > 2; /* Binary representation 15 = 1111 */System.out.println("p >> 2 = " + r );
r = p >>> 2; /* Binary representation 15 = 0000 1111 */
System.out.println("p >>> 2 = " + r );
is would produce the following result:
& q = 12
q = 61q = 49
= -61
> 15
>>> 15
perators Precedence and Associativityery operator has a precedence and associativity associated with it. Precedence of operators is
determining the sequence of operators for evaluating an expression in case expression has a
mber of operators. In an expression, the operators having higher precedence are evaluated firs
sociativity is the concept for determining the evaluation order of operators when there are mu
erators with same precedence then associative determines either to be evaluated from left to ri
right to left.
ecedence withRank
Operator Type Associativity
1
()
[]
·
Parentheses
Array subscript
Member selection
Left to Right
2++
--
Unary post-increment
Unary post-decrementRight to left
++
--
Unary pre-increment
Unary pre-decrementUnary plus
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
16/34
3+
-
!
~
( type )
Unary minus
Unary logical negation
Unary bitwise
complement
Unary type cast
Right to left
4
*
/
%
Multiplication
Division
Modulus
Left to right
5+-
AdditionSubtraction
Left to right
6
>
>>>
Bitwise left shift
Bitwise right shift with
sign extension
Bitwise right shift with
zero extension
Left to right
7
<
>=
instanceof
Relational less than
Relational less than or equal
Relational greater than
Relational greater than
or equal
Type comparison
(objects only)
Left to right
8==
!=
Relational is equal to
Relational is not equal
to
Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise exclusive OR Left to right
11 | Bitwise inclusive OR Left to right
12 && Logical AND Left to right
13 || Logical OR Left to right
14 ? : Ternary conditional Right to left
15
=
+=
-=
*=
/=
%=
AssignmentAddition assignment
Subtraction assignment
Multiplication
assignment
Division assignment
Modulus assignment
Right to left
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
17/34
Chapter 3:
Decision Making Statements in Javametimes there is a need to take decisions on the basis of given condition. Based on the
nditions, it is the decided that which condition is satisfied and statements correspondi
at conditions is executed.
ere are mainly three types of decision making statements in Java
1. If statement
2. switch statement
3. conditional operator statement
statement is further implemented as
Simple if statement If-else statement
If-else Ladder
Nested if –else statement
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
18/34
tatement
tatement is helpful in making a decision in our program.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
19/34
Simple if statement
he condition given in if is true then only the statements corresponding to that if block is execuntax of if statement
condition)
condition is true , these Statements written inside curly brackets will be executed .
ogram
public class ifstatement
{
public static void main(String args[])
{
int test1=10;
if (test1>10)
system.out.println(“you are wrong”);
if(test1>5)
{
System.out.println("good");
}
}
}
Result of this program is “good”.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
20/34
if else statement
case the if condition is true then the statements inside curly brackets of if block is execu
herwise statements of the else block are executed.
condition)
condition is true, these statements will be executed.
e
case the condition given in if statement is false , these statements will be executed.
se statements are executed always.
ogram
public class if-elsestatement
{
public static void main(String args[])
{
int test1=10;
if (test1>10)
{
system.out.println(“you are wrong”);}
else
{ System.out.println("good");
}
}
}
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
21/34
Output
good
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
22/34
if–else-if ladder
ntax with meaning
condition1)
atements // executed only if condition1 is true.}
e if (condition2)
atements // executed only if condition1 is true
e if (condition-n)
atements // execute only when condition-n is true}
e
atements // executes when all above given conditions are false.
atements // these statements are always executed.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
23/34
Nested if…else statement
hen there are a series of decision, then we have to use a number of if-else statements in nested
m.
condition1){
/Executes when the condition 1 is true
f( condition2){
//Executes when the condition 2 is true
blic class Test1 {
ublic static void main(String args[]){
int a = 30;
int b = 10;
if( a >10 ){
a== 30)
tem.out.println(” a is equal to 30”);
e
tem.out.println(“ a is not equal to 30”);
else System.out.print("a is less than 10");
}
}
}
tput : 30
he switch Statement
we studied, if statements are useful in deciding the sequence control of program. But in case re a number of alternatives to be tested against a variable, then the complexity of the program
umber of IF statements increase. Switch statements solves this problem by allowing a variabtested against a list of values. These values are called cases. When the variable is matched w
rticular case then the statements of that particular case is executed.
ntax:
witch (expression ){
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
24/34
case value1 :
block1
break; //optional
case value2 :
block2
break; //optional
………………………………………..…………………………………………….
……………………………………………………
default : //Optional
//default block
les for switch statement
The switch statement can have a variable of type short,int,byte or char.
A Switch block can have any number of case statements with the following syntax
Case value :
any The value specified in case should be of same data type as variable in the switc
statement. Also this value must be any constant or literal.
When the variable of switch statement is matched with nay case value then the
statements following that case will be executed until Break statement is reached.
As the execurion reaches to a break statement, the switch terminates, and the execut
is transferred to the next line following the switch block.
Putting Break in each case is not necessary. In case no Break appears, the execution
through the subsequent given cases until a Break is executed or the switch terminates.
There may be an optional default case in a switch at the end of switch. Default case
executed when value of a variable is unmatched with all given cases.ample:
blic class Test1 {
ublic static void main(String args[]){
char letter = 'S';
switch(letter)
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
25/34
{
case 'P' :
System.out.println("Duffer");
break;
case 'Q' :
case 'S' :
System.out.println("Excellent");break;
case 'R' :
System.out.println("You failed");
Case 'F' :
System.out.println("try again");
break;
default :System.out.println("Invalid input");
}
tput:
cellent
oping statements in java
metimes there is a need to execute a block of statements several times depending on any condit
is type of situation is handled by Loops in java.
va allows these loops mechanisms with three types of loops:
for Loop
while Loop
do...while Loop
e for Loop
for loop is a control structure which executes the statements within this IF block several times
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
26/34
pending on conditions.
for loop is beneficial when we already know for how many times to repeat a particular task.
ntax:
(initialization ; Boolean_expression ; update)
/body for the loop
quence of steps followed in a for loop:
First of all initialization statement is executed. This statement allows declaring or
initializing loop control variables.
Now the Boolean expression or test condition is evaluated. If this Boolean expressi
comes to true, the defined body of the for loop is executed. Otherwise in case of false, th
body does not execute and control is transferred to the statement following the for loop.
After once execution of body of loop, the control is transferred to the update stateme
which generally includes increment or decrement. This statement is generally used to upd
any loop variable.
Again there is a evaluation of Boolean expression. If it is evaluated true, the loop a
executes and this process (loop body , then update step, then Boolean expression) is repe
until Boolean expression is false. As Boolean expression evaluates false, loop is termina
ample:
blic class demo {
ublic static void main(String args[]) {
for(int a = 10; a < 20; a = a+1) {
System.out.print("value of a : " + a );
}
is program results in printing value of a from 10 to 19. Because as a is incremented to 20 , the
ndition a
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
27/34
hile ( Boolean_expression)
/body of the While Loop
he Boolean expression is true then the body defined for the While loop is executed and this rep
ecution for same body continues until the Boolean expression is evaluated to false.
the loop terminates or the Boolean-expression is false , the control is transferred to the first
tement following the while loop.
ample:
r the last given example of for loop, corresponding While Loop is given below.blic class Demo1 {
blic static void main(String args[]) {
int a= 10;
while( a < 20 ) {
System.out.print("value of a : " + a);
a++;
}
e do...while Loop
is loop is similar to other loops with a major difference that this loop is always executed at le
ce while the other for and While loops are executed only when condition or Boolean expressio
e. For and while loop may be executed for Zero times if the condition is false.
ntax:
/body for the loophile ( Boolean_expression);
nce this loop has the testing condition at the end of loop , the loop is executed at least once alw
e execution of this loop is otherwise very similar to While loop. Firstly loop is executed and t
olen_expression is evaluated. If expression is true then loop is executed again and again until
olean expression is false.
ample:
milar program for printing value of a from 10 to 19 using do….. while loop is given below.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
28/34
blic class demo2 {
ublic static void main(String args[]){
int a = 10;
do{
System.out.print("value of a : " + a );
a++;}while( a< 20 );
hanced for loop
hanced for loop is mainly used in case of arrays.ntax:
(declaration : expression)
/ Body for enhanced for loop
pression in the above given syntax generally represents the array which is nneeded to lop throu
is expression is either an array variable or a method call returning array.
claration is a block variable with the same type as the array we are accessing. This variable h
scope within this for block with a value equal to current array element.
ample:
blic class Demo {
ublic static void main(String args[]){
int [] values = {10, 20, 30, 40, 50};
for(int a : values ){
System.out.print( a );
System.out.print(" ");
}
System.out.print("\n");
String [] students ={"James", "Anil", "Tom", "Aman"};
for( String name : students ) {
System.out.print( name );
System.out.print(" ");
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
29/34
}
sult:
20 30 40 50
mes Anil Tom Aman
eak Keyword
va provides break keyword which is used to terminate the entire loop. This keyword can be uide a loop or switch statement to terminate that lop or switch.
ep in mind that in case of nested loops, break keyword only terminates the execution of innerm
op transferring the execution to the first statement following that loop.
ample:
blic class Demo {
blic static void main(String args[]) {int [] values = {10, 20, 30, 40, 50};
for(int a : values) {
if( a == 40 ) {
break;
}
System.out.print( a );
System.out.print("\n");
}
tput:
the value of a is equal to 40 , the break statement executes and terminates the loop.
ntinue Keyword
ntinue keyword can be used in any loop structure for deciding the execution control.
When continue is used in for loop then the control is immediately transferred to the
update statement without executing the statements after continue.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
30/34
In case of while or do-while, control is immediately transferred to the Boolean
expression without executing the statements after continue.
ample:
blic class Continue {
blic static void main(String args[]) {
int [] values = {10, 20, 30, 40, 50};
for ( int a : values ) {
if( a == 40) {
continue;
}
System.out.print( a );
System.out.print("\n");
}
is would produce the following result:
hen the value of a is equal to 40, the continue statement executes which transfers the control at
ginning of loop without printing the value of a equal to 40.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
31/34
Chapter 4;
Classes, objects and methodsJava is a pure object – oriented language, all java programs have at least a class. Everything
nt to represent through a Java program must be encapsulated in a class. Classes define the stat
haviors for the basic component of a class known as objects. Here the object – oriented refers
sses create objects and the objects uses the defined methods for their mutual communication.
nce Java is an object-oriented language and therefore supports the following feature:
Objects
Classes
Encapsulation
Abstraction
Polymorphism
Instance
Methods
ass: A class is a user-defined data type which acts as a blueprint to represent the states and
haviors for the corresponding objects.
bject: Objects are instances of a class and have their own states and behaviors. For example aect dog for an animal class has state as name, color, breed and behaviors as eating, barking an
gging.
ere are a number of objects in our surroundings which include dog, human, table, bird, mobile
l these objects have their specific states and behaviors.
case of a person as object, corresponding states are name, color, height, age and behaviors are
ing, walking, running, etc.
fining a class
ass is a user defined data type serving as a blueprint. A simple class is defined with the follow
m:
ass classname
ta members or fields declaration; // optional
ethods or member functions declaration; // optional
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
32/34
data members and member functions are optional, so Java allows even an empty class.
elds and Methods declaration
we know, data is encapsulated in Java by placing its data members and member functions ins
ss. These variables are known as instance variables as they are created as an object is instant
e method of declaring instance variables is same as local variables.
ass Person
age;
ing name;
ing color;
is class has three instance variables one age of integer type and other two name and color of st
e.
claring Methods
method declaration generally has the following things:
Name for the method
Return type of that method
List of arguments or parameters
Body for that method which actually defines the operations to be performed on data
e general form for method declaration is
urnType MethodName ( argument-list)
dy for the method;
class can have following types of variables:
Instance variables: The variables defined inside a class but outside any method are
known as instance variables. As a class is loaded, these variables are instantiated. These
variables can be accessed from any method or block including constructor of that particu
class.
Local variables: The variables defined inside any method, constructor or blocks are
known as local variables. The variable are declared and initialized within a particular
method and destroyed with the completion of that method.
Class variables: These variables are defined inside a class but outside any method
a single difference that they are declared using Static keyword.
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
33/34
the above given example name, color, age are data member and eating, hungry, walking, runnin
eping all these are functions.
ample for a class
blic class Person {
ing Name;
ing color;
nt age;
oid eating(){
oid hungry(){
void Walking (){
d Running (){
oid sleeping(){
eating Objects for a class
we know objects are the instances of the classes. Creating a object is also known as instantiatobject.
va provides a new operator for creating object. New operator creates an object for the specifss and also returns a reference for that created object. As this returns a reference of class type
refore there is aneed to create a reference type variable so that that can hold that reference.
ample for creating object for class squareuare s1; // declaring object
= new square(); // instantiate object
st statement declares a reference type variable to store the object reference of square type
hereas second statements actually assigns the object reference to S1 variable.
ese both statements can be combined in a single statement to create an object as
uare s1= new square();
th the above given method, we can create any number of objects for a class.
onstructors
8/18/2019 Java - The Fast Way - The Ultimate, Quick and Easy Java Programming Guide [HQ PDF][Psycho.killer]
34/34
nstructor is the most important topic which comes into the mind as there is a discussion ab
ss. Every class has at least one constructor. If a programmer does not explicitly specify
nstructor, there is always a default constructor for that class. As a object is created, a construc
voked.
portant points for a constructor
Constructor has the same name as class.
There is no return type for a constructor even not void. There can be multiple constructors for a single class.
If constructors are explicitly defined by the programmer then default constructo
comes in existence.
Top Related