Introduction to Java Programming Basics
Introduction to Java Programming Basics
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:
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;
}
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 {
[Link]("Thread is running...");
}
}
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 {
// 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!
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:
Platform-independent,
Platform dependent should be
Platform Java bytecode works on
compiled for different platforms.
Dependency any operating system.
and Interpreted
Language.
services.
It supports documentation
It doesn’t support documentation
Documentation comments (e.g., /**.. */)
comments for source code.
Comment for source code.
Parameter Java supports only the C++ supports both Pass by Value
Passing Pass by Value technique. and pass-by-reference.
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 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;
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;
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;
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].*;
if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
[Link](result);
}
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 {
// 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);
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 {
// 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
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";