0% found this document useful (0 votes)
4 views38 pages

Introduction to Java Programming Basics

Uploaded by

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

Introduction to Java Programming Basics

Uploaded by

nisha langeh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-1

Java is a high-level, object-oriented programming language used to build web apps,


mobile applications, and enterprise software systems.
 Known for its Write Once, Run Anywhere capability, which means code written in
Java can run on any device that supports the Java Virtual Machine (JVM).
 Syntax and structure is similar to C-based languages like C++ and C#.
Understanding Hello World Program in Java
When we learn any programming language, the first step is writing a simple program to
display "Hello World". So, here is a simple Java program that displays "Hello World" on
the screen.
// This is a simple Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}

Output
Hello World!
How does this work:
 // starts a single-line comment. The comments does not executed by Java.
 public class HelloWorld defines a class named HelloWorld. In Java, every
program must be inside a class.
 public static void main(String[] args) is the entry point of any Java application.
It tells the JVM where to start executing the program.
 [Link]("Hello, World!"); prints the message to the console.
Java program execution follows this below simple flow:

 Write code in a file like [Link].


 The Java Compiler "javac" compiles it into bytecode "[Link]".
 The JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.
 JVM converts bytecode to machine readable code i.e. "binary" (001001010) and
then execute the program.
To understand Hello World program in detail, refer to article: Java Hello World Program
Comments in Java
The comments are the notes written inside the code to explain what we are doing. The
comment lines are not executed while we run the program.
Single-line comment
// This is a comment
Multi-line comment
/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
To understand Java comments in detail, refer to article: Java Comments
Curly Braces and Indentation in Java
In Java, curly braces {} are used to define blocks of code. For example, the body of a
class or method is enclosed within curly braces.
Example:
public class Geeks{
public static void main(String[] args) {
{
[Link]("This is inside the block.");
}

[Link]("This is outside the block.");


}
}
 The code block inside {} runs unconditionally and prints a message.
 Curly brackets {} group multiple statements into a single block, even without
conditions.
Naming Conventions in Java
 Java uses standard naming rules that make the code easier and improves the
readability.
 In Java, the class names start with a capital letter for example, HelloWorld.
Method and variable names start with a lowercase letter and use camelCase
like printMessage.
 And the constants are written in all uppercase letters with underscores
like MAX_SIZE.
To understand Naming convention in Java in detail, refer to article: Java Naming
Convention
Famous Applications Built Using Java
 Android Apps: Most of the Android mobile apps are built using Java.
 Netflix: This uses Java for content delivery and backend services.
 Amazon: Java language is used for its backend systems.
 LinkedIn: This uses Java for handling high traffic and scalability.
 Minecraft: This is one of the world’s most popular games that is built in Java.
 Spotify: This uses Java in parts of its server-side infrastructure.
 Uber: Java is used for backend services like trip management.
 NASA WorldWind: This is a virtual globe software built using Java.
What Can We Do with Java?
Java is used for:
 Mobile App Development: Android development using Android Studio.
 Web Development: Using frameworks like Spring Boot and Jakarta EE.
 Desktop GUI Applications: With libraries like JavaFX and Swing.
 Enterprise Applications: Java is the backbone of many banking and business
software.
 Game Development: Through game engines like LibGDX.
 Big Data Technologies: Like Hadoop and Apache Kafka.
 Internet of Things (IoT): Java can run on embedded systems and devices.
 Cloud-based Applications: Java is used in services on AWS, Azure,
and Google Cloud.
 Scientific Applications: Java is used in tools that process large amounts of
scientific data.
 Java Features
Java is a high-level, object-oriented programming language. This language is very
easy to learn and widely used. It is known for its platform independence, reliability, and
security. It follows one principle, that is "Write Once, Run Anywhere" principle. It
supports various features like portability, robustness, simplicity, multithreading, and high
performance, which makes it a popular choice for beginners as well as for developers.
Features in Java
1. Simple Syntax
Java syntax is very straightforward and very easy to learn. Java removes complex
features like pointers and multiple inheritance, which makes it a good choice for
beginners.
Example: Basic Java Program
// Java program to Demonstrate the Basic Syntax
import [Link].*;

class Geeks {
public static void main(String[] args)
{
[Link]("GeeksForGeeks!");
}
}

Output
GeeksForGeeks!
Explanation: In Java, the execution starts with the main method, which is the entry
point of any Java application. The [Link] statement prints
"GeeksForGeeks!". The import [Link].*; statement means we are putting input-output
functionalities
2. Object Oriented
Java is a pure object-oriented language. It supports core OOP concepts like,
 Class
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
Example: The below Java program demonstrates the basic concepts of OOPs.
// Java program to demonstrate the basic concepts of oops
// like class, object, Constructor and method
import [Link].*;

class Student {
int age;
String name;
public Student(int age, String name)
{
[Link] = age;
[Link] = name;
}

// This method display the details of the student


void display()
{
[Link]("Name is: " + name);
[Link]("Age is: " + age);
}
}

class Geeks {
public static void main(String[] args)
{
Student student = new Student(22, "GFG");
[Link]();
}
}

Output
Name is: GFG
Age is: 22
Explanation: In the above example, we have created a Student class and inside the
class we have declared two variables age and name. A constructor is used to initialize
these variables when an object of the Student class is created. In the main method we
are creating an object of the student class and then we are calling the display method
which is prinitng the name and age on the console.
3. Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
 When we write Java code, it is first compiled by the compiler and then converted
into bytecode (which is platform-independent).
 This byte code can run on any platform which has JVM installed.
4. Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode.
This byte code is then understand by the JVM. This enables Java to run on any platform
without rewriting code.
5. Scalable
Java can handle both small and large-scale applications. Java provides features
like multithreading and distributed computing that allows developers to manage loads
more easily.
6. Portable
When we write a Java program, the code first get converted into bytecode and this
bytecode does not depend on any operating system or any specific computer. We can
simply execute this bytecode on any platform with the help of JVM. Since JVMs are
available on most devices and that's why we can run the same Java program on
different platform
7. Secured and Robust
Java is a reliable programming language because it can catch mistakes early while
writing the code and also keeps checking for errors when the program is running. It also
has a feature called exception handling that helps deal with unexpected problems
smoothly.
8. Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine
(JVM).
 Java garbage collector reclaim memory from objects that are no longer needed.
 Memory for objects are allocated in the heap
 Method calls and local variables are stored in the stack.
9. High Performance
Java is faster than old interpreted languages. Java program is first converted into
bytecode which is faster than interpreted code. It is slower than fully compiled
languages like C or C++ because of interpretation and JIT compilation process. Java
performance is improve with the help of Just-In-Time (JIT) compilation, which makes it
faster than many interpreted languages but not as fast as fully compiled languages.
10. Multithreading
Multithreading in Java allows multiple threads to run at the same time.
 It improves CPU utilization and enhancing performance in applications that
require concurrent task execution.
 Multithreading is especially important for interactive and high-performance
applications, such as games and real-time systems.
 Java provides build in support for managing multiple threads. A thread is known
as the smallest unit of execution within a process.
Example: Basic Multithreadig in Java
// Java program to demonstrate multithreading
class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");
}
}

public class Geeks {

public static void main(String[] args) {


MyThread thread = new MyThread();

// Starts the thread


[Link]();
}
}

Output
Thread is running...
Explanation: The MyThread class extends the Thread class and overrides the run
method. In the main method, an object of MyThread is created, and the start method is
called to begin the execution of the thread. The run method is executed in a separate
thread, printing "Thread is running..." to the console.
11. Rich Standard Library
Java provides various pre-built tools and libraries which is known as Java API. Java API
is used to cover tasks like file handling, networking, database connectivity (JDBC),
security, etc. With the help of these libraries developers save a lot of time and ready to
use solutions and can also build a powerful application.
12. Functional Programming Features
Since Java 8, the language has introduced functional programming features such as:
 lambda expression let us to write small block of code in a very easy way without
creating full methods.
 Stream API allows data to be processed easily, Instead of writing long loops we
can just filter, change, or combine data in a few lines.
 Functional interfaces are inteface that contains only one method. They work
perfectly with lambda expressions and help us write flexible and reusable code.
Example:
// Java program demonstrating lambda expressions
interface Lambda {

int operate(int a, int b);


}

public class Geeks {


public static void main(String[] args) {

// Lambda expression
Lambda add = (a, b) -> a + b;
[Link]("Addition: " + [Link](2, 3));
}
}

Output
Addition: 5
Explanation: A functional interface Lambda is defined with a single method operate. A
lambda expression (a, b) -> a + b is used to implement the operate method. The main
method calls the operate method using the lambda expression and prints the result.
13. Integration with Other Technologies
Java can easily work with many languages and tools as well. For example, Java can
connect with C and C++ with the help of Java Native Interface (JNI). Java is very
popular for building websites and webservices like RESTful & SOAP. In Java we can
use JDBC for databse connectivity also Java is the main language for android
development. As we can see Java works so well with so many different technologies
that's the reason developer prefers Java more to create scalable and powerful
application.
14. Support for Mobile and Web Application
Java offers support for both web and mobile applications.
 For web development: Java offers technologies like JSP and Servlets, along
with frameworks like Spring and Springboot, which makes it easier to build web
applications.
 For mobile development: Java is the main language for Android app
development. The Android SDK uses special version of Java and its various tools
to build mobile apps for Android devices.
15. Documentation and Community Support
Java provide documentation which includes guides, API references, and tutorials for
easy learning. Java has a large and active global community contributing to open-
source projects, and resources. This community support helps developers solve
problems and stay updated with new advancements.
What is Java?
Java is a popular programming language, created in 1995.
It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why Use Java?


 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming languages in the world
 It has a large demand in the current job market
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to
Java or vice versa

Get Started
When you are finished with this tutorial, you will be able to write basic Java programs
and create real-life examples.
It is not necessary to have any prior programming experience.
[Link]
notes-activity-7081811428583649280-qcFk?
utm_source=li_share&utm_content=feedcontent&utm_medium=g_dt_web&utm_campai
gn=copy

C++ vs Java
C++ vs Java
The following table lists all the major differences between Java and C++ programming
languages:

Parameters Java C++

Java was influenced by C++ was Influenced by Influenced by


Ada 83, Pascal, C++, C#, Ada, ALGOL 68, C, ML, Simula,
Influenced By etc. languages. Smalltalk, etc. languages.

Java was influenced to


develop BeanShell, C#, C++ was influenced to develop C99,
Clojure, Groovy, Hack, Java, JS++, Lua, Perl, PHP, Python,
J#, Kotlin, PHP, Python, Rust, Seed7, etc. languages.
Influenced to Scala, etc. languages.

Platform-independent,
Platform dependent should be
Platform Java bytecode works on
compiled for different platforms.
Dependency any operating system.

It can run on any OS C++ is platform-dependent. Hence it


Portability hence it is portable. is not portable.

Compilation Java is both a Compiled C++ is a Compiled Language.


Parameters Java C++

and Interpreted
Language.

Memory Memory Management is Memory Management in C++ is


Management System Controlled. Manual.

It doesn't have Virtual


It has Virtual keywords.
Virtual Keyword keywords.

It supports only single


inheritance. Multiple It supports both single and multiple
Multiple inheritances are achieved Inheritance.
Inheritance partially using interfaces.

It supports only method


overloading and doesn't It supports both method and operator
allow operator overloading.
Overloading overloading.

It has limited support for


It strongly supports pointers.
Pointers pointers.

Libraries It doesn't support direct It supports direct system library calls,


native library calls but making it suitable for system-level
only Java Native programming.
Interfaces.

C++ libraries have comparatively


Libraries have a wide low-level functionalities.
range of classes for
various high-level
Parameters Java C++

services.

It supports documentation
It doesn’t support documentation
Documentation comments (e.g., /**.. */)
comments for source code.
Comment for source code.

Java provides built-in C++ doesn’t have built-in support for


support for threads, depends on third-party
Thread Support multithreading. threading libraries.

Java is only an object- C++ is both a procedural and


oriented programming an object-oriented
Type language. programming language.

Java uses the (System


class): [Link] for C++ uses cin for input and cout for
Input-Output input and [Link] for output operation.
mechanism output.

Java doesn't support the


C++ supports the goto keyword.
goto Keyword goto Keyword

Structures and Java doesn't support C++


Unions Structures and Unions. supports Structures and Unions.

Parameter Java supports only the C++ supports both Pass by Value
Passing Pass by Value technique. and pass-by-reference.

Global Scope It supports no global It supports both global scope


Parameters Java C++

scope. and namespace scope.

Automatic object
It supports manual object
Object management with
management using new and deletes.
Management garbage collection.

Call by Value
Java supports only calls C++ both supports call by value and
and Call by
by value. call by reference.
Reference

Java is not so interactive


C++ is nearer to hardware.
Hardware with hardware.

The compilation and execution of a Java program involves a two-step process:


1. Compilation:
 Source Code Creation:
The Java program is written in human-readable source code and saved with
a .java extension (e.g., [Link]).
 Compilation by javac:
The Java compiler, javac, is used to translate the .java source file into bytecode. This is
done using the command:
Code
javac [Link]
 Bytecode Generation: If the compilation is successful and no syntax errors are
found, javac generates a .class file (e.g., [Link]). This .class file
contains platform-independent bytecode, which is an intermediate representation
of the program.
2. Execution:
 JVM Invocation: The Java Virtual Machine (JVM) is invoked to execute the
compiled bytecode. This is done using the command:
Code
java MyProgram
Note that the .class extension is omitted when running the program.
 Class Loading: The JVM's class loader loads the necessary .class files into
memory.
 Bytecode Verification: The bytecode verifier within the JVM checks the loaded
bytecode for security violations and integrity.
 Bytecode Interpretation and Execution: The JVM's interpreter or Just-In-Time
(JIT) compiler translates the bytecode into machine-specific instructions for the
underlying operating system and hardware. The program then executes, and its
output is displayed on the console or in a graphical user interface.

 Java Variables
In Java, variables are containers that store data in memory. Understanding variables
plays a very important role as it defines how data is stored, accessed, and manipulated.
Key Components of Variables in Java:
A variable in Java has three components, which are listed below:
 Data Type: Defines the kind of data stored (e.g., int, String, float).
 Variable Name: A unique identifier following Java naming rules.
 Value: The actual data assigned to the variable.
Note: There are three types of variables in Java: Local, Instance and Static.
Example: The below example demonstrates the variable declaration in Java
// Demonstarting how to declare and use a variable in Java

class Geeks {
public static void main(String[] args) {
// Declaring and initializing variables
// Integer variable
int age = 25;

// String variable
String name = "GeeksforGeeks";

// Double variable
double salary = 50000.50;

// Displaying the values of variables


[Link]("Age: " + age);
[Link]("Name: " + name);
[Link]("Salary: " + salary);
}
}

Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5
How to Declare Java Variables?
The image below demonstrates how we can declare a variable in Java:
Variable Declaration
From the image, it can be easily perceived that while declaring a variable, we need to
take care of two things that are:
1. data type: In Java, a data type define the type of data that a variable can hold.
2. variable name: Must follow Java naming conventions (e.g., camelCase).
In this way, a name can only be given to a memory location. It can be assigned values
in two ways:
 Variable Initialization
 Assigning value by taking input
How to Initialize Java Variables?
It can be perceived with the help of 3 components explained above:
Variable Initialization
Example: Here, we are initalizing variables of different types like float, int and char.
// Demonstrating how to intialize variables
// of different types in Java

class Geeks{
public static void main(String[] args) {
// Declaring and initializing variables
// Initializing float variable
float si = 5.5f;

// Initializing integer variables


int t = 10;
int s = 20;

// Initializing character variable


char var = 'h';

// Displaying the values of the variables


[Link]("Simple Interest: " + si);
[Link]("Speed: " + s);
[Link]("Time: " + t);
[Link]("Character: " + var);
}
}

Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
Types of Java Variables
Now let us discuss different types of variables which are listed as follows:
 Local Variables
 Instance Variables
 Static Variables

Type of Variable
Let us discuss the traits of every type of variable listed here in detail.
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
 The Local variable is created at the time of declaration and destroyed when the
function completed its execution.
 The scope of local variables exists only within the block in which they are
declared.
 We first need to initialize a local variable before using it within its scope.
Example: This example show how a local variable is declared and used inside the
main method and it can not be used outside of it.
// Java Program to show the use of local variables
import [Link].*;

class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


[Link]("Local Variable: " + var);
}
}

Output
Local Variable: 10
Example: This example demonstrates that local variables are only accessible within the
block in which they are declared
// Java Program to show the use of
// Local Variables
import [Link].*;

public class Geeks {

public static void main(String[] args)


{
// x is a local variable
int x = 10;

// message is also a local


// variable
String message = "Hello, world!";

[Link]("x = " + x);


[Link]("message = " + message);

if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
[Link](result);
}

// Uncommenting the line below will result in a


// compile-time error [Link](result);
for (int i = 0; i < 3; i++) {
String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
[Link](loopMessage);
}

// Uncommenting the line below will result in a


// compile-time error
// [Link](loopMessage);
}
}

Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
2. Instance Variables
Instance variables are known as non-static variables and are declared in a class outside
of any method, constructor, or block.
 Instance variables are created when an object of the class is created and
destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier, then the default access specifier will be
used.
 Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it
is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null,
etc.
 Scope of instance variables are throughout the class except the static contexts.
 Instance variables can be accessed only by creating objects.
 We initialize instance variables using constructors while creating an object. We
can also use instance blocks to initialize the instance variables.
Example: This example demonstrates the use of instance variables, which are declared
within a class and initialized via a constructor, with default values for uninitialized
primitive types.
// Java Program to show the use of
// Instance Variables
import [Link].*;

class Geeks {

// Declared Instance Variable


public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor
// initializing Instance Variable
[Link] = "Sweta Dash";
}

// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();

// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);

// toString() called internally


[Link]("Default value for Integer is: "+ name.I);
}
}

Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null
3. Static Variables
Static variables are also known as class variables.
 These variables are declared similarly to instance variables. The difference is
that static variables are declared using the static keyword within a class outside
of any method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of a static variable is not mandatory. Its default value is dependent
on the data type of variable. For String it is null, for float it is 0.0f, for int it is 0,
for Wrapper classes like Integer it is null, etc.
 If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won't halt the program. The
compiler will replace the object name with the class name automatically.
 If we access a static variable without the class name, the compiler will
automatically append the class name. But for accessing the static variable of a
different class, we must mention the class name as 2 different classes might
have a static variable with the same name.
 Static variables cannot be declared locally inside an instance method.
 Static blocks can be used to initialize static variables.
Example: This example demonstrates the use of static variables, which belong to the
class and can be accessed without creating an object of the class.
// Java Program to show the use of
// Static variables
import [Link].*;

class Geeks {

// Declared static variable


public static String geek = "Sweta Dash";

public static void main(String[] args)


{

// geek variable can be accessed without object


// creation Displaying O/P [Link] --> using the
// static variable
[Link]("Geek Name is: " + [Link]);

// static int c = 0;
// above line, when uncommented,
// will throw an error as static variables cannot be
// declared locally.
}
}

Output
Geek Name is: Sweta Dash
Instance Variables vs Static Variables
Now let us discuss the differences between the Instance variables and the Static
variables:
 Each object will have its own copy of an instance variable, whereas we can only
have one copy of a static variable per class, irrespective of how many objects we
create. Thus, static variables are good for memory management.
 Changes made in an instance variable using one object will not be reflected in
other objects as each object has its own copy of the instance variable. In the
case of a static variable, changes will be reflected in other objects as static
variables are common to all objects of a class.
 We can access instance variables through object references, and static variables
can be accessed directly using the class name.
 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed. Static variables are
created when the program starts and destroyed when the program stops.
Syntax: Static and instance variables
class Geeks
{
// Static variable
static int a;
// Instance variable
int b;
}
Common Mistakes to Avoid
The common mistakes that can occur when working with variables in Java are listed
below:
 Using uninitialized local variables: Accessing a local variable without
initializing it leads to a compile-time error.
 Confusing == and .equals() for Strings: == is used to compare object
references, while .equals() is used to compare the content of the strings.
 Modifying static variables incorrectly: Changing static variables in a multi-
threaded environment can lead to thread safety issues

 What is a Java Variable?


 A variable provides us with named storage that our programs can
manipulate. Each variable in Java has a specific type, which determines
the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be
applied to the variable.

Variable Declaration and Initialization


You must declare all variables before they can be used. Java variables are declared by
specifying the data type followed by the variable name. To assign a value, use the
assignment (=) operator followed by the value. Each declaration or initialization
statement must end with a semicolon (;).
Syntax
Following is the basic form of a variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's data types and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated
list.
Example of Valid Variables Declarations and Initializations
Following are valid examples of variable declaration and initialization in Java −
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
Java Variables Types
The following are the three types of Java variables:
1. Local variables
2. Instance variables
3. Class/Static variables
1. Java Local Variables
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared
and an initial value should be assigned before the first use.
Example 1: Variable's local scope with initialization
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.
Open Compiler
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Output
Puppy age is: 7
Example 2: Variable's local scope without initialization
Following example uses age without initializing it, so it would give an error at the time of
compilation.
Open Compiler
public class Test {
public void pupAge() {
int age;
age = age + 7;
[Link]("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
[Link]();
}
}
Output
[Link][Link]variable number might not have been initialized
age = age + 7;
^
1 error
2. Java Instance Variables
 Instance variables are declared in a class, but outside a method, constructor or
any block.
 When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
 Instance variables are created when an object is created with the use of the
keyword 'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one
method, constructor or block, or essential parts of an object's state that must be
present throughout the class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the
class. Normally, it is recommended to make these variables private (access
level). However, visibility for subclasses can be given for these variables with the
use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned
during the declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside
the class. However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified
name. [Link].
Example of Java Instance Variables
Open Compiler
import [Link].*;

public class Employee {

// this instance variable is visible for any child class.


public String name;
// salary variable is visible in Employee class only.
private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.


public void printEmp() {
[Link]("name : " + name );
[Link]("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
[Link](1000);
[Link]();
}
}
Output
name : Ransika
salary :1000.0
3. Java Class/Static Variables
 Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
 Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and static.
Constant variables never change from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the
program stops.
 Visibility is similar to instance variables. However, most static variables are
declared public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is
0; for Booleans, it is false; and for object references, it is null. Values can be
assigned during the declaration or within the constructor. Additionally, values can
be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class
name [Link].
 When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and final,
the naming syntax is the same as instance and local variables.
Example of Java Class/Static Variables
Open Compiler
import [Link].*;

public class Employee {


// salary variable is a private static variable
private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[]) {


salary = 1000;
[Link](DEPARTMENT + "average salary:" + salary);
}
}
Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be
accessed as [Link]

You might also like