Class:
A class can also be called a logical template to create the objects that share
common properties and methods.
A class is an blueprint or logical entity.
Syntax:
<access specifier> class class_name
{
// member variables
// class methods
}
Objects:
In Java, an object is created from a class. We have already created the class named Main, so
now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object name, and use
the keyword new.
To create object :
Classname refvarible = new classname();
1 2 3 4
1: classname
2: refvarible
3: new keyword
4: constructor
5: =(assignment operator)
Packages:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined packag
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql et
Syntax is : package packagename;
Ex: Package Datatypes;
Example program:
// class definition
public class Calculate {
// instance variables
int a;
int b;
// constructor to instantiate
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}
// method to add numbers
public int add () {
int res = a + b;
return res;
}
// method to subtract numbers
public int subtract () {
int res = a - b;
return res;
}
// method to multiply numbers
public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);
// calling the methods of Calculate class
[Link]("Addition is :" + [Link]());
[Link]("Subtraction is :" + [Link]());
[Link]("Multiplication is :" + [Link]());
[Link]("Division is :" + [Link]());
}
Datatypes:
A data type is an attribute associated with a piece of data that tells a computer system how
to interpret its value.
datatypes are of two types
1) primitive:
priitive into two types
boolean integral
boolean character integer floating
char byte short int long float double
2) non primitive:
[Link]
[Link]
[Link]
byte > short > int > long > float > double
the out of range in integer is "int"
syntax of datatypes:
datatype varible name = Value;
1) Byte:
byte n = 24;
// range :-128 to +127
error://byte c = 129;////Type mismatch: cannot convert from int to byte
2)short:
shotr r =12000;
range: -32768 t0 32767
error://Type mismatch: cannot convert from int to short
3)int:
int s =20;
range-2147483648 to 2147483647
error://int x =2147483649;// The literal 2147483649 of type int is out of range
4)long:
long l = 234556;
range: -9223372036854775808 to 9223372036854775807
error: //long h = 8989888089;//The literal 8989888089 of type long is out of range
5)float:
range: 1.40239846e-45f to 3.40282347e+38f
float f = 123.34;
error: //float f = 1233.5;// Type mismatch: cannot convert from double to float
6)double:
range: 4.94065645841246544e-324 to 1.79769313486231570e+308
double d = 5476454674.0;
// without using . to slove errors
double a = 3535465467.;
double b = 3535465467l; or L
double c = 3535465467f; or F these three are exclusive le decleared
double m = 3535465467d; or D
error://double f = 3535465467;//The literal 35354654676 of type int is out of rang
case study 1:
//float e = 123;
//int n = 123.0;//int n = 123.0; Type mismatch: cannot convert from double to int
Case study 2 :
1. int r = 12d; //Type mismatch: cannot convert from double to int
2. float h = 123d; //Type mismatch: cannot convert from double to float
3. byte d = 34l; //Type mismatch: cannot convert from long to byte
4. long g = 56f; //Type mismatch: cannot convert from float to long
5. float k = 78l; //78.0
6. long l = 5678; //5678
7. double o = 78989l; //78989.0
8. double y = 558876.0; //558876.0
7)boolean: here boolean means (true or false)
boolean n = "TRUE";//Type mismatch: cannot convert from String to boolean
boolean m = TRUE;//Type mismatch: cannot convert from String to boolean
boolean b = True;//Type mismatch: cannot convert from String to boolean
boolean h = "true";//Type mismatch: cannot convert from String to boolean
boolean l = true;
boolean u = false;
boolean p = 6789;Type mismatch: cannot convert from int to boolean
boolean c = 6789l; Type mismatch: cannot convert from long to boolean
8) Char:
Data is stored in "single quotes"
stored data should be "single character"
Syntax :
char y = 'n';
9) String: The String class represents character strings. Allstring literals in Java programs,
such as "abc", areimplemented as instances of this class.
Strings are constant; their values cannot be changed after theyare created. String buffers
support mutable strings.
Because String objects are immutable they can be shared. For example:
String str = "abc";
Data is stored in "double quotes"
stored data should be "single or multiple character"
Syntax:
String s = "[Link]";
Case study 3:
int r = "10"; Type mismatch: cannot convert from String to int
String s = "tree"; tree
boolean n = false; false
int u = 'p; 112
char m = 99; c
float f = 'N'; 78.0
Variables:
Vary means : change
Ables means: happens
"Variables are containers for storing data values."
variable is an stored location or memory location to store data in our program
Datatype variable = value;
Variables are of three types :
they are:
[Link] variables:
Local variables are declared inside the function block
(or)
Local variables are declared in inside class and method
local variables are can’t use outside method .
we can access local variables in main method with object reference variable.
EX program:
package Variables;
public class localvaribleclass2
{
void m2()
{
int v = 67;
[Link](v);
}
public static void main(String[] args) {
localvaribleclass2 b = new localvaribleclass2();
b.m2();
}}
[Link]/static variables:
static variables are declared inside the class and inside the method with static keyword.
To access these variables in main method we dont need any object reference.
In this we have to use one memory location to many variables.
EX program:
package Varibles;
public class staticvarible3 {
int b = 678;// instance variables
static String n = "Naveen Royals";// static variables
void m1()
{
[Link](b);// instance variables access in instance area is m1
[Link](n);//static variables access directly m1 and m2
}
void m2()
{
[Link](n); // static variable access in m2
}
public static void main(String[] args) {
[Link](n);
staticvarible3 k = new staticvarible3();
[Link](k.b);
k.m1();
k.m2();
}
}
[Link] varibles:
i) The variables which are declared inside of a class but outside the methods is known as
instance variables.
ii) To acess instance variable in main method we need to object reference.
Ex program:
package Varibles;
public class Instanceclass1 {
void m1()
{
[Link]("Welcome to Naveen Royals");
}
String s = "Naveen Royals"; //instance variable//
public static void main(String[] args) {
Instanceclass1 v = new Instanceclass1();
v.m1();
[Link](v.s);
}
}
Methods:
A method in Java is a block of code that, when called, performs specific actions
mentioned in it.
Syntax :
Returntype methodname ()
{
//lines of code
}
methods are of two types:
they are:
1) static method:
In static method we can store only static /global variables.
we can access static/global variables do not need any object reference.
The area under static method is called as static area.
EX PROGRAM:
public class staticmethod {
int b = 678;// instance variables
static String n = "Naveen Royals";// static variables
void m1()
{
[Link](b);// instance variables access in instance area is m1
[Link](n);//static variables access directly m1 and m2
}
void m2()
{
[Link](n); // static variable access in m2
}
public static void main(String[] args) {
[Link](n);
staticmethod k = new staticmethod();
[Link](k.b);
k.m1();
k.m2();
}
}
2) Non-static method:
In Non static method we can store both static /non static variables.
we can access non static variables we need object reference in main method.
we can access static variables in this method directly.
The area under non static method is called as instance area.
Note:
1) instance variables are used in if data is changes every time and second
2) in that if any changes are in program, then do not affect another variable.
3) main dis advantage is memory wastage.
1) coming to static variables we have to use static variables when the data is constant
everywhere in the program.
2) in that if any changes occur the total program will change.
3) here no memory wastage.
Default values of instance variables and static variables:
Instance variables:
int: 0
float: 0.0
long: 0
short :0
byte: 0
Character:
char: square box
Boolean:
Boolean: false
String:
String: null
Method Categories:
They are of four types:
1. Method without return type and without parameters:
EX PROGRAM:
package Methodcategories;
public class MWORWOP {
void n1() // void is an return type it does not return any thing
{
int i = 23;
int n = 34;
[Link](i+n);
}
public static void main(String[] args) {
MWORWOP n = new MWORWOP();
n.n1();
}
}
2. Method with returntype and without parameters:
* in this we have to return one variable only .
In this which data is return to method that method name is return value datatype:
int naveen ()
{
int b = 654;
int n = 556;
[Link](n+b);
return n;
}
we have to access returntype varible for that to print method.
like: [Link]([Link]());
EX PROGRAM:
package Methodcategories;
public class MWRWOP {
int naveen ()
{
int b = 654;
int n = 556;
[Link](n+b);
return n;
}
public static void main(String[] args) {
MWRWOP m = new MWRWOP();
[Link]([Link]());
}
}
3. Method without returntype and with parameters:
EX PROGRAM:
package Methodcategories;
public class MWORWP {
void me(int a, int b)
{
int c = a+b;
[Link](c);
}
public static void main(String[] args) {
MWORWP b = new MWORWP();
[Link](900,9999);
}
}
4. Method with returntype and with parameters.
EX PROGRAM:
package Methodcategories;
public class MWRWP {
int div(int n , int m)
{
int d = n/m;
return d;
}
public static void main(String[] args) {
MWRWP n = new MWRWP();
[Link]([Link](565, 60));
}
}
FLOW CONTROL STATEMENTS:
It can control the flow of lines on code in program.
It can change the flow of execution.
In this normal program flow to jump directly on some statements.
It has three types:
1) conditional statements:
1. if
[Link] -else
[Link] if -else
[Link] if
[Link] statements
2) transfer statements:
[Link]
[Link]
3) looping statements/iterative statements.
[Link] loop
[Link] for loop
[Link] loop
[Link] while loop
1) if statement:
> if statement contains only one condition occurred first check the condition
if it is true, it will execute block of statements otherwise not executed.
> syntax is:
if (condition)
{
// block of statements
}
> EX:
package controlstatement1;
public class IFclass {
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}
}
}
2) if -else:
> The if-else statement is an extension to the if-statement
which uses another block of code, else block.
The else block is executed if the condition of the if-block is evaluated as false.
comditions are:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a! = b
> syntax:
if(condition)
{
statement 1; //executes when condition is true
}
else
{
statement 2; //executes when condition is false
}
> EX:
package controlstatement1;
public class IfElse {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10)
{
[Link]("x + y is less than 10");
}
else
{
[Link]("x + y is greater than 20");
}
}
}
Nested if else:
The if-else-if statement contains the if-statement followed by multiple else-if statements.
In other words, we can say that it is the chain of if-else statements that create a decision
tree
where the program may enter in the block of code where the condition is true.
We can also define an else statement at the end of the chain.
conditions:
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Equal to a == b
Not Equal to: a != b
Syntax:
if(cond)
{
}
else if(cond)
{
}
else if(cond)
{
}
else
{
}
Nested if:
Nested if refers to an if statement within an if statement.
When we write an inner if condition within an outer if condition,
then it is referred to as a nested if statement in java.
Syntax:
if(test_condition1)
{
if(test_condition2)
{
//statements
}
switch case:
Instead of writing many if. Else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed.
how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later in this chapter
Syntax is:
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
EX:
int day = 4;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
}
// Outputs "Thursday" (day 4)
LOOPING STATEMENTS:
For Loop:
Syntax:
for(intialization;condition ;increment/decrement)
{
// block of code
}
To print even numbers using for loop:
code 1:
public class Forloop6 {
public static void main(String[] args) {
for(int k = 1; k<=100;k++)
{
if(k%2==0)
{
[Link](k);
}
}
}
}
(or)
public class Forloop7
{
public static void main(String[] args) {
for(int k = 0; k<=100;k=k+2)
{
[Link](k);
}
}
}
or
public class Forloop9
{
public static void main(String[] args) {
for(int k = 1; k<=100;k=k++)
{
[Link](k);
k++;
}
}
}
(or)
public class Forloop10 {
public static void main(String[] args) {
for(int k = 1; k<=50;k++)
{
[Link](k*2);
}
}
}
To print odd numbers using for loop:
code1 :
public static void main(String[] args) {
for(int k = 1; k<=100;k++)
{
if(k%2==1) {
[Link](k);
}
}
}
code 2:
public static void main(String[] args) {
for(int k = 1; k<=50;k++)
{
[Link](k*2-1);
}
}
}
To print tables using for loop:
code:
public class tables2 {
public static void main(String[] args) {
for(int y =1; y<=10; y++)
{
[Link]("12 x "+y+"="+(12*y));
}
}
}
to print table in reverse order:(assignment )
code :
public class reversetables {
public static void main(String[] args) {
for (int i=10 ; i>=1 ; i-- )
{
[Link](10 + "*" + i + "=" + i*10);
}
}
}
Nested for loop:
Syntax:
for(init;cond;increment/decrement) ->row
{
for(init;cond;increment/decrement) ->coloum
{
}
}
pattern 1:
123456789
123456789
123456789
123456789
code:
public static void main(String[] args) {
for(int r=1;r<=3;r++)
{
for(int c = 1;c<=9;c++)
{
[Link](c);
}
[Link]();
}
pattern 2:
11111111
22222222
33333333
44444444
55555555
66666666
code :
public static void main(String[] args) {
for(int r=1;r<=6;r++)
{
for(int c = 1;c<=8;c++)
{
[Link](r);
}
[Link]();
}
pattern 3;
1
12
123
1234
12345
123456
1234567
12345678
123456789
code:
public static void main(String[] args) {
for(int r=1;r<=9;r++)
{
for(int c = 1;c<=r;c++)
{
[Link](c);
}
[Link]();
}
pattern4:
1
22
333
4444
55555
666666
7777777
88888888
999999999
code:
public static void main(String[] args) {
for(int r=1;r<=9;r++)
{
for(int c = 1;c<=r;c++)
{
[Link](r);
}
[Link]();
}
pattern 5:
@
@@
@@@
@@@@
@@@@@
@@@@@@
@@@@@@@
code:
public static void main(String[] args) {
for(int r=1;r<=9;r++)
{
for(int c = 1;c<=r;c++)
{
[Link]("$");
}
[Link]();
}
}
pattern 6:
*********
********
*******
******
*****
****
***
**
*
code:
public static void main(String[] args) {
for (int i =9; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
[Link]("*");
}
[Link](); // Move to the next line after each row
}
pattern 7:
10 9 8 7 6 5 4 3 2 1
987654321
87654321
7654321
654321
54321
4321
321
21
1
code:
public static void main(String[] args) {
for (int i =10; i >= 1; i--)
{
for (int j = 1; j <= i; j++) (asec order )
{
[Link](j);
}
[Link](); // Move to the next line after each row
}
or
for (int i =1; i <= 10; i++)
{
for (int j = 10; j >= i; j--)
{
[Link](j); (desc order)
}
[Link]();
}
Transfer statements:
they are of two types:
1) Break :
Break Statement is a loop control statement that is used to terminate the loop.
As soon as the break statement is encountered from within a loop, the loop iterations stop
there,and control returns from the loop immediately to the first statement after the loop.
Syntax:
jump-statement;
break;
2) continue:
Unlike break statement, the continue statement doesn't break the loop
whereas, it skips the specific part of the loop and jumps to the next
iteration of the loop immediately.
Syntax:
jump statement;
continue;
Access specifiers:
they are of four types:
> private:
within the class -yes
in same package in sub class-no
other class in same package-no
in sub class another package- no
other class in another package-no
> default:
within the class -yes
in same package in sub class-yes
other class in same package-yes
in sub class another package- no
other class in another package-no
> protected:
within the class -yes
in same package in sub class-yes
other class in same package-yes
in sub class another package- yes
other class in another package-no
> public:
within the class -yes
in same package in sub class-yes
other class in same package-yes
in sub class another package- yes
other class in another package-yes
Constructors:
> Constructors are like methods.
> it does not have return type.
> it has same name as classname.
> it will default calls only once when object is created.
to create object for this
we have "new classname ();"
types:
they are of two types:
> default constructor:
add ()
{
}
> parameterized constructor/method:
add(parameters)
{
}
THIS keywords:
this can be used to call variables, methods, constructors (default/ parameterized)
this. Variablename--->variable
this. method () --->method
this () (in that we can call default/ parameterized) --->constructor
case study 1:
from parameterized constructor we can call default constructor, method variables
using this keyword.
case study 2: from default constructor we can call parameterized constructor, method
variables using this keyword.
note:
> methods/ variable can be called using THIS in any line inside constructor.
> constructor can be called in first line in a constructor.
> in method we cannot call constructor inside method in first line.
> THIS concept deals with current class data only.
CORE JAVA
in core java we have to discuss about OOPS concepts:
they are of four types:
[Link]:
it is a mechanism in which one object acquires all the properties and behaviors of a parent
object.
It is an important part of OOPs (Object Oriented programming system).
the idea behind inheritance in Java is that you can create new classes that are built upon
existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent
class.
Moreover, you can add new methods and fields in your current class also.
inheritance represents the "IS-A "relationship which is also known as a parent-child
relationship.
Why use inheritance in java:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Terms used in Inheritance
Class: A class is a group of objects which have common properties.
It is a template or blueprint from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class
It is also called a derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields
and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.
for this we an use extends keyword.
syntax is :
class Subclass-name extends Superclass-name
{
//methods and fields
}
types:
1)singe inheritance:
When a class inherits another class, it is known as a single inheritance.
In the example given below, Dog class inherits the Animal class,
so, there is the single inheritance.
Example:
class Animal{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal{
void bark()
{
[Link]("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}
Output:
barking...
eating...
2)Multilevel inheritence:
When there is a chain of inheritance, it is known as multilevel inheritance.
As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
ex:
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
} void bark(){[Link]("barking...");}
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
Output:
weeping...
barking...
eating..
3)Hierarchal inheritance:
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class,
so there is hierarchical inheritance.
EX:
class Animal{
void eat()
{
[Link]("eating...");}
}
class Dog extends Animal{
void bark()
{
[Link]("barking...");}
}
class Cat extends Animal{
void meow()
{
[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
Output:
meowing...
eating..
in that:
multiple inheritence is not suported.
because,To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors,
Java renders compile-time error if you inherit 2 classes.
So whether you have same method or different,
there will be compile time error.
ex:
class A{
void msg()
{
[Link]("Hello");}
}
class B{
void msg()
{
[Link]("Welcome");}
}
class C extends A,B
{
//suppose if it were
public static void main(String args[]){
C obj=new C();
[Link]();//Now which msg() method would be invoked?
} }