Java
Binary Language:
Developing the application in the binary language will take more time and very difficult also. The application which are developed under Binary language those are platform dependent.
Platform:
It is a combination of hardware and software, it will provide the environment. On top of that we can execute the programs.
Execute programs means, installing software’s, typing some content on notepad.
Platform Dependency:
Whatever the application we developed and compiled under one operating system, that is not executing under different operating systems is called platform dependency.
Whatever the application we developed under the binary language, that application is not executed in all the operating systems.
This is main drawback of binary language.
Assembly language:
If we want to decrease the difficulty of binary language program then we can go for assembly language.
This is low level language.
This language uses MNEMONICS (ADD, SUB, and MUL)
It is also platform dependency language.
To avoid the drawback of platform dependency, then we can go for High-level languages.
High Level Language:
It is very easy to learn, easy to code.
These High Level Languages programs executes with in the less time.
We have different high level languages, those are
C, C++, COBOL, Pascal, .Net, java.......
Except java remaining above languages also platform dependent language.
If we want to get platform independency, then we go for java.
With the help of java we can develop platform independency application or internet support applications.
Java standard edition is basic for learning hadoop, selenium, salesforce, android, cloud computing.
Software: Software is a development tool, which used to converting from imaginaries to real world existing things, by writing set of programs.
Types of software’s:
1. System software
2. Application software
3. Internet software.
System Software’s are used to develop hardware functionalities.
Ex: C, embedded systems, PLC
Application software is used to develop databases.
Ex: oracle, MySQL, db2 and sqlserver.....
Internet software’s are used to develop the internet support applications.
Ex: java, .NET
Object Oriented programming language:
Any language which can develop under Object Oriented Programming System principles, those languages are called OOPL.
Ex: C++, .NET, Java
OOPS: OOPS provides some rules and regulation and designs which help to develop languages very easily.
We have the following OOPS principles. Those are
1) Class
2) Object
3) Encapsulation
- 4) Abstraction
5) Inheritance
6) Polymorphism
History of Java:
- Development of java is start from Green Team (java team).
- Initially java had introduced for digital devices (set-top boxes, televisions etc.).
- Now java is used internet programming, mobile devices, games, e-business).
- James gosling, patrick naughton introduced in 1991 June.
- Initially it was called greetalk and file extension is ".gt".
- After this language renamed as OAK.
- OAK is symbol of strength.
- OAK is the tree name.
- It is the national tree for Germany, USA, France
- In 1995 OAK renamed as Java.
- No abbreviations for OAK and Java.
- Java is an island of Indonesia.
- (First coffee was produced).
- In 1995 java introduced version like JDK Alpha and Beta.
- In 1996 JDK 1.0 version released in the market.
- JDK Alpha and Beta (1995)
- JDK 1.0 (23rd Jan, 1996)
- JDK 1.1 (19th Feb, 1997)
- J2SE 1.2 (8th Dec, 1998)
- J2SE 1.3 (8th May, 2000)
- J2SE 1.4 (6th Feb, 2002)
- J2SE 5.0 (30th Sep, 2004)
- Java SE 6 (11th Dec, 2006)
- Java SE 7 (28th July, 2011)
- Java SE 8 (18th March, 2014)
Java software released in the market in the form of three flavors.
Java Standard Edition
Java Enterprise Edition
Java Mobile/Micro Edition
With the help above flavor’s we can develop the following applications.
1. Standalone/Desktop applications.
2. Client-Server programming (socket programming)
3. Database interaction applications.
4. Web applications.
5. Enterprise/Distributed applications.
6. Interoperable applications.
High Performance:
If we go for other languages, they are using only one translator for executing the program. So that language will take more time to execute. If any application will take more time to execute that application performance will be decreased.
To avoiding this problem java internally uses two translators
1. Interpreter.
2. JIT Compiler
Compiler: It is an translators, it will convert our source code to byte code. It is check all line at a time, if ant syntax errors available first those errors will be placed into memory, after checking all the statements finally it will print all error information on the output device (console).
Whereas Interpreter will translate the code from bytecode to machine understandable code. It will check line by line. If current line valid then control goes to next line otherwise it will print error or exception message on the console.
Interpreter is very good at execute the single time execute statements.
Whereas JIT compiler good at execute the looping statements.
But these two components do not have any capability to understand whether the statements are single time execute or looping statements.
In JVM, there is one special component i.e. "profiler".
This profiler will recognize the statement behavior.
If statement is single time execution statement then those statements will give to Interpreter, if statements are looping statements then those statements are handover to JIT compiler.
In java both Interpreter and JIT compiler works combined and execute the program within the less time, if program is execute with in the less time automatically the performance of an application will be increase.
By this reason, we can say java is a high performance language.
Robust: Java is a robust language due to the following reasons.
1) Proper Memory Management.
2) Exception Handling.
3) Casting.
Java internally used one background program, which is used to maintain memory properly.
The background program is Garbage Collector. This Garbage Collector, will check is there any unused memory or not, if yes that memory will be cleanup, the same memory will be allocated to other data.
2) Exception Handling:
Java is giving very great support to handle the both compile time and runtime exceptions.
Whenever exception is raised, internally java uses some predefine code to generate exception message in the following manner.
In the exception message it will give information about
1) FileName
2) ClassName
3) MethodName
4) LineNumber
5) Description of an exception (Exception Message)
Casting: In java both compile time and runtime the casting operation will be checked.
In the compile time compiler will check is that casting is proper or not.
If not compiler will give compile time error?
In the runtime JVM will check is that casting is proper or not
If not JVM will give runtime error.
By above three advantages, we can say java is a robust language.
Secure:
Java provides huge security in the following ways.
1) Avoiding the pointers.
2) Packages
3) Security Manager
4) Verifier.
If are avoiding the pointers we can provide security, avoid virus and hacking code.
With the help of packages we can provide security to both default and protected data.
Packages provide fully security to default data, but packages are not providing full security to protected data.
If we are doing some modification on protected data, we can access from outside of the package also.
Verifier will check whether the byte code is properly organized or not and is there any virus and hacking code or not.
If yes verifier is provides one Verifier Error.
Distributed:
Whatever applications developed under the java, those application services are equally distributed or sharable.
Data is shared between all the machines in the form of object with in the same time.
Dynamic:
With the help of java we can develop dynamic pages and animated games.
Multi threading:
Executing the threads concurrently one after another is called multithreading.
With the help of multithreading we can execute our programs with the in the less time, then automatically we will improve the performance of an application.
In general our java program contains two threads
1) Main Thread
2) Garbage collector
With the help main thread we can call methods, we can create memory.
With the help of garbage collector we can clean up the memory.
Object Oriented Programming System:
Any language which has been developed based on object oriented programming system principles those languages are called OOPL.
Ex: C++, .Net, java.
We have the following OOPS.
1) Class
2) Object
3) Encapsulation
4) Abstraction
5) Inheritance
6) Polymorphism
Major and Minor versions:
Every java software comes with two versions
1) Major Version
2) Minor version.
Major Version: If we want new features to the existed
Software, then we should go for major version.
Ex: java 1.6
Java 1.7
Minor version:
If we want add bug fixing code to the existed software,
Then we can release our software as an minor version.
One java software is not suitable for all the operating systems. Different operating systems have it’s own java software.
Environment variables setting:
Command prompt is comes with operating system, whereas java development tools (binary files) and library files are comes with java software.
So our command prompt is unable to recognize the development tools.
Then programmer should provide the information about binary and library files to command prompt, with the help of environment variables.
OS by default uses environment variables to recognize software.
For java we have two types of path settings.
1) Temporary settings.
2) Permanent settings.
Temporary Settings: Whatever the setting witch we are done at one command prompt those settings are applicable to that command prompt only not applicable to other command prompt and also if we did close the command prompt automatically all the settings are gone.
Syntax: set path=C:\Program Files\Java\jdk\bin;
With the help of above settings our command prompt recognize the binary files.(javac, java, javap command).
set classpath=.;C:\Program Files\java\jre\lib\rt.jar;
With the help of above settings our compiler and JVM can recognize the predefine .class files.
Binary files used to compile and execute the program, whereas Library files are used develop the user define program.
Permanent Settings:
The settings are which are applicable for entire system; those settings are called permanent settings.
Steps to permanent settings:
Right click on my computer-->Properties--> Advanced System Settings-->Advance--> EnvironmentVariables---->Under System variables.
Click on new button set the path.
Click on new button set the class path.
First java program:
class Demo{
public static void main(java.lang.String[] ram){
java.lang.System.out.println("Welcome to Java");
}
}
FileName: FirstDemo.java
ClassName: Demo
compilation: javac FirstDemo.java
execution: java Demo
Valid syntax:
String[] JhonDoe;
String [] JhonDoe;
String [] JhonDoe;
String JhonDoe [];
Invlid syntax:
[]String JhonDoe;
Note: we cannot place array symbol before data type.
class Demo{
static public void main(java.lang.String[] ram){
java.lang.System.out.println("welcome to java");
}
}
Note: we change places between static and public.
We can develop empty .java file. This file can be compiled but we cannot get any .class file, the reason is there is no source.
We cannot execute the program, the reason is there is no class name.
We can create empty java class. We can compile but we cannot execute.
In java 1.6 we got one error: NoSuchMechError:main
We cannot develop class without class_name.
If we write the following code we will get one compile time error that is identifier expected.
class {
}
Every statement must be ended with semicolon, otherwise we get compile time error that is ';' expected.
In java method must be have return type. If we are not writing, we will get compile time error that is invalid method declaration, return type required.
class Demo{
static{
System.out.println("this is static block");
System.exit(0);
}
}
Without main method also we can compile and execute the program from java 1.0 to java 1.6. But in java 1.7 and 1.8 main method is mandatory.
System.exit(0) means, we are explicitly stopping the program.
class Demo{
static public void main(String... ram){
System.out.println("this is main method");
}
}
(...) called varargs(Variable arguments). we can also called elipse.
Internally varargs maintain array concept only.
This feature is introduced in java 1.5.
Valid syntax:
String... JhonDoe;
String... JhonDoe;
String ... JhonDoe;
String ... JhonDoe;
Invalid syntax:
String JhonDoe...;
...String JhonDoe;
String. .. JhonDoe;
String.. . JhonDoe;
String . . . JhonDoe;
class Demo{
static public void main(String... ram){
System.out.println("this is main method");
}
}
class A{
}
class B{
}
class C{
}
Within the one .java file we can create multiple class. How many class keywords we have those many .class file will be generated by the compiler?
In the execution time, we should give classname, which have main method.
class Demo{
static public void main(String... ram){
System.out.println("this is Demo main method");
}
}
class A{
static public void main(String... ram){
System.out.println("this is A main method");
}
}
class B{
static public void main(String... ram){
System.out.println("this is B main method");
}
}
Within the one .java file we can write multiple class and also in all the classes we can write main method also.
Which class name we are going to be given at execution time that class main method will be execute.
javac FirstDemo.java
java Demo
java A
java B
We can compile more than one .java file at a time with the help of following syntax.
javac *.java
But we cannot execute more than .class files at a time.
If given .java file is not existed, then compiler will give file not found error.
if given .class file is not existed, then jvm will provide NoClassDefFoundError: classname
FileName no need of same as className. But if the class is public type then our filename must be same as className otherwise compiler will give one compile time error i.e.
class <class-name> is public, we should declared file name as <class-name>.java
We cannot write more than one public class with in the one .java file as bellow
public class Demo{
}
public class C{
}
*************
No user define method will be executed automatically in java, except main method.
If we want to execute the user define method, then we should call explacitly.
class B{
void a1(){
System.out.println("a1 method");
}
static public void main(String... JhonDoe){
System.out.println("this is B main method");
}
}
By default compiler will provide java.lang package classes.
We can call main method explacitly by using below syntax.
main(new String[0]);
If we call main method of other class then we should we bellow syntax
Class_name.main(new String[0]);
class A{
psv main(String... JhonDoe){
System.out.println("hi");
main(new String[0]);
}
}
In the above program in the body of main method we did write one syntax like main method calling. This syntax will reach in fine loop.
Finally JVM will provide one runtime error is
"java.lang.StackOverfloeError".
The following are the java programming language elements (The syntax which is used to develop the program)
Those are
1) Comments.
2) Packages
3) Java Tokens
a. Keywords.
b. Literals.
c. Operators.
d. Separators.
e. identifiers
i. Class
1. Methods
2. Variables
ii. Interface
1. Methods
2. Variables
iii. Enum
1. Methods
2. Variables
4) Annotations
5) Constructors
6) Blocks
7) Import statements
Identifiers:
It is name or word or character which is used differentiates from one java element to another java elements.
class Student{
public static void main(String... JhonDoe){
System.out.println("hi");
}
}
To differentiate from one java element to another java element, then we can go for identifier.
Identifier is a name, character, word which is differentiating one java element to another java element.
Naming Conventions in java:
1) class:
class name must be starts with capital letter
Ex: Student
If any class name having multiple words first word first letter must be capital letter, the remaining words first letter must be capital letter.
Ex: StudenPersonalDetails
We can use digits in the class name
Ex: Student1;
We can use two special characters with in the class name.
Ex: Student_Info
Ex: Student$Details
We can start class name with the help of '_' and '$' and combination also.
Ex: _ _ Student
$_$Bank
We can use predefine class name as user define class name. But in this time we cannot get functionalities from predefine class.
ex: class String{
}
Note: Don’t use predefine class names as user define class names.
Don’t use keywords as a class names.
Invalid Classnames:
Class name never be start with digits.
Ex: 1Student //wrong
class name doesn’t have any spaces.
Ex: Student Details//wrong
Student Personal Details//wrong
class name doesn’t have any special characters except under(_) and dollar($).
Ex: Student"Info //wrong
Ex: Student=Info //wrong
We cannot use keyword for class names.
Ex: class while{//wrong
}
Whatever rules we have about to classes, the same rules applicable to interfaces, enum, annotations.
keywords: Keywords must be write with in the small case.
ex: for,if,else,private,public
ex: For, Native, Strictfp //wrong syntax
Variables:
Variables always start with small letter.
Ex: String name;
byte age;
float sal;
Variables name having more than one word then first word first letter must be small letter, the reaming words first letter must be capital letter. The reaming rules same as class rules.
ex: String studentName;
String accountHolderName;
Methods: Whatever the rules we have related to variables, the same rules we have for methods also.
There is a small different between variables and methods is method always ended with '(' and ')'.
Constants:
All the final variables are comes under constants in java
Ex: final double PI= 3.14;
Final variables or constant variable names are always in the capital letters.
Ex: MIN_PRIORITY--->1
MAX_PRIORITY--->10
NORM_PRIORITY..>5
Packages:
Names must be in the small case.
Ex: java.lang
java.util
java.io.
java.net
com. JhonDoe
com.nit
com.google
Literals: A values which is assigns to variable is called literal
Ex: int a = 10 ; //10 is an int literal
char c = 'b' ; //b is an char literal
boolean b = false;//false--boolean literal
boolean b1 = true;//true--boolean literal
String s = "ram";//ram-- String literal
Student s = null; // null---is also called as literal
double d = 23.34d; //23.34---is an doubleliteral
char literal--> always with in the single quote.
we cannot write more than one character with in the single quote.
Ex: 'a' or '4'
'abc' //wrong
boolean literal--> it is always either true or false.
String literal---> always with in the double quotes.
float literal always ended with either small 'f' or 'F'
ex: float f1 = 23.23f;
float f2 = 56.61F;
ended 'f' or 'F' is mandatory.
double d = 34.45;
double d1 = 34.45d;
double d2 = 34.45D;
double literal can be followed by either 'd' or 'D'. It is not a mandatory.
By default all number in java comes under int literal.
By default all fractional numbers in java comes under double literal.
long l = 100;
long l1= 100L;
long l2 = 100l;
ended 'l' and 'L' is not mandatory.
Keywords:
Keywords are predefine/reserved words.
By using these keywrods we can make communication to compiler and jvm.
In java we have 50 keywords
Among the 50 keywrods 48 are used and 2 are unused keywords.
false, true, null these are also predefine words but these not comes under keywords, these are comes under literals.
boolean b = false;
boolean b1 = true;
String s = null;
List of keywords:
java files:
class
interface
enum
datatypes:
byte
short
int
long
float
double
char
boolean
for return type:
void.
controle statements:
if
else
switch
case
default
Looping statements:
for
do
while
Transfer the controle:
break
continue
return
AccessModifer
private
public
protected
Modifer:
final
abstract
synchronized
strictfp
volatile
native
transient
object related keyword:
this
super
instanceof
relationship:
extends
implements
package:
package
import
Exception handling:
try
catch
finally
throw
throws
assert
memory allocation:
static
new
unused:
goto
const
Note: keywrods must be write in small case.
String is a predefine class, which is available in java.lang package. But we can use String as a datatype.
Separators:
It is a small java element which is used to differentiate from one java code to another code(element).
ex: We have totally eight separators.
Those are:
“()”
”{}”
“[]”
”.”
”,”
”;”
”:”
“<>”
Datatypes:
Data types are preserved words, which is used to specify the type of iteral/value.
int a = 10;
boolean b = false;
With help of datatype we can provide the memory for variables.
int a = 10; // 4 bytes of memory.
Datatypes allowes valid operations.
boolean b = true;
b = b++; //invalid syntax
Datatypes provides proper result/output.
String s1 = "10";
String s2 = "20";
S.o.p(s1+s2);//1020
int a = 10;
int b = 20;
S.o.p(a+b);//30
classification of datatypes:
diagram relation to classification.
q) why java uses these many datatypes?
A) To use the memory in proper manner then java uses different datatypes.
If the value is small then we can go for small range of datatype.
If the values is big then we can go for higher range of datatype.
Ranges of data types:
byte:(1 byte)---> 1* 8 = 8 bits
byte b = 10;
if we want to place the data in the memory, first we should convert into binary number system.(0,1). zero and one are two digits.
8
2 = 256 7
--- = 128 = 2
2
-ve number, + numbers
-128 to 128
-128 to 0 to 127
7 7
-2 to 0 to 2 -1
8-1 8-1
-2 to 0 to 2 -1
The range of float, double is greater than the byte,short,int,long datatypes.
Casting:
Converting from one dataype variable value to another datatype variable value is called Casting.
Casting is two types.
1. Implicit casting.
2. explicit casting.
1. Implicit Casting: Converting lower data type value to higher datatype values is called implicit casting.
We can pass the values to variables within the range only we can not pass beyond the range values.
int a = 10;
1) In the above statement compiler will check the destination variable type(int).
2) Based on the type, compiler will check range
3) Compiler is also checking the value of an variable.
4) If value is within the range then compiler will not give any error otherwise compiler will give one compiler time error.
That is incompatible error.
class Casting{
public static void main(String args[]){
System.out.println("main method");
byte b = 127;
System.out.println("b: "+b);
byte b2 = -128;
System.out.println("b2: "+b2);
//byte b1 = 128;
//System.out.println("b1: "+b1);
short s = 32767;
System.out.println("s: "+s);
short s1 = -32769;
System.out.println("s1: "+s1);
}
}
class Casting{
public static void main(String... ram){
char b8 = 'A';
int b9 = b8;
System.out.println(b9);
byte b1 = 10;
short b2 = b1;
int b3 = b1;
System.out.println(b3);
float b4 = b1;
System.out.println(b4);
long b5 = 123L;
float b6 = b5;
System.out.println(b6);
float b7 = 34.34F;//float must be ended //with either 'f' or 'F'
char b10 = 97;
System.out.println(b10);
for(int i=48;i<58;i++){
System.out.print((char)i+" ");
}
System.out.println();
for(int i=65;i<=90;i++){
System.out.print((char)i+" ");
}
System.out.println();
for(int i=97;i<=122;i++){
System.out.print((char)i+" ");
}System.out.println();
char c = '?';
System.out.println((int)c);
}
Assigning the values to variables:
We have 5 ways to assign the values to variables.
1. Assign the values directly to variable.
int a = 111;
2. Assign the values to variable by using another variable.
byte b = 222
int c = b;
3. Assign the values to variables by using method return type.
int m1 = m2();//calling area
Destination part initialization part
int m2(){//called area
return 333;
}
Note: "return" statement will forward the data from called area to calling area.
If any method calling is available in initialization part, then that method must be non-void method.
Non-void method means, method carrying some information. That information must be compatible with destination variable data type.
Method must be having return type. Return type also must be compatible with destination variable data type. If any method having return type then that method must be have return statement with value. Again value must compatible with method return type.
4. Passing the value as a parameter to other method.
void m3(String s){
}
calling the m3 method: m3("ram");
void m2(boolean b){
}
Calling the m2 method: m2(true);
5) We can assign the value to variable with the help of expression.
int c = 10+20;//here 10+20 is an expression
int a = 10;
int b = 20;
int d = a+b;//a+b is an expression.
Functionalities of compiler and JVM in the casting:
Compiler:
Compiler checks type of an variables (both source and destination variables)
Based on the type, compiler checks range of an variables.(data types).
If Destination variable Range greater than source variables Range then compiler will satisfy otherwise compiler will give error.
(DVR>=SVR)
Compiler not checks any value.
short b = 111;
int i = b;//valid
DVR >= SVR
byte b1 = b;//not valid
JVM: jvm will check type of a variable, range of a variable, DVR >= SVR or not, finally JVM will check "value" also.
Note: if we assign the value directly to variable compiler will check type and range and value.
byte b = 127;
ExplacitCasting: Converting from higher data type value to lower data type value.
By default it is not possible in java.
But we can do with the help of cast operator.
int b = 127;
byte b1 = b;//invalid
byte b2 = (byte)b;//valid
In the explicitly casting, if the source value is within the range, then JVM will place the same value assign to destination variable. Otherwise JVM will place some other value.
public class ExplacitCasting {
public static void main(String[] args) {
byte b = 127;
int i = b;
int j = 127;
byte b1 = (byte)j;
System.out.println(b1);
int k = 130;
byte b2 = (byte)k;
System.out.println(b2);
int k1 = 150;
byte b3 = (byte)k1;
System.out.println(b3);
int k2 = 300;
byte b4 = (byte)k2;
System.out.println(b4);
}
}
Note: we cannot convert boolean data type values to another data type.
boolean b = false;
int a = b;//invalid
boolean value we cannot placed into other data type and any other data type value cannot placed into boolean data type.
byte b = 100;
boolean b1 = b;//invalid
*********************
public class ExplacitCasting {
public static void main(String[] args) {
char c1 = 'a';
//char c2 = 'ab';
//we cannot write more than one character
//with in the single quote
char c2 = 100;
System.out.println(c2);
System.out.println((int)' ');
System.out.println((int)'f');
char c3 = '\u0061';//hexadecimal //number system
System.out.println(c3);
char c4 = 0061;//octal number system
System.out.println(c4);
//short s = c4;
//boolean c5 = false;
//byte b = c5;
//boolean c6 = c4;
float f = 23.34f;
int f1 = (int)f;
System.out.println(f1);
double f2 = 435.1234567890d;
long f3 = (long)f2;
System.out.println(f3);
float f4 = (float)f2;
System.out.println(f4);
}
}
Difference between print() and println():
With the help of print() and println(), we can print the data on the console.
print() is printing on the console, after printing the data the cursor position is in the same line, whereas println() will print the data on the console, after printing the data the cursor position is in the next line.
ex: System.out.print("hi");
System.out.print ("bye");
Output: hibye
&&&&
ex: System.out. println("hi");
System.out. println("bye");
Output:hi
bye
In java we have only "+" operator is overloaded.
'+' is used for both
1. Concatenation
2. Addition
If we are using ‘+' in between two number data types then we will get addition functionalities.
If we are using '+' in between number and string then we will get concatenation functionalities.
public class ExplacitCasting {
public static void main(String[] args) {
double d = 23.34D;
float f = (byte)(char)(int)(short)(int)(double) (long)(float)d;
byte b1 = 100;
byte b2 = 20;
//byte b3 = b1+b2;
//byte+byte=int.
int a = 111;
int b = 222;
int c = a+b;
//int+int = int;
byte b3 = 100;
int b4 = 100;
//short b5 = b3+b4;
//byte+int=int
short b6 = 100;
short b7 = 200;
//short b8 = b6+b7;
//short + short = int
//short b9 = b3+b7;
//byte+short=int
System.out.println("10+20: "+(10+20));
int f1 = 111;
int f2 = 222;
System.out.println("f1"+"+"+"f2:"+" " + (f1+f2));
System.out.println(11+"ram");
System.out.println("ram"+22);
System.out.println("ram"+"22");
System.out.println(10+20+"ram");
System.out.println(10+20+"ram"+10+20);
System.out.println(10+20+"ram"+(10+20));
//System.out.println(10+false);
System.out.println("ram"+'A');
System.out.println('A'+32);
//int+char = int
System.out.println(32+'A');
long ll = 34l;
float ff = ll;
long l2 = ll+ff;
//long+float=float
}
}
Comments:
If we want write any statements not related to java grammar rule, then we can write with in the comments.
Comments are used to provide the information about java elements.
Whatever the code which is available under the comments, that code simply ignored by the compiler, that comments source code not converted into byte code. So JVM is also ignored.
With the help of the comments we can easily understand program.
java provides three types of comments
1. Single line comment.
2. Multiline comment.
3. Document comment.
Single Line Comment: By using these comments we can write only line of code.
This can be represent with "//" (two forwards slashes)
Multiline comments: by using this comment we can comment more than one line of code.
This can be represents with "/*......*/".
Document comment:
This is also same as multiline comment; by using this we can comment more than one line of code.
This is represent with "/** ......*/"
Example:
/*Author: John Doe
Date of Birth: 14/12/2015
Vendor: nit
java Version: 1.7
*/
public class CommentDemo {
//With out main method we can not execute the //program.
public static void main(String[] args) {
/**
* int a = 10;
* int b = 20;
*System.out.println(a+b);
*/
}
}
Valid comments:
// // // //
// /* */
// /** */
/* // */
/* /* */
/** /** */
/** /* */
Invalid comments:
/* */ */
/**/** */
/**/* */
/** /* */ */
/* /** */ */
Escape characters:
class EscapeDemo{
static public void main(String...ram){
//System.out.println("hibye");//hibye
//System.out.println("hi\nbye");//hi
//bye
//System.out.println("hi\tbye");//hi bye
//System.out.println("hi\bbye");//hbye
//System.out.println("hi\ bbye");//error
//System.out.println("hihi\bbye");//hihbye
//System.out.println("hi\rbye");//bye
//System.out.println("hihi\rbye");//byei
//System.out.println("hi\fbye");
//System.out.println("hi\'bye");//hi'bye
System.out.println("hi\"bye");//hi"bye
}
}
Note: dont give any space between '\' and character(t,n,b,r,f,',",\).
Variable:
Variable is a named memory location, it can be hold value, the value can be change from one statement to another statement.
int a = 10;//value --10
a = a+1;//value--11
a = a*2;//value--22.
Based on the data types variables can be classified into two types.
1. Primitive Variable
2.Referenced Variable
Primitive Variable:
A variable, which can define with the help of primitive data type is called primitive variable.
Ex: int x=10;
float y=45.56f;
Drawbacks of Primitive Variable:
1. Primitive variables can hold only single value at a time.
It is unable hold more than one value.
2. If we are placing the data into memory with the help of primitive variables, the data is not stored in the memory in sequential order; the data will be stored in random order.
While retrieving the data from memory will take more time.
3. If we are sending the information from machine to another machine with the help of primitive variable, will take more network calls.
if we want resolve above drawbacks then we can go for referenced data types.
1. Arrays
2. class
3. interface
4. enum
Arrays: array is a continuous memory location, which holds more than one value with same data type.
int a[] = {10,20,30};
Each and every element can recognize, with the help of index position.
Within the one index position, we can write only one value.
Representation of arrays:
We have three ways to represents arrays.
1. int a[] = {11,22,33,44};
2. int b[] = new int[5];
//here 5 is called size or dimentions
//mention the size is mandatory.
3. int c[] = new int[]{11,22,33,44,55};
Arrays can be represents with help of "[]".
Difference between length field and length ():
Length filed can be applicable on array variables, to know the size of an array.
int a [] ={0,1,2,3,4,5,6,7,8,9};
System.out.println(a.length);//10
String s[] = {"jhon","doe","uday","kiran","goshika"};
System.out.println (s.length); //5
System.out.println (s[4].length()); //7
length() : This is used for to know the number character are existed in string.
String s = "internationalization";
System.out.println (s.length());//20
Arrays can be classified in the following manner.
1. Single dimensional array
2. Double dimensional array
3. Multi-dimensional array
single dimensional array:
Store the elements either in horizontal(rows) or vertical manner(columns).
Ex: int a[] = {111,222,333,444,555};
public class ArrayDemo {
public static void main(String[] args) {
int a[] ={111,222,333,444,555};
/* System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);
System.out.println(a[3]);
System.out.println(a[4]);*/
for(int i = 0; i < a.length; i = i+1 ){
System.out.println(a[i]);
}
}
}
Java provides 4 ways to read the data from keyboard.
1. commandline arguments
2. java.util.Scanner
3. java.io.BufferedReader
4. java.io.Console.
Command Line Arguments:
Passing values at mean while executing the program is called command line argument.
Syntax: java ArrayDemo 111 ram
(click on enter button)
here 111, ram are called command line arguments.
what ever the data, which is sending from keyboard to java application, that data is always in the form of string.
The data may numerical("123"), character(".net"), special character("%^&*").
class CommandLine{
static public void main(String[] ram){
String s1 = ram[0];
String s2 = ram[1];
System.out.println(s1);
System.out.println(s2);
System.out.println("s1+s2: "+(s1+s2));
}
}
javac CommandLine.java
java CommandLine php android
php
android
s1+s2: phpandroid
------
java CommandLine 123 234
123
234
s1+s2: 123234
-------
java CommandLine "#$%^" "&*("
#$%^
&*(
s1+s2: #$%^&*(
=======
invalid execution:
--------------------
java CommandLine (enter)
java.lang.ArrayIndexOutOfBoundsException: 0
-----------
java CommandLine 123 (enter)
java.lang.ArrayIndexOutOfBoundsException: 1
class CommandLine{
static public void main(String[] ram){
String s1 = ram[0];
System.out.println(s1);
String s2 = ram[1];
System.out.println(s2);
System.out.println(s1+s2);
int i = Integer.parseInt(s1);
System.out.println(i);
int j = Integer.parseInt(s2);
System.out.println(j);
System.out.println(i+j);
}
}
The drawback of above program is , we read the data in the form of string, later we will converting into respective data type(int, boolean, float ......).
so here we are writing some extra logic to read the data in different format. To avoiding this problem, we should go for java.util.Scanner class.
java.util.Scanner:
Scanner is an one predefine class, which is used to read the data in the different data format.
Different data format means either Stirng, int, byte, short,long,float,double,boolean.
With the help of Scanner class we cannot read character data.
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter some string value");
String s = scan.nextLine();
System.out.println(s);
System.out.println("enter some string value");
String s1 = scan.next();
System.out.println(s1);
System.out.println("enter some integer data");
int i = scan.nextInt();
System.out.println(i);
System.out.println("enter some boolean data");
boolean b = scan.nextBoolean();
System.out.println(b);
System.out.println("enter some float data");
float f = scan.nextFloat();
System.out.println(f);
}
}
--------------
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("enter some string value");
String s1 = scan.next();
System.out.println(s1);
scan.nextLine();
System.out.println("enter some string value");
String s = scan.nextLine();
System.out.println(s);
}
}
Note: In the above program, if we are not
using obj.nextLine() syntax, then we are unable to read more words by using second nextLine() method. The reasong is next() will read only collection of characters after that if we click enter button, that enter button value will be read by nextLine().
so we are unable type some words.
to overcome the above problem we need to use one extra nextLine() syntax in our program.
import java.util.Scanner;
public class ArrayDemo1 {
public static void main(String[] args) {
int a[] = new int[5];
Scanner scan = new Scanner(System.in);
System.out.println("Reading the valued from keyboard");
for(int i = 0; i < a.length; i = i+1){
a[i] = scan.nextInt();
}
System.out.println("printing the values of a array");
for(int i = 0; i< a.length; i++){
System.out.println(a[i]);
}
}
}
//copy the elements from one array to another
public class ArrayDemo1 {
public static void main(String[] args) {
int a [] = {11,22,33,44,55};
int b [] = new int[5];
for(int i =0; i < a.length ; i++){
//reading the elements from a array
//b[i] = a[i];
for(int j =i; j<i+1; j++ ){
//placing elements into b array
b[j] = a[i];
}
}
System.out.println("printing b array elements");
for(int i =0;i<b.length;i++){
System.out.println(b[i]);
}
}
}
Java provides one predefine method for copy the elements from one array to another array.
That is arrayCopy(). It is static method, which is available at java.lang.System.
System.arrayCopy(a,0,b,0,5);
a--->source array
0-->from which index position we are reading the elemen ts
from source array
b--> destination array
0-->In which index position, we are going to be place the elements in destination array
5-->Number of elements.
Double dimentional array:
import java.util.Scanner;
public class ArrayDemo1 {
public static void main(String[] args) {
int a[][] = {{11,22,33},{44,55,66}};
for(int i =0;i<2 ; i++){//rows
for(int j=0;j<3;j++){//columns
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}import java.util.Scanner;
public class ArrayDemo1 {
public static void main(String[] args) {
int a[][] = new int[3][3];
System.out.println("enter some data for 3*3 matrix");
Scanner scan = new Scanner(System.in);
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
a[i][j] = scan.nextInt();
}
}
System.out.println("data from a array");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
}
}
}
Difference between char array to remaining data type arrays:
If we are printing char array reference variable we will get data. if we are print remaining data type array variables we will reference.(classname@memory)
public class ArrayDemo {
public static void main(String[] ram) {
char c[]={'1','a','o'};
System.out.println(c);
int a[] = {11,22,33,444};
System.out.println(a);
boolean b[] = {false,true,true,false};
System.out.println(b);
}
}
-----------------
public class ArrayDemo {
public static void main(String[] ram) {
byte b[] = new byte[2];
System.out.println(b.getClass().getName());
short s[] = new short[3];
System.out.println(s.getClass().getName());
int i[] = new int[2];
System.out.println(i.getClass().getName());
float f[] = new float[3];
System.out.println(f.getClass().getName());
double d[] = new double[7];
System.out.println(d.getClass().getName());
char c[] = new char[1];
System.out.println(c.getClass().getName());
System.out.println("****************");
long l[] = new long[2];
System.out.println(l.getClass().getName());
boolean b1[] = new boolean[2];
System.out.println(b1.getClass().getName());
}
}
Anonymous arrays:
An array, which does not having any external reference, that array is called annonymous array.
ex: new int[]{11,12,13,14,15};
With the help of anonymous array we can reuse the memory.
With the help of anonymous array we can interact with the data only one time.
public class ArrayDemo {
static void m1(int x[]){
for(int i=0;i<x.length;i++){
System.out.println(x[i]);
}
System.out.println("***********");
}
public static void main(String[] ram) {
//reference array
int a[] = new int[]{11,22,33,44};
m1(a);
//annonymous array
m1(new int[]{111,222,333,444});
}
}
Multidimensional Array:
---------------------------
import java.util.Scanner;
public class ArrayDemo {
public static void main(String[] ram) {
int a[][][] = new int[2][2][3];
Scanner scan = new Scanner(System.in);
System.out.println("please enter integer" +
" values for 2*2*3 matrix");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<3;k++){
a[i][j][k]= scan.nextInt();
}
}
}
System.out.println("elements of a array");
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
for(int k=0;k<3;k++){
System.out.print(a[i][j][k]+" ");
}
System.out.println();
}
System.out.println();
}
}
}
Jagged array:
if we want to save the memory while inserting the data into the array, we can go for jagged array.
Scanner scan = new Scanner(System.in);
int a[][] = new int[4][];
a[0] = new int[1];
a[1] = new int[2];
a[2] = new int[3];
a[3] = new int[4];
System.out.println("enter elements for jagged array");
for(int i=0;i<4;i++){//rows
for(int j=0;j<i+1;j++){
a[i][j] = scan.nextInt();
}
}
System.out.println("a array elements");
for(int i=0;i<4;i++){//rows
for(int j=0;j<i+1;j++){
System.out.print(a[i][j]+" ");
}System.out.println();
}
Variable:
Variable is a named memory location, which can be hold the data temporarly.
The data can be change from one statement to another statement.
int a = 10;
a = a*20;
a=a-100;
syntax:
AccessModifer modifer modifier datatype variable_name = value;
Example: public static final int a = 10;
Variable can be classified as two types
1. Primitive Variables.
2. Referenced variables.
Primitive variable: A variable,which can be declared with the help of primitive datatype is called primitive variable.
int x;
float y;
Referenced variables:
A variable which can be declared with the help of referenced datatype is called referenced variable.
int x[];
Student s;
Runnable r;
ArrayList al;
Primitive Variable:
Variable can be categorized in two types.
1. Class level variable
2. Local variable/method level variable.
Class Level Variable: A variable, which is located at class scope those variable are called class level variable.
These are two types.
a. static variable
b. non-static/instance variable
a.static variables:
The variable which have static keyword in its declaration is called static variable.
static int a = 111;
In java data is clasified into two types.
sharabale data
non-sharable data.
sharable data can be represents with "static" keyword.
In java we can allocate the memory in two ways
1.static
2.new
non-sharable data comes under "new" keyword(object).
Before executing main method some static data is going to be executed.
static data means
static variables
static blocks
static methods.
Before executing main() all static variables and static blocks will be executed, but methods are not executed automatically, if we want to execute we should call explicitly.
All the static variables having same priority, the execution priority is dependupon the way we mention in the program from top to bottom.
variables execution means placing the data into memory.
All the static variables are memorized into two phases.
1.Loading phase.
2.Execution/initialization phase.
LoadingPhase: In this phase all the variables are memorized with default values. These default values will be placed by one special component in jvm that is "preparer".
Onec LoadingPhase is completed of all variables, then jvm control will goes to initialization phase.
Initialization phase:
In this phase all the default values will be replace with original values/actual values. these original values will be given by one of the special component of jvm that is "initializer".
static int a = 111;
initially a value is 0 in the loading phase
after 0 will be replaced with 111 in the initialization phase.
public class StaticVariableDemo {
static int m2(){
System.out.println(b);
return 222;
}
static int a = m1();
public static void main(String[] args) {
System.out.println("main method");
System.out.println(a);
System.out.println(b);
}
static int m1(){
System.out.println(a);
return 111;
}
static int b = m2();
}
Accessing the static variable:
We have three ways to access the static variables.
1. Class name
2. Directly (by variable name)
3. By Object or reference.
Note: If we want to call any otherclass static variable we have only two ways
1.classname
2. object or reference.
we cannot call other class static variable directly.
class A{
static int b = 222;
}
public class StaticVariableDemo {
static int a = 111;
public static void main(String[] args) {
System.out.println("main method");
int i = StaticVariableDemo.a;
System.out.println(i);
System.out.println(StaticVariableDemo.a);
int j = A.b;
System.out.println(j);
System.out.println(A.b);
System.out.println("****************");
int k = a;
System.out.println(k);
System.out.println(a);
//System.out.println(b);
System.out.println("***************");
StaticVariableDemo sd = new StaticVariableDemo();
System.out.println(sd.a);
System.out.println(new StaticVariableDemo().a);
}
}
Note: static data is sharable data between Objects.
static data having only one memory location.
That memory location can be sharable by all the
objects in the application.
If anyone object is updating the static data, that updated data will be effected to other objects also.
static block:
Block means group of statements.
A block which contains only static keyword, that block is called static block.
Syntax: static{
}
It is used for executing the common logic for all objects before main method. That type of code, we should be writing in the static block.
To initialize the static variables.
All the static blocks having same priority.
The execution of static blocks will be depend upon the way we mention in the program from top to bottom.
We cannot write one static block with in the another static block and also another method, constructor, interface, annotation.
class A{
static{}//valid
static{
static{}//invalid
}
void m1(){
static{}//invalid
}
}
interface I{
static{}//invalid
}
@interface AAA{
static{}//invalid
}
All the static variables and static blocks having same priority. The priority is depend upon the way we mention in the program from top to bottom.
If both static variables and blocks are available in single class, then all static variables loading phase will be first completed. after that both static variables and static blocks will be executed(initialization phase) in the order wise.
Loading phase: in this phase the static data is variable, then jvm provides memory,in that jvm will place default values.
If static data is block and method, then those heading will be read by the jvm and place into some memory.
Initialization phase: In the phase, the static data is variable, and then default values will be replaced with original values. If static data is block then automatically block will be executed. If static data is method then not executed, the reason is no method will be executed automatically except main.
After successfully completion of static variable, static blocks execution, then jvm will give chance to main method to execute.
Static data can be sharable between all the objects. If anyone objects is doing modification, that updated value effected to reaming objects also.
Note: All the static data are stored in Method area.
Non-static data:
Non-static data comes under
non-static variable
non-static blocks
non-static methods.
Non-static variable:
A variable which doesnot have any static keyword in its declaration is called non-static variable.
Ex: int a = 111;
Non-static is not sharable between any two objects.
If one object is doing modification, that updated value not effected to remaing objects.
all the non-static data and objects are stored in the heap area.
Whenever we create an object jvm will do the following things.
static data is loading or memorized only one time for entire application.
As many objects we create in our program, those many times non-static data memorized/loaded.
Loading phase: if data is non-static variable, then JVM blindly provides memory and place the default values.
If data is non-static block, JVM will read only block heading.
If data is non-static method, JVM will read only method heading.
Initialization phase: If data is non-static variable, then JVM replace the default values with original/actual values.
If data is non-static block then block will be executed by JVM.
If data is non-static method, not executed.
All the non-static variables are having same priority, the execution of variables is depend upon, the way we mention in the program from top to bottom.
public class Nonstatic {
int a = m1();
int m2(){
System.out.println(b);
System.out.println("m2 method");
return 222;
}
public static void main(String[] args) {
System.out.println("main method");
Nonstatic ns = new Nonstatic();
}
int m1(){
System.out.println(a);
System.out.println("m1 method");
return 111;
}
int b = m2();
}
Note: static int a = m1();
"static int a" is comes
under declaration part.
The space between equal operator and semicolon is called initialization part.
If any method calling syntax is available in initialization part, that must be carry the information from called area to calling area.
A method which is carrying the information is called non-void method.
Information must be same or compatible with variable data type.
If method having return type, that method must be have return statement with value.
Again value must be compatible with return type.
Accessing the non-static variable:
We have two ways to access the non-static data
1.by directly.
2.by object or reference.
//non-static variable we cannot call from static area directly. We should always by using reference or object.
//if we want to call any other class non-static data, we have only one way. That is object or reference.
class B{
int b = 222;
}
public class Nonstatic {
int a = 111;
void m1(){
System.out.println("m1 method");
System.out.println(a);
}
public static void main(String[] args) {
System.out.println("main method");
Nonstatic ns = new Nonstatic();
System.out.println(ns.a);
System.out.println(new Nonstatic().a);
ns.m1();
//System.out.println(a);
//System.out.println(b);
B obj = new B();
System.out.println(obj.b);
System.out.println(new B().b);
}
}
Non-static data is non-sharable between objects. If anyone object is doing modification those modification are not effected to other objects the reason every object have its own memory. If we are doing modification on one memory those are not effected to another memory.
public class C {
int a = 111;
int b = 222;
public static void main(String[] args) {
C obj1 = new C();
System.out.println(obj1.a);
System.out.println(obj1.b);
System.out.println("---------");
C obj2 = new C();
System.out.println(obj2.a);
System.out.println(obj2.b);
System.out.println("---------");
obj1.a = 888;
System.out.println(obj1.a);
System.out.println(obj1.b);
System.out.println("---------");
obj2.a = 999;
System.out.println(obj2.a);
System.out.println(obj2.b);
}
}
Non-static Blocks:
A block which does not contains static keyword in its declaration is called non-static block.
All the non-static blocks having same priority.
The execution priority is depend upon, the way we mention in the program from top to bottom.
public class C {
{
System.out.println("non-static block 1");
}
{
System.out.println("non-static block 3");
}
public static void main(String[] args){
System.out.println("main method");
C obj = new C();
}
{
System.out.println("non-static block 2");
}
}
public class C {
static {
System.out.println("static block 1");
}
int a = m1();
{
System.out.println("non-static block 1");
}
static int c = m3();
int m1(){
System.out.println(a);
System.out.println("m1 method");
return 2222;
}
static int m3(){
System.out.println(c);
System.out.println("m3 method");
return 4444;
}
{
System.out.println("non-static block 3");
}
int b = m2();
public static void main(String[] args) {
System.out.println("main method");
C obj = new C();
System.out.println(obj.a);
System.out.println(obj.b);
}
{
System.out.println("non-static block 2");
}
int m2(){
System.out.println(b);
System.out.println("m2 method");
return 3333;
}
}
Valid statement:
{
{
}
}
static{
{
}
}
C(){
{
}
}
interface D{
//{}
}
enum E{
;
{
}
}
abstract class F{
{
}
}
@interface I{
//{}
}
public class C {
{
System.out.println("non-static block 1");
{
System.out.println("non-static inner block 1 ");
}
}
static{
System.out.println("static block 1");
{
System.out.println("non-static inner block2");
}
}
C(){
System.out.println("constructor");
{
System.out.println("non-static inner block 3");
}
}
static void m2(){
{
System.out.println("m2 method non-static block");
}
}
public static void main(String[] args) {
{
System.out.println("main method non-static block");
}
System.out.println("mainmethod");
C obj = new C();
}
}
Non-static block we can write with in the class, enum, abstract class, staticblock, static method, non-static method, constructor but we cannot write in interface and annotation.
Static block we can write only within his class, enum, abstract class.
Q) Difference between static and new keyword?
static:
1)It is a keyword, is used allocate the memory for static data.
2) static data means, static ariable,blocks, methods.
3) static data is sharable data
4) static data having only one memory
5) only one time static data is loaded.
6) If any one object is doing updation on static data, that updated value will be effected to remaining objects.
7) Meanwhile of class loading static-data is loaded by the jvm.
8) Static data can be acces with in 3 ways.
directly,classname,object or reference.
9)static data we can call any where in the program.
10) other class static can be access only in two ways. a.by classname
b.by object or reference
new:
1)It is keyword is used to allocate the memory for non-static data.
2)non-static data means, non-static variables, non-static blocks , non-staic methods.
we have one more name to non-static data that is instance data.
3)non-static data is non-sharable data.
4)non-static data having multiple memory.
5)as many object we created those many times non-static data is going to be loaded.
6)If any one object is doing updation on non-static data, that updated data/value will not be effected to remaining objects.
7)Meanwhile of object creation non-static data executed.
8)non-static can be acces in two ways.
by using directly,object or reference.
9)non-static we cannot call directly in static area.
10) other class non-static can be access only in one way.
a.by object or reference
nsb sb constructor
throw no no yes
return no no yes
returnwivale no no no
Local variable: A variable, which is resides or locate within the parameter of an method, constructor and body of method,constructor, block(static,non-static) is called local variable.
ex:
void m1(int x){
int y;
}
{
int z;
}
static{
int l;
}
class A{
A(int n){
int m;
}
}
x,y,z,l,m,n all are local variables.
local variables always either default or final.
void m1(){
int a; //valid
final int b; //valid
private int x; //invalid
public int y; //invalid
protected int z; //invalid
static int l; //invalid
transient int m; //invalid
}
Local variables may be default or final.
there is no default values for local variables.
Before using local variables we should be initialize.
if we are using local variables without initialization, we will get one compiletime error.
Same variable name we can declare in different scopes.
final keyword we can be applied on variables, method, classes.
final variables:
A variable which have final keyword in its declaration is called final variable.
final keyword we can be applied on top of class level and local variables also.
class level final variable must be initialized meanwhile of declaration.
local level final variable must be initialized before using that variable.
final variable can be use more than one time but we can not update/change the data.
If we are trying to change we will get CE.
final class Student{
String sname="suji";
}
public class FinalVariable {
final int a = m1();
//final int b; //class level final variable must be
//intialize mean while of declaration.
int m1(){
System.out.println(a);
System.out.println("m1 method");
return 111;
}
final void m2(){
System.out.println("m2 method");
}
static void m3(final int x){
System.out.println(x);
//x=x+1;
}
public static void main(String[] args) {
FinalVariable fv = new FinalVariable();
System.out.println(fv.a);
//fv.a = fv.a*2;
int c = fv.a*2;
final int d;
d=888;
System.out.println(d);
Student s = new Student();
System.out.println(s.sname);
s.sname="ram";
System.out.println(s.sname);
fv.m2();
}
}
Referenced Variables:
Referenced variables are categorized into two types.
1.Class level referenced variable
2. Local referenced variable.
Class level referenced variable:
A referenced vairble available at class level is called CLRV.
It has been categorized into two types
a. static referenced variable
b. non-static/instance referenced variable.
class Student{
Student s = new Student();
static Student s1 = new Student();
}
Local referneced variable:
A variables which is available at block or method level is called LRV.
ex:
class Student(){
psv main(-){
Student s = new Student();
}
}
Arrays can hold more than one value with same type, but it is unable hold different type of data , to overcome this problem then we can go for another referenced data type is called "class".
Class is an imaginary thing, which is not existed in the real world.
Class is a model.
Class is a model for creating objects. Means the properties and actions of the objects are written in the class.
Properties are represented by variables.
Actions of the objects are represented by methods.
So a class contains variables and methods.
The same variable and methods are also available in the objects because they are created from the class.
These variables are also called as instances.
How can we provide functionality to a class?
A) By creating an object.
Object:
Whatever the functionalities the class having, we should get those functionalities by creating object only.
Creating an object is nothing but, allocating memory, necessary to store the actual data of the variable.
By creating the object only, we can give the memory to name, age variables
class def.: It is a java element, it can be hold both static and non-static variables, static and non-static method, static and non-static block, both static and non-static innerclass,interface, enum.
Object Creation:
In java we have 5 ways to create an object.
1.new keyword
2.clone()
3.newInstance()
4.Factory methods.
a.static factory methods
b.non-static factory methods
5. Deserialization.
1. new Keyword:
in java we can create two types of objects.
a. referenced object.
b. un-referenced object.
Referenced object creation:
classname reference_name = new classname();
When ever jvm see the new keyword blindly provides new memory.
With the helpof referenced object creation we can reuse the memory more than one time.
Unreferenced object cretion:
new classname();
With help of unreferenced object we can use the memory only one time.
With the help of object we can communicate with both static and non-static data also.
class Student {
int a = 111;
int b = 222;
psv main(){
Student s1 = new Student();
new Student();
}
}
Difference between object and reference:
Object means allocating memeory.
Reference means holding the memory, which is generated by object.
But both object and reference will point to same memory.
With the help of reference, we can use the same memory more than one time.
With the help of object, we can use the memory only one time.
public class SRV {
int x = 100;
int y = 200;
public static void main(String[] args) {
SRV obj = new SRV();
System.out.println(obj.x);
System.out.println(obj.y);
new SRV();
int a = new SRV().x;
int b = new SRV().y;
System.out.println(new SRV().x);
System.out.println(new SRV().y);
}
}
public class SRV {
SRV obj = new SRV();
public static void main(String[] args) {
SRV obj1 = new SRV();
}
/*static SRV obj = new SRV();
public static void main(String[] args) {
SRV obj1 = new SRV();
System.out.println(obj1);
System.out.println(obj);
}*/
}
public class SRV {
int a = 111;
static int b = 222;
public static void main(String[] args) {
int a = 333;
int b = 444;
SRV obj = new SRV();
System.out.println(a);
System.out.println(obj.a);
System.out.println(obj.b);
System.out.println(b);
}
}
JVM always gives priority to local data.
if we are calling variable directly first compiler will with in the local area(block), if not then it will goto class level.
System.out.println (obj.a) then compiler directly check in object are(heap area), if available that a value bind to obj, then jvm will print a value in runtime.
If not compiler will check in the method area/static is
if available compiler will bind the data to obj, then jvm will print a value in runtime.
if not compile time error.
public class NSD {
static int b = 333;
int a = 111;
//static int a = 222;
//same we cannot be define more than one time
//in the same scope
public static void main(String[] args) {
int a = 222;
System.out.println(a);(1)
new NSD();//no use
System.out.println(new NSD().a);(2)
NSD ns = new NSD();
System.out.println(ns.a);(3)
System.out.println(ns.b);(4)
System.out.println(NSD.b);(5)
System.out.println(b);(6)
}
}
Note:
in step 1) jvm will give priority to local data first
if data is not available in block level(jsa) then controle goes to method area.
2)jvm control directly goes to heap area if not available then goes to method area
3) same as 2
4)same as 2
5) same controle directly goes to method area
6) jvm controle goes to jsa, if not available then control to goes to method area
class Student1{
int sid = 111;
String sname = "suji";
}
public class SRV {
public static void main(String[] args) {
Student1 s1 = new Student1();
Student1 s2 = new Student1();
Student1 s3 = new Student1();
System.out.println("s1: "+s1.sid +"...."+s1.sname);
System.out.println("s2: "+s2.sid +"...."+s2.sname);
System.out.println("s3: "+s3.sid +"...."+s3.sname);
}
}
Output:
s1: 111....suji
s2: 111....suji
s3: 111....suji
In above program we are getting same id,name for all the students, it is not possible in real time, to avoid this drawback we should provides different values for different students. If we want to achieve this requirement then we can go for constructors.
Constructors:
Constructors are special blocks in class level, to initialize the non-static varaibles.
Constructors are used to creating object.
Constructors are class level blocks.
Constructor name is same as class name.
After successfully executing of all non-static variables, blocks then constructors will be executed.
Once constructor is successfully executed, then we can say this, our object is successfully initialized.
Constructors are plays major role in object creation.
In constructor block we can write throws keyword and return statement without value. But we cannot write return statement with value.
Without constructor we cannot create object for a class "with new keyword".
Constructors are three types.
a. default constructor
b. zero argument/non-parameterized constructor
c. parameterized/argumented constructor
Default constructor:
If we are not specify any constructor in our class by default compiler will provide one constructor with zero parameters is called default constructor.
In that default constructor compiler will provides one non-static variable that is "super()".
ex: class A{
}
javac A.java
javap A
class A extends java.lang.Object{
A(){
super();
}
}
javap command is used to check the .class files information.
javap command always needs fullyqualified name(packagename + classname/interfacename/ enum/abstract class/annotaion).
If our class is public compiler generated constructor also public.
If our class is default compiler generated constructor also default.
we cannot write protected, private, static, native, volatile, transient, synchronized modifiers infront of outer class name.
we can write only default,public,final,abstract, strictfp in frontof the outer class names.
Comments
Post a Comment