0% found this document useful (0 votes)
78 views

Introduction

This document provides an overview of the Java programming language. It discusses that Java was created by James Gosling at Sun Microsystems in 1995 under the name Oak and was later renamed to Java. It notes some key facts about Java including that it is an open source language that runs on multiple operating systems and its extensions include .java, .class, and .jar files. It also discusses some of Java's uses like developing web applications and desktop applications and how over 3 billion devices run on Java.

Uploaded by

Suvendu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Introduction

This document provides an overview of the Java programming language. It discusses that Java was created by James Gosling at Sun Microsystems in 1995 under the name Oak and was later renamed to Java. It notes some key facts about Java including that it is an open source language that runs on multiple operating systems and its extensions include .java, .class, and .jar files. It also discusses some of Java's uses like developing web applications and desktop applications and how over 3 billion devices run on Java.

Uploaded by

Suvendu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

JAVA introduction:-

Author : James Gosling

Vendor : Sun Micro System

Project name : Green Project

Type : open source & free software

Initial Name : OAK language

Present Name : java

Extensions : .java & .class & .jar

Initial version : jdk 1.0 (java development kit)

Present version : java 7 2011

Operating System : multi Operating System

Implementation Lang : c, cpp……

Symbol : coffee cup with saucer

Objective : To develop web applications

SUN : Stanford Universally Network

Slogan/Motto : WORA(write once run anywhere)

Ex:-

Class Test
{
Public static void main (String [] args)
{
System.out.println (“welcome to java language”);
}
}

Compilation :- javac FileName.java


Execution :- java Class Name
Output :- welcome to java language

3|Page
Importance of core java:-

According to the SUN 3 billion devices run on the java language only.

1) Java is used to develop Desktop Applications such as MediaPlayer,Antivirus etc.


2) Java is Used to Develop Web Applications such as durgajobs.com, irctc.co.in etc.
3) Java is Used to Develop Enterprise Application such as Banking applications.
4) Java is Used to Develop Mobile Applications.
5) Java is Used to Develop Embedded System.
6) Java is Used to Develop SmartCards.
7) Java is Used to Develop Robotics.
8) Java is used to Develop Games etc.

Technologies Depends on Core java:-

android
Adv java

struts Core java Cloud Coputing

spring Selenium Testing

JAVA VERSIONS:-
Java Alpha & beta : 1995

JDK 1.0 : 1996

JDK1.1 : 1997

J2SE 1.2 : 1998

J2SE 1.3 : 2000

J2SE 1.4 : 2002

J2SE 1.5 : 2004

JAVA SE 6 : 2006

JAVA SE 7 : 2011

4|Page
C –language:-

Author : Dennis Ritchie

Implementation Languages : BCPL, ALGOL, FORTRAN……

Extensions : .c & .h

Released in : 1972

Ex:-
#include<stdio.h>
Void main()
{
Printf(“hello Students”);
}

Compilation :- alt+f5
Execution :- ctrl+f9
Output :- hello Students

CPP –language:-

Author : Bjarne Stroustrup

Implementation Languages : c

Extensions : .cpp & .h

Released in : 1983

Initial Name : C with Classes

Prasent Name : C++(c plus plus)

Ex:-
#include<iostream.h>
Void main()
{
Cout<<“hello CVRGU”;
}
Compilation :- alt+f5
Execution :- ctrl+f9
Output :- hello CVRGU

5|Page
Parts of the java language:-
As per the Ameerpet standard the java language is divided into 2 types
a. Core java
b. Adv java

As per the sun micro system standard the java language is divided into three types.
1) J2SE/JSE(java 2 standard edition)
2) J2EE/JEE(java 2 enterprise edition)
3) J2ME/JME(java 2 micro edition)

J2SE:-
By using j2se we are able to develop the standalone applications.
Ex:- notepad, WordPad, paint, Google Talk………..etc

Standalone applications:-
1) Standalone applications are the java applications which don’t need the client server
architecture.
2) The standalone applications applicable for the only one desktop hence it is called
desktop applications or window based applications.
3) For the standalone applications doesn’t need internet connections.
4) It is a local application it doesn’t need any other external application support.
5) This type of the applications we can launch by using the command line or by using
the executable jar.

Client Database
J2EE:-
By using j2ee we are able to develop the web based applications.
Ex:- Gmail, yahoo mail, bank, reservation…………etc

Web-applications:-
1) Web applications are the java applications which needs client and server concept.
2) Web applications must need the internet connections to access the application.
3) The application which is present in the internet is called the web application.
4) Web application can be launched by using HTTP driven. HTTP request sent to the
Servlet present in the server side.

6|Page
Web-application architecture:-

Client server database

Html request
Css (java)
Jsp (.net) Hibernate
(php) Used to
velocity
response Jdbc store the
data.

Client:-
The person who is sending the request is called client. All web browsers come under the clients.
Ex:- InternetExploral, MozillaFrefox, opera………..etc
Server:-
The server contains the applications. The main purpose of the server is
a. It will contain the application.
b. Take the request from the client.
c. Based on the taken request it will identify the project resource and execute that project
resource.
d. By executing the project some response will be generated that response is dispatched to the
client browser.
Ex:- Tomcat,GlassFish,WebLogic,JBOSS,WebSphere………..etc
DataBase:-
DataBase is used to store the details like client details, application details, registration
details……etc.
Ex:- Oracle,MySql………..etc
J2ME:-
By using j2me we are able to develop the applications that applications only run on mobile
devices.
As a software engineer we must know these technologies:-
HTML(Hyper Text Markup Language):-
It is used for web pages designing. Introduced by World Wide Web Consortium and developed
by Tim Berners-Lee

Old new

7|Page
JavaScript(JS):-
It is designed by Brendan Eich at NetScape Communications Corporation in 1995.it is used to
validate the forms.
Java:-
Developed by James Gosling at Sun Micro Systems in 1996 used to develop particular for client-server
web applications. Now it is merged into Oracle Corporation.

.net:-
Developed by Microsoft peoples in 2002 and it is used to develop the we based applications.

PHP(Hyper Text Preprocessor):-


It is a server side programming language used to develop the server side applications(web
applications)and developed by Rasmus Lerdorf in 1995.

Oracle:-
It is a data base used to store the data permanently. Developed by oracle people in 1977.

8|Page
Mr.Ratan

Android:-
It is a Linux based mobile phone operating system used to develop the mobile applications that
runs only on mobile devices.

Server side techmologies:-(servlets,structs,spring,php,.net)


By using server side technologies we are able to prepare the applications these application only
run on server side.
Servlets vs structs:-
Servlets is a technology used to develop the server side application and structs is a frame work it
developed on the basis of the servelts.
Jdbc vs hibernate:-
Jdbc and hibernate is used to provide the connection between java application and data base.
Jdbc is a technology and hibernate is a framework it is developed on the basis of the jdbc.
Frame work:-
Frame is a semi implemented component working with the frame works is very seay.

Technology:-
1. J2SE
2. J2EE
3. J2ME

Frame works:-
1. Struts
2. Spring
3. Hibernate
Servers:-
1. Tomcat
2. Glassfish
3. Jboss
4. Weblogic
5. Websphere……………
IDE(integrated development environment):-
1. Eclips
2. Myeclips
3. Netbeans
4. Jdeveloper…………………
Database :-
Oracle Mysql……………..

9|Page
Difference between
C-lang Cpp-lang Java -lang

1) The program execution The program execution starts The program execution starts
starts from main method from main method called by from main method called by
and main method is called by operating system.
Operating system. JVM(java virtual machile).

In the cpp language the In the java language the


2) In the c-language the
predefined is maintained in predefined is maintained in
predefined support is
the form of header files. the form of packages.
maintained in the form of
Ex:- iostream.h Ex:- java.lang java.io
header files
Ex:- stdio.h,conio.h java.net java.awt

The header files contains


3) the header files contains The packages contains
predefined functions. predefined classes.
predefined functions.
Ex:- cout,cin….
Ex:- printf,scanf….. Ex:- String,System

To make available
4) to make available To make available
predefined support into our
predefined support into our predefined support into our
program we have to use
program we have to use program we have to use
#include statement.
#include statement. import statement.
Ex:- #include<iostream>
Ex:- #include<stdio.h> Ex:- import java.lang.*;

Allocation :constructor
5) memory allocation: malloc Allocation :constructor
Deallocation:destructors
Memory deallocation: free Deallocation:Garbage
collector(part of the jvm)
Irrespective of any os
6) size of the data types are
Int -4
varied from operating system Irrespective of any os
Char-2
to the operating system. Int -4
16-bit int -2bytes char- 1byte Char-2
32-bit int -4bytes char – 2 bytes

7) to print some statements To print the statements we To print the statements we


into the console we have to have to use “cout” have to use
use “printf” function. “System.out.println”

8) C is dynamic language the Cpp is static language the Java is dynamic language the
memory is allocated at memory is allocated at memory is allocated at
compilation time. compilation time. runtime time

10 | P a g e
c-language:-
c-language Dennis Ritchie void main() (program starting point)

headerfiles stdio.h,conio.h printf(“ratan”);

functions printf,scanf…..

cpp-language:-

cpp-language Bjarne Stroustrup void main() (program starting point)

headerfiles iostream.h cout<<”ratan”;

functions cout,cin….

java-language:-
java-language james gosling public static void main(String[] args)
(program starting point)
packages java.lang System.out.println(“ratan”);

classes & interfaces System,String……..

methods & variables length(),charAt(),concat()…

JAVA Features:-
1. Simple
2. Object Oriented
3. Platform Independent
4. Architectural Neutral
5. Portable
6. Robust
7. Secure
8. Dynamic
9. Distributed
10. Multithread
11. Interpretive
12. High Performance

11 | P a g e
1. Simple:-
Java is a simple programming language because:
 Java technology has eliminated all the difficult and confusion oriented
concepts like pointers, multiple inheritance in the java language.
 The c,cpp syntaxes easy to understand and easy to write. Java maintains
C and CPP syntax mainly hence java is simple language.
 Java tech takes less time to compile and execute the program.
2. Object Oriented:-
Java is object oriented technology because to represent total data in the form of object.
By using object reference we are calling all the methods, variables which is present in
that class.
Class Test
{ Test t=new Test(); Class data
Class data; t
}
The total java language is dependent on object only hence we can say java is a object
oriented technology.
3. Platform Independent :-
Compile the Java program on one OS (operating system) that compiled file can execute
in any OS(operating system) is called Platform Independent Nature. The java is
platform independent language. The java applications allows its applications
compilation one operating system that compiled (.class) files can be executed in any
operating system.

exe
Test.class JVM windows
Test.java
exe
JVM linux
Javac
JVM
exe
JVM macos

exe solaris
source file compilation JVM understandable file output console

12 | P a g e
4. Architectural Neutral:-
Java tech applications compiled in one Architecture (hardware----RAM, Hard Disk) and
that Compiled program runs on any hardware architecture(hardware) is called
Architectural Neutral.
5. Portable:-
In Java tech the applications are compiled and executed in any OS(operating system)
and any Architecture(hardware) hence we can say java is a portable language.
6. Robust:-
Any technology if it is good at two main areas it is said to be ROBUST
1 Exception Handling
2 Memory Allocation
JAVA is Robust because
a. JAVA is having very good predefined Exception Handling mechanism whenever we
are getting exception we are having meaning full information.
b. JAVA is having very good memory management system that is Dynamic Memory (at
runtime the memory is allocated) Allocation which allocates and deallocates
memory for objects at runtime.
7. Secure:-
To provide implicit security Java provide one component inside JVM called Security
Manager.
To provide explicit security for the Java applications we are having very good predefined
library in the form of java.Security.package.
Web security for web applications we are having JAAS(Java Authentication and
Authorization Services) for distributed applications.
8. Dynamic:-
Java is dynamic technology it follows dynamic memory allocation(at runtime the
memory is allocated) and dynamic loading to perform the operations.
9. Distributed:-
By using JAVA technology we are preparing standalone applications and Distributed
applications.
Standalone applications are java applications it doesn’t need client server architecture.
web applications are java applications it need client server architecture.
Distributed applications are the applications the project code is distributed in multiple
number of jvm’s.
10. Multithreaded: -
Thread is a light weight process and a small task in large program.

13 | P a g e
If any tech allows executing single thread at a time such type of technologies is called
single threaded technology.
If any technology allows creating and executing more than one thread called as
Multithreaded technology called JAVA.
11. Interpretive:-
JAVA tech is both Interpretive and Completive by using Interpretator we are converting
source code into byte code and the interpretator is a part of JVM.

12. High Performance:-


If any technology having features like Robust, Security, Platform Independent, Dynamic
and so on then that technology is high performance.

Install the software and set the path :-


Download the software from internet based on your operating system. The software is different
from 32-bit operating and 64-bit operating system.

To download the software open the fallowing web site.


http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html

for 32-bit operating system please click on


Windows x86 :- 32- bit operating system

for 64-bit operating system please click on


Windows x64 :- 64-bit operating system

After installing the software the java folder is available in the fallowing location
Local Disk c: ------program Files--------java----jdk(java development kit),jre(java
runtime environment)
To check whether the java is installed in your system or not go to the command prompt. To
open the command prompt
Start ----------run------open: cmd-----ok
Command prompt is opened.
In the command prompt type :- javac
‘javac’ is not recognized is an internal or external command, operable program or batch
file.
Whenever we are getting above information at that moment the java is installed but the java is
not working properly.
C:/>javac
Whenever we are typing javac command on the command prompt
1) Operating system will pickup javac command search it in the internal operating system
calls. The javac not available in the internal command list .

14 | P a g e
2) Then operating system goes to environmental variables and check is there any path is
sets or not. up to now we are not setting any path. So operating system don’t know
anything about javac command Because of this reason we are getting error message.
Hence we have to environmental variables. The main aim of the setting environmental
variable is to make available the fallowing commands javac,java,javap (softwares) to the
operating system.
To set the environmental variable:-
My Computer (right click on that) ---->properties----->Advanced--->Environment Variables---->

User variables--new---->variable name : Path


Variable value : C:\programfiles\java\jdk1.6.0_11\bin;.;
-------ok------ok
Now the java is working good in your system. open the command prompt to check once
C:>javac---------now list of commands will be displayed

Steps to Design a First Application:-


Step 1 :- Select an Editor.

Step2:- Write a Program & save the program.

Step3:- Compile the program.

Step4:- Execute the program.

Step1:- Select an Editor

Editor is a tool or software it will provide very good environment to type the java application

Ex:- Ameerpet Editors-----Notepad, Notepad++ ,Edit Plus---etc

Hi-Tech City Editors--- Eclipse, Myeclips, Net Beans----etc

Step 2:- Write the program and save the program

Write the java program based on the java API(Application Programming Interface) rule and
regulations .

Java is a case Sensitive Language while writing the program we have to take care about the case
(Alphabet symbols)

After writing the program we have to save the program while saving the program we have to consider
fallowing steps

Check whether the source file contain the public class or not

15 | P a g e
1. if the source file contain public class the name of the public class and the name of the
Source file must be same(publicClassName.java). Otherwise we are getting compilation
error.
2. if the source file does not contain any public class at that situation we can save the
source file with (anyName.java)

Step3:- Compile the program

To single source file


Ex:- Javac filename.java
Javac Test.java

The java compiler goes to Test.java file and it will search for syntactical error if the syntactical errors are
presented the java compiler raise compilation error if there is no syntactical errors are presented at
that situation the java compiler converts the .java files into the .class file.

Note:- the .class file generation totally based on the number of classes present in the source it is not
depending the number of classes present in the source file it is not depending on the name of
the file.
To compile multiple source files at a time
Javac *.java

Durga.java
Class A A.class
{
} B.class
Class B compilation
C.class
{
} Javac Durga.java
Class C
{
}

Step4:- Execute the program


Java class-name
Java Test
Whenever we are typing the Test class in the command prompt first it will search for the Test class if the
Test class is available then it will search for the Main method if the main method is there the program
execution starts from main method onwards.
The JVM will search for the .class file if the .class file is not available then JVM will raise an exception
Exception inn thread “main” java.lang.NoClassDefFoundError
The JVM will search for the .class file if the .class is available the JVM will search for the main method if
the main method is not available then the JVM will raise an Eception.
Exception in thread “main” java.lang.NoSuchMethodError: Main

16 | P a g e
JAVA ENVIRONMENT:- Java Sorce File (*.java)

Java Compiler (javac)

Java Byte Code File (*.class)

Java Virtual Machine (JVM)

Environment of the java programming development:-

First program development :-

17 | P a g e
Class Contains Five elements:-

Class Test
{
1. variables
2. methods
3. constructors
4. instance blocks
5. static blocks
}
TOKENS:-Smallest individual part in a java program is called Token. It is possible to provide any number
of spaces in between two tokens.

Ex:-Class Test

{
Public static void main(String[] args)
{ int a=10;
System.out.println(“java tokens”);
}
}
Tokens are---------class,test,{,”,[-----------------------------etc

Print() vs Println ():-


Print():-
Print is used to print the statement into the console and the control is available in the same line.
Ex:- System.out.print(“durgaSoftware”);
System.out.print(“core java”);
Output:-durgasoftwarecorejava
Println():-
In the println statement Print is used to print the statement into the console and ln represent
go to the new line now the control is available in the next line.
Ex:- System.out.println(“durgasoftware”);
System.out.println(“core java”);
Output: - durgasoftware
Core java

18 | P a g e
Identifiers:-
any name in the java program like variable name,class name,method name,interface name is called
identifier.
class Test Test-------identifier
{
void add() add-------identifier
{
int a=10; a----------identifiers
int b=20; b----------identifiers
}
};
Rules to declare identifiers:-
1. the java identifiers should not start with numbers,it may start with alphabet symbol and
underscore symbol and dollar symbol.
a. Int abc=10;-----valied
b. Int 2abc=20;----not valied
c. Int _abc=30;----valied
d. Int $abc=40;----valied
e. Int @abc=50;---not valied
2. The identifier will not contains symbols like
+ , - , . , @ , # , *………………….
3. The identifier should not duplicated.
class Test
{
void add()
{
int a=10;
int a=20; the identifier should not be duplicated.
}
};
4. In the java applications it is possible to declare all the predefined class names and predefined
interfaces names as a identifier. But it is not recamanded to use.

class Test
{
public static void main(String[] args)
{
int String=10; //predefind String class
int Serializable=20; //predified Seriaiable class
float Exception=10.2f; //predefined Exception class
System.out.println(String);
System.out.println(Serializable);
System.out.println(Exception);
}
};

19 | P a g e
JAVA NAMING CONVENSIONS:-
Java is a case sensitive language so the way of writing code is important.
1. All Java classes,Abstract classes and Interface names should start with uppercase letter ,if
any class contain more than one word every innerword also start with capital letters.
Ex: String
StringBuffer
FileInputStream
2. All java methods should start with lower case letters and if the method contains more than
one word every innerword should start with capital letters.
Ex :- post()
toString()
toUpperCase()
3. All java variables should start with lowercase letter and inner words start with uppercase
letter.
Ex:- pageContent
bodyContent
4. All java constant variables should be in uppercase letter.

Ex: MIN_PRIORITY
MAX_PRIORITY
NORM_PRIORITY
5. All java packages should start with lower case letters only.
Ex: java.awt
Java.io

NOTE:-
The coding standards are applicable for predefined library not for user defined library .But it is
recommended to fallow the coding standards for user defined library also.

JAVA COMMENTS :-
To provide the description about the program we have to use java comments.
There are 3 types of comments present in the java language.
1) Single line Comments:-
By using single line comments we are providing description about our program within a
single line.
Starts with…………….>// (double slash)
Syntax:- //description

2) Multi line Comments:-


This comment is used to provide description about our program in more than one line.
Syntax: - /*…………….line-1
……………..line-2
*/

20 | P a g e
3) Documentation Comments:-
This comment is used to provide description about our program in more than one page.
In general we are using document comment to prepare API kind of documents but it is not
sujastable.
Syntax: - /*…………….line-1
*……………..line-2
*………………line-3
*/
Ex:-/*project name:-green project
team size:- 6
team lead:- ratan
*/
class Test
{
//main method
public static void main(String[] args)
{
//printing statement
System.out.println("ratan");
}
};

21 | P a g e
Key words:-

Keywords Keywords Keywords for Keywords Keywords Keywords


for for for for for primitive
Modifier Exception data Types
Flow Handling Class Object
Control

Public If try Import New Byte

private else catch class instanceof short

protected switch finally interface super int

static break throw extends this long

abstract case throws package float

final default implements double

native for (5) (6) (4) char

volatile do boolean

synchronized while (8)

transient continue

strictfp (10) Unused keywords Metho level Reserved 1.5 version


literals keywords
(11)

goto Void true assert

const return false enum

(2) (2) null (2)

(3)

38 | P a g e
Data Types:-

1) Data types are used to represent the type of the variable and type of the expression.
2) Data types are used to specify the how much memory is allocated for variables.

Data type Size Range Default values

Byte 1 -128 to 127 0

short 2 -32768 to 32767 0

int 4 -2147483648 to 2147483647 0

long 8 -2`31 to 2`31-1 0

float 4 -3.4e38 to 3.4e308 0.0

double 8 -1.7e308 to 1.7e308 0.0

char 2 0 to 65535 Single space character

Boolean NA Not Applicable False

Syntax:- data-type name-of-variable=value/literal;


Ex:- int a=10;
Int--------Data Type
a----------variable name
=----------assignment
10--------constant value
; ----------statement terminator

Literals:-
Literal is a constant value assigned to the variables.
‘a’----------------char literal
10---------------integral literal
False-----------boolean literal
10.2345--------double literal

39 | P a g e
Floating point literal & double literal:-
By default the decimal point values represent double so if we want to assign the floating point
values to the variables we must attach the suffix F or f to the number. If we are not providing the
number we will get compilation error possible loss of precision.
double d=100.9898-------------good
float f=10.897--------------------compilation error(possible loss of precision)
float f=12345.67890f;---------good suffix with f
it is optionally to attach the d or D with double double value
double d=1234.5678;-------------good
double d=1234567.7654321d;-----good

Boolean literal:-
The Boolean values are true or alse.
boolean b=true;------good
Boolean b=0;-----------it’s working in c-lang but not in java
Char literal:-
A character literal is represented by a character in single quote.
Char ch=’a’;
Char ch1=’#’;
Char ch=’1’;
class Test
{
public static void main(String[] args)
{
char ch1='"';
System.out.println((int)ch1);
char ch2='\'';
System.out.println((int)ch2);
}
}
String literal:-
A string literal represented by group of character in double quotes.
String str=”ratan”;
class Test
{
public static void main(String[] args)
{
String str1="ratan";
System.out.println(str1+"soft");
System.out.println("durga"+"javahome");
}
}
Ex:-
byte+byte=int byte+short=int short+int=int byte+int=int byte+long=long
short+float=float long+float=float float+double=double String+int=String

40 | P a g e
There are two types of areas:-
1) Instance area
2) Static area
Instance area:-
void m1()
{
Instance Instance method
area

}
Static area:-
Static Void m1()
{

Static
area Static method

}
Static variables & methods accessing:-

Static variables/methods

Directly can access directly can access

Static area instance area

Instance variables/methods declaration:-

Instance variables/methods

Directly can access directly can’t access

(we have to create a object based on obj reference we


have to call that instance methods and variables)

Instance area cant accessed into static area

Two figures are heart of the java language

41 | P a g e
Types of variables:-

 Variables are used to store the values. By storing that values we are achieveing the
functionality of the project.
 While declaring variable we must specify the type of the variable by using data type’s concept.

In the java language we are having three types of variables


1. Local variables
2. Instance variables
3. Static variables
Local variables:-
a. The variables which are declare inside a method & inside a block & inside a constructor is called
local variables
b. The scope of local variables are inside a method or inside a constructor or inside a block.
c. We are able to use the local variable only inside the method or inside the constructor or inside
the block only.
Ex:-
class Test
{
public static void main(String[] args)
{
int a=10; Local variables
int b=20;
System.out.println(a+b);
}
}
Instance variables:-
1. The variables which are declare inside a class and outside of the methods is called instance
variables.
2. We are able to access instance variables only inside the class any number of methods.
class Test
{
int a=10;
int b=20;
void add()
{
System.out.println(a+b);
}
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a+t.b);
t.add();
}
}

42 | P a g e
3. Static variables:-
 The instance variables which are declared as a static modifier such type of
variables are called static variables.
 We are able to access static variables within the class any number of methods.
class Test
{
static int a=10;
static int b=20;
public static void main(String[] args)
{
System.out.println(a+b);
}
void add()
{
System.out.printl(a+b);
}
}
Calling of static variables:-
a. Directly possible.
b. By using class name possible.
c. By using reference variable possible.
class Test
{
static int x=100;
public static void main(String[] args)
{
//1-way(directly possible)
System.out.println(a);
//2-way(By using class name)
System.out.println(Test.a);
//3-way(By using reference variable)
Test t=new Test();
System.out.println(t.a);
}
};
Instance vs Static variables:-
1. Instance variable for the each and every object one separate copy is maintained.
2. Static variable for all objects same copy is maintained. One Object change the value another
object is affected.
class Test
{
int a=10;
static int b=20;
public static void main(String... ratan)
{

43 | P a g e
Test t1=new Test();
System.out.println(t1.a);//10
System.out.println(t1.b);//20
t1.a=444;
t1.b=555;
Test t2=new Test();
System.out.println(t2.a);//10
System.out.println(t2.b);//555
t2.b=111;
System.out.println(t2.b);//111
Test t3=new Test();
System.out.println(t3.a);//10
System.out.println(t3.b);//111
Test t4=new Test();
System.out.println(t4.a);//10
System.out.println(t4.b);//111
}
};
Variables default values:-
Case 1:- for the instance variables the JVM will provide the default values.
class Test
{
int a=10;
int b;
public static void main(String[] args)
{
Test t=new Test();
System.out.println(t.a);//10
System.out.println(t.b);//0
}
}
Case 2:- for the static variables the JVM will provide the default values.
class Test
{
static double d=10.9;
static boolean b;
public static void main(String[] args)
{
System.out.println(d);//10.9
System.out.println(b);//false
}
}
Case 3:- for the local variables the JVM won’t provide the default values before using those variables
we have to provide the default values.

44 | P a g e
class Test
{
public static void main(String[] args)
{
byte a=10;
int b;
System.out.println(a);
System.out.println(b);
}
}
Compilation error:- Variables b might not have been initialized
System.out.println(b);
Practice example:-
class Test
{
//2-instance variables
int a=10;
boolean b;
//2-static variables
static int c=20;
static double d;
//1-instance methods
void m1()
{
System.out.println(a);//10
System.out.println(b);//false
System.out.println(c);//20
System.out.println(d);//0.0
}
//1-static method
static void m2()
{
Test t=new Test();
System.out.println(t.a);//10
System.out.println(t.b);//false
System.out.println(c);//20
System.out.println(d);//0.0
}
public static void main(String[] args)
{
Test t=new Test();
t.m1();
m2();
}
}

45 | P a g e

You might also like