JavaNotes
JavaNotes
=====
what is java?
syntax:
=======
class <classname>
//statements;
steps:
======
1) create a file and the save the file with .java Extension
syntax:
-======
javac Filename.java
syntax:
======
java Filename
ex1:
=====
note:
======
1)If we are creating any class with out any access modifier then
by default the class will have default access modifier.
comments:
=========
syntax:
=======
// comments
2)multiple line comments:
==========================
syntax:
========
/*
statements
*/
Datatypes:
==========
java contain eight primitive datatypes
Integer Datatypes:
================
1)byte -size is 1 byte(8bits) --range -128to 127 -default value-0
Note:
=====
==> f or l is a literals to store float and Long values into a variables
long a=10L;
float b = 20.0f;
note:
=====
Any predefined class will act as Referenced types.
Default value for the Referenced Types is = null
ex:
===
String s;
variables :
==========
syntax:
========
accessmodifier datatype variablename ;
default
private
protected
public
1)instance variable --
=================
a)memory is allocated at Heap area of JVM
ex:
====
public class Ex1{
int b; --declaration
int a=10; --declarattion and initialization
int a,b;
int a=10,b=30,c;
//methods
public static void main(String args[]){
}
}
2)static variable--
=================
ex:
===
public class Ex2{
3)local variable --
==============
a)For local variable the memory is allocated
at stack in JVM
ex:
====
int a=10;
JAVANAMING CONVENTIONS:
==========================
1)CLASSNAME:
=============
Class name is a noun and the classname should start with Capital Letter and
secondWord also
followed by Capital.
Ex:
===
class StudentRegistration{
2) methodName:
=============
method name is verb and the method name should startwith small letterand next
word
start with capital Letter(camelCase)
Ex:
===
class Employee{
void getEmployeeDetails(){
//statements
}
3) variableName:
==============
variableName is also camelCase
ex:
===
class Employee{
int empId;
int empName;
int sal;
Example:
=======
class ExampleOnVariables{
int studentNo;
String studentName;
float studentMarks; //instance variables
System.out.println(studentNo);
System.out.println(studentName);
System.out.println(studentMarks);
Example2:
========
WAP named as ExampleOnVariables1 and declare
three instance variables of type int and
create a method named as getSum() ,return type of method is void and perform sum
of two numbers
and display the sum of two numbers.
sol:
===
public class ExampleOnVariables1{
int num1;
int num2;
int res;
res=num1+num2;
System.out.println("sum of two numbers is "+res);
}}
}
oops:
=====
1)class
2)Object
3)Inheritance
4)Encapsulation
5)Abstraction
6)Polymorphism
Class:
======
class classname
{
//Datamemebers //to specify object properties
//member methods // to specify object functionality or actions.
Object:
=======
example:
=======
Chair is an Object
sol:
=====
class Chair
{
String color="black";
String material="plastic";
System.out.println("Chair is moveable");
syntax:
=======
ex:
===
syntax:
=======
ex:
====
System.out.println(c.color);
System.out.println(c.wheels); //to call instance variables
syntax:
========
typeCasting:
=========
There are two typecasting
note:
====
it convert lower datatype to higher datatype
byte->short->int->long->float->double
or
char->int->long->float->double
syntax:
======
(specify the dataype)
Example :
========
1) write a java program to convert one datatype into another data type.
sol:
===
int a=10;
double d = 20.0;
System.out.println(x);
long aa = 30;
System.out.println(y);
Operators:
=========
1)Arithmetic operators:
===================
this operators are used to perfrom calculations between two operands.
+ -- ADDITION
- --SUBSTRACTION
* --MULTIPLICATION
/ --DIVISION --- IT WILL RETURN QUOTIENT
2)Relational operators:
==================
3)Logical operators:
================
&& --- logical and
|| --logical or
^ --logical XOR
! --- logical Not
++,--,+=,-=,%=
Example:
=======
Conditional operator:
=====================
this operator is used to make Conditional Expressions.
syntax:
======
Datatype variableName =Expression1?Expression2:Expression3;
Ex:
===
int a=10;
int b=20;
int value1=(a<b)?a:b;
int value2=(a>b)?a:b;
Conditional Statements:
======================
1)if
===
syntax:
=======
if(condition){
//true statements
}
note:
=====
In if condition it contains only one statement braces
are optional but this statement should not be initialization statement.
Example:
=======
1)WAp to compare two int variables and print which is greater.
using if-else condition.
if-else
======
syntax:
======
if(condition){
//true statments
}else{
if-else-if:
===========
to check multiple conditions
syntax:
======
if(condition1){
//statements
}else if(condition2){
//statements
}else{
//statements
}
ex:
===
WAp to compare three int variables and print which is greater.
using if-else-if condition and logical operators (&& or ||).
Nested If-else:
==========
Nested if-else statements which means you can use one if or else if statement
inside another if or else if statement.
Syntax:
========
if(condition1){
//if condition1 is true then this if block of code will be executed.
if(condition2){
}else{
if(condition2){
}
Assignment:
-----------
WAp to compare three int variables and print which is greater.
using nested-if condition and logical operators (&& or ||).
switch-case:
===========
The Switch statement allows us to execute a block of code among many
alternatives.
syntax:
=======
switch(expresssion){
.....
case condn: statements;
break;
default : statement;
}
Note:
=====
fall-through mechanism in java
the break statement is used to terminate the switch-case statement.
if break is not used, all the cases after the matching case are also executed.
Example
++++++++
wAp to perform arthematic operations using switch case expresssion .
Iterative statments:
=====================
While loop:
===========
to repeat the statements until the condition become true.
syntax:
=======
initialize a variable;
while(condition)
{
//statements;
//increment/decrement
ex:
==
Write a program to print 1 to 10 natural numbers.
write a program to display multiplication table of 2 using while loop;
sol:
===
while(i<=10){
}}
}
sol:
===
int i=1;
while(i<=10){
System.out.println(i);
i++
}
}
}
for loop
========
syntax:
=======
for(initilization;condition;increment/decrement){
//statements
ex:
===
WAP to print 1 to 10 integers
WAP to display multiplication table of 5 using for loop;
sol:
====
public class ExampleOnFor{
public static void main(String args[]){
int n=5;
for(int i=1;i<=10;i++){
}
}
}
do-while loop
=============
syntax:
=======
initilization variable;
do{
//statements;
//increment/decrement
}while(condition);
note:
=====
the statements will execute atleast one time before checking the condition.
Example:
=======
write a java program to print 1 to 10 integers using do-while loop.
WAP to print multiplication table of 4
sol:
===
public class ExampleOndoWhile{
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
continue :- explicity based on condition to skip the iteration and continue the
loop.
Example:
=======
Write a java program to read studentId,studentName,marks,comments from
keyboard or run time by using scanner class
sol:
===
import java.util.Scanner;
}
}
Note:
====
It's because when you enter a number then press Enter, input.nextInt() consumes
only the number, not the "end of line". When input.nextLine() executes, it consumes
the "end of line" still in the buffer from the first input.
}
note:
======
AccessModifer:-(public,protected,private,default)
return type :- primitive datatypes or object References
if not primitive or object it must be void(empty).
ex:
===
void methodOne(){
//any statements
or
//logic
//return type of variable
}
or
static methods:
===============
syntax:
========
//
}
ex:
====
public static void main(String args[]){
//logic
}
Abstract Method:
================
A abstract method is a method , it contains only method declaration
but not definition .
syntax:
=======
public abstract retruntype methodname(if any arguments);
ex:
public abstract void methodOne();
note:
=====
if a class contain atleast one abstract method then compiler will
force the user or Developer to declare the class as abstract.
Example:
=======
1) WAP named as ExampleOnMethods
a) create a instance method(getEmpSal) which return int type value and
perform sum of two numbers by passing values to method.
sol:
===
public class ExampleOnMethods{
int z=x+y;
return z;
int total=m1+m2+m3;
return total;
}
public static void main(String args[]){
Constructor:
============
A constructor doesn't not return any value not even void also.
note:
=====
Initialize the object means ,allocating memory for
instance variables (heap) and the instance variables
will store with it default values based on it types.
1) default constructor:
=======================
2) parameterized constructor:
===========================
A constructor is defined with some parameters with in class.
note:
=====
1)if class doesnt not contain any constructor,
compiler is responsible to provide default constructor in the
class implicitly.
ex:
===
compiled welcome.class
public class Welcome{
public Welcome(){
this()/super()
}
this keyword:
=============
1) this is keyword which represents current class object or instance
example:
--------
public ExampleOnThis(){
Arrays:
=======
A array is used to store collection of similar types of element.
An array is used to store homogenous types of elements.
int[] a;
int []a;
to Declare and initilaize the size for array using new key word
-----------------------------------------------------------------===============
syntax:
=======
ex:
---
Example:
========
sol:
====
public class ExampleOnArray{
System.out.println(a);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
//for each loop
}
}
Example:
=======
1)Create an int array and with size of five elements
and initiliaze the array and display the elements from array
sol:
-----
public class ExampleOnArray2{
int a[] = new int[5]; //declared the array with size using new operator
//initilaze the array
a[0]=10;
a[1]=40;
a[2]=50;
a[3]=60;
a[4]=30;
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println(b);
}
}
Example:
=======
}
//to display the values from array c
for(int i=0;i<c.length;i++){
System.out.println(c[i]);
//foreach-loop
for(int i :c){
System.out.print(i+" ");
}
}}
syntax:
========
sol:
=====
int a[][]={{1,2,3},{10,30,50}}; // 1 2 3
// 10 30 50 2 rows and 3 cols
//no of elements in array is rows*cols
for(int i=0;i<2;i++){ //rows
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
}
}
olp:-
1 2 3
10 30 50
Example:
========
WAP program to declare two dimension array of type int
with size(r=3,c=3) and insert the values to array using Scanner
and display the element using for loop
sol:
===
public class ExampleOnArray6 {
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
Example:
========
eoa.getEmpSal(empSal);
}
}
Example:
========
int a[]={10,30,40,50};
return a;
}
public static void main(String args[]){
for(int b:res){
System.out.println(b);
}
}
String:
=======
String a predefined class available in java.lang.String
// create a string
String example = "Hello! ";
Here, we have created a string variable named example. The variable holds the
string "Hello! ".
Here, we are using the concat() method to add another string World to the previous
string.
It looks like we are able to change the value of the previous string. However, this
is not true.
2)equals() method check for the content inside the Object Reference.
note:
====
1)String literal object will store in String constant
pool memory area of heap
Method Description:
------ ------------------------
contains() checks whether the string contains a substring
replace() replaces the specified old character with the specified new character
out = "HELLO".equals("HELLO");
System.out.println("Checking Equality " + out);
out = "HeLlo".equalsIgnoreCase("Hello");
System.out.println("Checking Equality " + out);
// Converting cases
String word1 = "World";
System.out.println("Changing to lower Case " +word1.toLowerCase());
// Converting cases
String word2 = "world";
System.out.println("Changing to UPPER Case " +word2.toUpperCase());
// Replacing characters
String str1 = "Hello";
System.out.println("Original String " + str1);
String str2 = "Hello".replace('H' ,'M') ;
System.out.println("Replaced H with M -> " + str2);
}
}
Inheritance:
============
or
By using extend keyword we can get the properties and method from
parent class to child class.
note:
=====
syntax:
=======
//data members;
//member methods;
//using child object we can call parent class datamemebrs and members.
//using child object we can call it own data memeber and member methods.
}
Different types of inheritance:
================================
1)single inheritance
2)multiple inheritance
3)multi-level inheritance
1) single inheritance:
======================
ex:
----
public class A{
//variables and methods
}
}
}
A class extend from more than one class and one child
ex:
===
public class A{
}
}
a) parent class :-
1)create a class named as First .
b) child class:-
1)create a class named as Second which extends from First.
sol:
===
int num1=10;
int num2=20;
int z = x+y;
return z;
float f1=10.0;
float f2=20.0;
System.out.println(s.num1);
System.out.println(s.num2);
System.out.println(s.f1);
System.out.println(s.f2);
String gt = s.getMessage("sainath");
System.out.println(gt);
}
}
2) multi-level inheritance
----------------------------
Example-level inheritance
====================
a) create a class named as A and it contains one method
method name is methodOne()(simple statement(sop)
and retrun type is void .
Has-A relation:
===============
A class which contain object reference or entity reference
as a instance variable is called composition or Has-a relation.
Example:
========
1)Address Class
String city;
String state;
String country;
public Address(){
this.city=null;
this.state=null;
this.country=null;
this.city=city;
this.state=state;
country=cn;
}
}
int sid;
String sname;
Address a; //represents student has-a relation with address
public Student(){
this.sid=0;
this.sname=null;
this.a=null;
this.sid=sid;
this.sname=sname;
this.a=a;
System.out.println("Student Details");
System.out.println("Sid is :"+s.sid);
System.out.println("Stundent name is :"+s.sname);
System.out.println("city :"+s.a.city);
System.out.println("state "+s.a.state);
System.out.println("country :"+s.a.country);
super keyword:
==============
->super keyword is used to refer parent class object.
note:
====
1)it will call default constructor of super class by default without specifying
in subclass default constructor.
Example:
========
int a=10;
public ExampleOnsuper(){
}
public void display(){
}
public class Test3 extends ExampleOnSuper{
int a=20;
public Test3(){
Encapsulation:
==============
Encapsulation is process of wrapping or binding the
data members(variables) and member methods functionalities as single unit .
ex:
====
class
note:
=====
In spring,Hibernate frameworks the java bean class will called as Pojo class
(plain old java object)
ex:
===
this.empid=empid;
}
public void setEmpName(String empName){
this.empName=empName;
}
this.sal = sal;
}
return this.empid;
return this.empName;
}
public float getSal(){
return this.sal;
}
note:
======
In eclipseIDE we can generate getter and setter methods
in class rightclik-->source-->generate setters and getters-->selectall
-->finish.
method signature:
=================
syntax :-
---------
methodname(datatype of variables);
ex:
===
public int getSum(int x,int y){
Polymorphism:
=============
polymorphism is means many forms.
A class which contain one or more methods which consists of same method name
and differ in arguments is called method overloading.
1) different in no of arguments.
2)different in type of arguments,
ex:
====
sol:
----
int z=x+y;
return z;
System.out.println(x+" "+y);
System.out.println(x+" "+y);
}
byte ->short->int->long->float->double
or
char ->int->long->float->double
ex:
===
public class ExampleTypePromotion {
ept.methodOne(10);
ept.methodOne(10.5);
ept.methodOne('a');
note:
======
compiler is responsible to perform or to execute the
methods based on method signature is called method resolution
(decision) ,the decision taken at compile time based on argument referenced
type.
ex:
===
public class ExampleOnOverride //parent
{
}
}
tmd.methodOne();
}
note:
======
In method overriding the method resolution(decision) will
take at run time based on Object reference type.
For A super class Reference variable Holding its sub class Object Execution:
===========================================================
ExampleOnOverride tmd1 = new TestOnMethodOverride();
tmd1.methodOne();
1)first it will check the method reference in Super class and based on
method signature if available it will check same method Signature in child
class ,
if available it will execute child class method.
2)If method signature not available in super class and the same method signature
available in child class ,it will not execute child class method it will throw
an error.
Interface:
==========
-->An interface contain variables and these variable must be static and final
syntax:
=======
//variables;
//abstract methods
note:
=====
1)if we not provide implementation for any one abstract method then
declare the class as abstract.
2)we can not create the object for abstract class directly.
3) to create the object for the abstract class, create one more
class which extends from abstract class and provide
the implementation for the abstract method
Example:
========
Sol:
-----
interface:
=======
Implementation Class
=================
int z=x+y;
return z;
return x+y+z;
}
Example:2
=========
1) create a interface named as MyInterface
a) int methodOne();
b) String methodTwo(String s);
c) void methodThree();
4)create a one more class named as ExImp2 extends from above class
ExImp1 and provide the implementation for abstract method
methodThree();
5) create a object for ExImp2 class and call the methods
public interface MyInterface{
4)create a one more class named as ExImp2 extends from above class
ExImp1 and provide the implementation for abstract method
methodThree();
5) create a object for ExImp2(two ways) class and call the methods
String wc = ex2.methodTwo("Welcome");
System.out.println(wc);
ex2.methodThree();
Example3:
========
a)
public interface I1{
public abstract String getMessage();
void display();
}
public interface I2 extends I1{
sol:
===
System.out.println(ei2.getMessage());
ei2.methodTwo();
ei2.display();
Abstraction:
============
abstraction is a process of hiding implementation details
and showing useful information to user is called abstraction.
ex:
===
ATM--withdrawal a money
note:
======
we can declare the class as abstract but even it does not contain
any abstract method to achieve security i.e., for the class
it will not allow us to create object for the class directly.
ex:
====
case1:
-------
public abstract class Ex1 implements Interface{
//not implemented any abstract method
//instance methods
case2:
------
public abstract class Ex1{
//instance methods
final keyword:
==============
we can use final keyword in three ways
4)we can declare a class as final and we can create the object for final class
but
final class will not participate in inheritance.