Java Week 1 Part 1
Java Week 1 Part 1
Welcome to Week 1 of your Java programming journey! This week lays the
foundation for everything you'll build ahead from understanding what Java is to
writing your first program. Through beginner-friendly explanations, practical coding
exercises and consistent daily learning, you'll gain the confidence and clarity to start
developing real-world Java applications from scratch.
Day 1 – Java Basics and Features
Get introduced to Java, its core principles and why it's one of the most widely used
programming languages.
• What is Java?
• Features of Java
• JDK, JRE and JVM
JVM is OS-
Platform Platform- Platform- specific, but
Dependen dependent (OS dependent (OS bytecode is
cy specific) specific) platform-
independent
JRE +
ClassLoader, JIT
Development tools JVM + Libraries
Includes Compiler, Garbage
(javac, debugger, (e.g., rt.jar)
Collector
etc.)
Working of JDK
Java Development Kit (JDK) is one of the most important tools for developers who use it to
build, compile, and run Java applications. It does not matter if you are a beginner or an
experienced programmer; installing JDK is the first step towards working with Java development.
We can download JDK to create and run Java applications on our system. Also, the JDK is used
to create Android application source files as well, using the Java or Kotlin pr ogramming
language. There are multiple benefits of installing a JDK.
Key Features of JDK:
• Compiler (javac): Converts Java code into bytecode for JVM execution.
• JRE + JVM: Includes runtime environment to execute Java programs.
• Rich Libraries: Pre-built classes for I/O, networking, databases, and more.
• Debugging Tools: JDK provides JDB (Java Debugger) for troubleshooting code.
• Multi-Platform Support: JDK supports write-once, run anywhere (Windows, Linux, macOS).
The system will execute the code using a set of Libraries and Compilers. JDK, JRE, and JVM
should not be confused with one another.
Refer to this article to learn more: Differences between JDK, JRE, and JVM.
Why Install JDK?
• To develop and run Java applications
• Compile Java source code (javac)
• Includes JRE (Java Runtime Environment) and JVM (Java Virtual Machine)
• Required for Android app development (Java/Kotlin)
This article describes the step-by-step process for installing and configuring the JDK on
Windows, Mac, and Linux.
Java JDK Download
The JDK can be installed on the following Platforms:
1. Microsoft Windows
2. Linux
3. macOS
Download JDK (Java Development Kit)
We need to download the JDK first, find the steps below to get started:
Step 1: Visit the Official Website
Step 2.1: To set the Environment Variables, you need to search Environment Variables in the
Task Bar and click on “Edit the system environment variables”.
System
Properties
Step 2.3: Under System variables, select the "Path" variable and click on "Edit". Click on
"New" then paste the Path Address i.e. C:\Program Files\Java\jdk-
{YOUR_JDK_VERSION}\bin. Click on "OK".
Path
Step 2.4: Now, in the Environment Variables dialogue, under System variables, click on
"New" and then under Variable name: JAVA_HOME and Variable value: paste address i.e.
C:\Program Files\Java\jdk-{YOUR_JDK_VERSION}. Click on OK => OK => OK.
System Properties
Command Prompt
Install JDK on Linux
Follow the steps below to install the Java software Development Kit on a Linux environment.
These instructions are applicable to various Linux distributions such as Ubuntu, Fedora, and
CentOS.
Note: We have used Kali Linux distributions here.
Step 1: Install Oracle Java Development Kit (JDK)
To install the downloaded JDK File using terminal, Open terminal and change your directory to
downloads by using the command:
$ cd downloads
To list files and packages present in the directory, Type
$ ls
Root Kali
Step 1.1: Now we use Debian Package Manager to configure our downloaded file for
installation by typing
$ sudo dpkg -i jdk-{YOUR_JDK_VERSION} (replace {-} with your version)
Enter your password as we have run an elevated prompt, i.e. the sudo or superuser do
command, which is a quick way to grant specific users permission to perform specific system
commands at the system's root (most powerful) level.
Kali Linux
Step 1.2: Now, Type the following commands to proceed with the installation
$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-
{YOUR_JDK_VERSION}/bin/java 1
$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-
{YOUR_JDK_VERSION}/bin/javac 1
sudo
Step 3.2: Now we have to refresh the environment file by using this command:
$ SOURCE /etc/environment
And echo the JAVA_HOME Path
JAVA_HOME
Installation
Step 2.1: We have to set this output as our JAVA_HOME Environment Variable. You can use
any command or code editor to edit the file, here we are using VS Code
$ code ~/. bash_profile
Terminal
Step 2.2: At the very bottom, we have to export the path we obtained earlier i.e.
$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-
{YOUR_VERSION}.jdk/Contents/Home
bash
Step 2.3: Now we have to refresh the environment file by using this command:
$ source ~/.bash_profile
And echo the JAVA_HOME variable
JAVA_HOME
Java HOME
javac
Advanatages of JDK
The Advanatages of JDK are listed below:
• Complete Development Kit: It Includes compiler (javac), JRE, JVM, and debugging tools.
• Platform Independence: It write once, run anywhere (WORA) using JVM.
• Rich Libraries & APIs: JDK has built-in support for networking, I/O, databases, and more.
• Performance Optimization: Just-In-Time (JIT) compiler boosts execution speed.
• Backward Compatibility: Older Java apps still run on newer JDK versions.
Disadvantages of JDK
The disadvantages of JDK are listed below:
• Large Memory Usage: JDK consumes more RAM compared to some lightweight
languages.
• Complex Setup: Requires manual environment variable configuration.
• Slower Startup Time: JVM initialization can delay execution.
• License Restrictions: Oracle JDK requires a commercial license for business use.
Conclusion
Installing the latest JDK version is a simple process, whether you're on Windows, macOS or
Linux. By following this guide, you can setup JDK and start developing Java applications in just a
few steps. You can easily download the latest jdk 23 in your system and start with Java
development today.
Java Hello World Program
Java is one of the most popular and widely used programming languages and
platforms. In this article, we will learn how to write a simple Java Program. This
article will guide you on how to write, compile, and run your first Java program. With
the help of Java, we can develop web and mobile applications.
In this article, we will learn:
• How to create your first Java program
• How to compile and run Java code
• Understanding the Hello World program structure
Prerequisites:
• Download install JDK.
• Download install intelliJ
Implementation of Java Hello World
The below-given program is the most simple program of Java printing "Hello World"
to the screen. Let us try to understand every bit of code step by step.
// Simple Java program
// FileName: "HelloWorld.java"
public class HelloWorld
{
// Your program begins with a call to main(). // Prints "Hello, World" to the terminal window.
public static void main(String[] args)
{
System.out.println("Hello, World");
}}
Output
Hello, World
Shell
Note: If you get ClassNotFoundException, ensure the .class file is in the correct
directory or check your CLASSPATH.
Comments
They can either be multiline or single-line comments.
// Simple Java program
// FileName: "HelloWorld.java"
This is a single-line comment. This type of comment must begin with // as in C/C++.
For multiline comments, they must begin from /* and end with */.
/*
This is a
multi-line comment
*/
Memory is allocated every time an object is Memory is allocated only once when the class i
created. loaded.
Declared without the static keyword Declared using the static keyword.
Accessed using the object name Accessed using the class name
Value can be different for each object. Value is common for all objects of the class.
❖ Types of Methods
In Java programs generally, we may define two types of methods
apart from the constructor.
• Instance or non-static methods
• Static or class methods
Instance Methods vs Static Methods
The table below demonstrates the difference between Instance
methods and Static methods.
Instance Methods Static Methods
Java Identifiers
An identifier in Java is the name given to Variables, Classes,
Methods, Packages, Interfaces, etc. These are the unique names
used to identify programming elements. Every Java Variable must
be identified with a unique name.
Example:
public class Test
{
public static void main(String[] args)
{
int a = 20;
}}
In the above Java code, we have 5 identifiers as follows:
• Test: Class Name
• main: Method Name
• String: Predefined Class Name
• args: Variable Name
• a: Variable Name
Rules For Naming Java Identifiers
There are certain rules for defining a valid Java identifier. These
rules must be followed, otherwise, we get a compile-time error.
These rules are also valid for other languages like C and C++.
• The only allowed characters for identifiers are all alphanumeric
characters([A-Z],[a-z],[0-9]), '$'(dollar sign) and '_' (underscore). For
example, "geek@" is not a valid Java identifier as it contains a '@', a
special character.
• Identifiers should not start with digits([0-9]). For example,
"123geeks" is not a valid Java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier, but it is advisable
to use an optimum length of 4 - 15 letters only.
• Reserved Words can't be used as an identifier. For example,
"int while = 20;" is an invalid statement as a while is a reserved word.
Note: Java has 53 reserved words (including 50 keywords and 3
literals), that are not allowed to be used as identifiers.
Examples of Valid Identifiers
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of Invalid Identifiers
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Reserved Words in Java
Any programming language reserves some words to represent
functionalities defined by that language. These words are called
reserved words. They can be briefly categorized into two parts:
• Keywords (50): Keywords define functionalities. The below table
shows list of 50 keywords.
• literals (3): Literals define value. The three literals are, true,
false and null.
Identifiers are stored by symbol tables and used during the
lexical, syntax, and semantic analysis phase of compilation.
List of Java Reserved Words
abstra continu
for protected transient
ct e
Boolea
Do If Static throws
n
implemen
break double strictfp Package
ts
Extend instanceo
Catch return void
s f
synchroniz
Char Final Int volatile
ed
Note: The keywords const and goto are reserved, even though
they are not currently used in Java. In place of const, the final
keyword is used. Some keywords like strictfp are included in later
versions of Java.
JVM-
depende
boolea fals
true or false nt true, false true, false
n e
(typically
1 byte)
8-bit signed
byte 0 1 byte (none) -128 to 127
integer
16-bit signed
short 0 2 bytes (none) -32,768 to 32,767
integer
-2,147,483,648
32-bit signed
int 0 4 bytes -2,0,1 to
integer
2,147,483,647
-
9,223,372,036,854,7
64-bit signed 8
long 0L 8 bytes -2L,0L,1L
integer to
9,223,372,036,854,7
7
32-bit IEEE
3.14f, - ~6-7 significant
float 754 floating- 0.0f 4 bytes
1.23e-10f digits
point
Output
Number of Students: 1000
Temperature: -200
Output
Population: 2000000
Distance: 150000000
Output
World Population: 7800000000
Light Year Distance: 9460730472580800
Output
Value of Pi: 3.14
Gravity: 9.81
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
Output
Grade: A
Symbol: $
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Output
Name: Geek1
Message: Hello, World!
Note: String cannot be modified after creation. Use StringBuilder for heavy string
manipulation
2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It
represents the set of properties or methods that are common to all objects of one
type. In general, class declarations can include these components, in order:
• Modifiers : A class can be public or has default access. Refer to access
specifiers for classes or interfaces in Java
• Class name: The name should begin with an initial letter (capitalized by
convention).
• Superclass(if any): The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one parent.
• Interfaces(if any): A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class can implement more than
one interface.
• Body: The class body is surrounded by braces, { }.
Example: This example demonstrates how to create a class with a constructor and
method, and how to create an object to call the method.
// Demonstrating how to create a class
class Car {
String model;
int year;
Car(String model, int year)
{
this.model = model;
this.year = year;
}
void display()
{
System.out.println(model + " " + year);
}}
public class Geeks {
public static void main(String[] args)
{
Car myCar = new Car("Toyota", 2020);
myCar.display();
}}
Output
Toyota 2020
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life
entities. A typical Java program creates many objects, which as you know, interact
by invoking methods. An object consists of :
• State: It is represented by the attributes of an object. It also reflects the
properties of an object.
• Behavior: It is represented by the methods of an object. It also reflects the
response of an object to other objects.
• Identity: It gives a unique name to an object and enables one object to interact
with other objects.
Example: This example demonstrates how to create the object of a class.
// Define the Car class
class Car {
String model;
int year;
// Constructor to initialize the Car object
Car(String model, int year)
{
this.model = model;
this.year = year;
}}
// Main class to demonstrate object creation
public class Geeks {
public static void main(String[] args)
{
// Create an object of the Car class
Car myCar = new
Car("Honda", 2021);
// Access and print the object's properties
System.out.println("Car Model: " + myCar.model);
System.out.println("Car Year: " + myCar.year); }}
Output
Car Model: Honda
Car Year: 2021
4. Interface
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no body).
• Interfaces specify what a class must do and not how. It is the blueprint of the
class.
• An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set
of methods that the class has to implement.
• If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
• A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
Example: This example demonstrates how to implement an interface.
// Demonstrating the working of interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound()
{
System.out.println("Woof");
}}
public class InterfaceExample {
public static void main(String[] args)
{
Dog myDog = new Dog();
myDog.sound();
}}
Output
Woof
5. Array
An Array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some
important points about Java arrays.
• In Java, all arrays are dynamically allocated. (discussed below)
• Since arrays are objects in Java, we can find their length using member length.
This is different from C/C++ where we find length using size.
• A Java array variable can also be declared like other variables with [] after the
data type.
• The variables in the array are ordered and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method
parameter.
• The size of an array must be specified by an int value and not long or short.
• The direct superclass of an array type is Object.
• Every array type implements the interfaces Cloneable and java.io.Serializable.
Example: This example demonstrates how to create and access elements of an
array.
// Demonstrating how to create an array
public class Geeks {
public static void main(String[] args)
{
int[] num = {1, 2, 3, 4, 5};
[] arr = {"Geek1", "Geek2", "Geek3"};
System.out.println("First Number: " + num[0]);
System.out.println("Second Fruit: " + arr[1]);
}}
Output
First Number: 1
Second Fruit: Geek2
Memor
Stored on the stack Stored on the heap
y
Exampl
int x = 5; String s = "Geeks";
e
❖ Java Keywords
In Java, keywords are the reserved words that have some predefined meanings
and are used by the Java compiler for some internal process or represent some
predefined actions. These words cannot be used as identifiers such as variable
names, method names, class names, or object names.
Now, let us go through a simple example before a deep dive into the article.
Example:
// Java Program to demonstrate Keywords
class Geeks {
public static void main(String[] args)
{
// Using final and int keyword
final int x = 10;
// Using if and else keywords
if(x > 10){
System.out.println("Failed");
}
else
{
System.out.println("Successful demonstration"+" of keywords.");
}
}}
Output
Successful demonstration of keywords.
Example: Using a keyword as a variable name would give error as shown below.
// Java Program to illustrate what if
// we use the keywords as the variable name
class Geeks
{
public static void main(String[] args)
{
// Note "this" is a reserved
// word in java
String this = "Hello World!";
System.out.println(this);
}
}
Output:
./Geeks.java:9: error: not a statement
String this = "Hello World!";
^
./Geeks.java:9: error: ';' expected
String this = "Hello World!";
^
2 errors
Important Points:
• The keywords const and goto are reserved, even though they are not currently
used in Java.
• true, false, and null look like keywords, but in actuality they are literals.
However, they still can't be used as identifiers in a program.
• In Java, keywords are case-sensitive, and writing Java keywords in upper case
(like IF instead of if) will throw an error.
)
Literals in Java
In Java, a Literal is value of boolean, numeric, character, or string data. Any
constant value that can be assigned to the variable is called a literal.
// Here 100 is a constant/literal.
int x = 100;
Types of Literals in Java
Java supports the following types of literals:
• Integral Literals
• Floating-Point Literals
• Char Literals
• String Literals
• Boolean Literals
Integral Literals in Java
For Integral data types (byte, short, int, long), we can specify literals in four ways,
which are listed below:
1. Decimal literals (Base 10): In this form, the allowed digits are 0-9.
int x = 101;
2. Octal literals (Base 8): In this form, the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
3. Hexadecimal literals (Base 16): In this form, the allowed digits are 0-9, and
characters are a-f. We can use both uppercase and lowercase characters, as we
know that Java is a case-sensitive programming language, but here Java is not
case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
4. Binary literals: From 1.7 onward, we can specify literal value even in binary form
also, allowed digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;
Example:
public class Geeks {
public static void main(String[] args)
{
// decimal-form literal
int a = 101;
// octal-form literal
int b = 0100;
// Hexa-decimal form literal
int c = 0xFace;
// Binary literal
int d = 0b1111;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d); }}
Output
101
64
64206
15
Note: By default, every literal is of int type, we can specify explicitly as long type by
suffixed with l or L. There is no way to specify byte and short literals explicitly but
indirectly we can specify. Whenever we are assigning integral literal to the byte
variable and if the value is within the range of byte then the compiler treats it
automatically as byte literals.
Floating-Point Literal in Java
For Floating-point data types, we can specify literals in only decimal form, and we
can not specify in octal and Hexadecimal forms.
1. Decimal literals(Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;
Example:
public class Geeks {
public static void main(String[] args)
{
// decimal-form literal (float type suffix 'f' or 'F' is required)
float a = 101.230f;
// It is a decimal literal despite the leading zero
float b = 0123.222f;
// Hexadecimal floating-point literals are NOT supported in Java and will cause an error
// This line causes compilation error
// float c = 0x123.222;
System.out.println(a);
System.out.println(b);
// Commented out due to error
// System.out.println(c);
}}
Output
101.23
123.222
Note:
• By default, every floating-point literal is of double type, and hence we cant assign
directly to the float variable without suffix f and F. But we can specify floating-point literal
as float type by suffixed with f or F. We can specify explicitly floating-point literal as
double type by suffixed with d or D(but suffix is optinal).
• Hexadecimal floating-point literals are not supported in Java, and attempting to
use them causes a compilation error.
Char Literals in Java
For char data types, we can specify literals in four ways which are listed below:
1. Single quote: We can specify literal to a char data type as a single character
within the single quote.
char ch = 'a';
2. Char literal as Integral literal: we can specify char literal as integral literal, which
represents the Unicode value of the character, and that integral literal can be
specified either in Decimal, Octal, and Hexadecimal forms. But the allowed range is
0 to 65535.
char ch = 062; // Octal literal representing character with Unicode code 50 (which is
'2')
Note: If invalid digits are used for octal (means digit other than 0=7), it will cause a
compile-time error, for example:
char b = 0789; // Invalid octal literal due to digits 8 and 9 — causes compile-time
error
3. Unicode Representation: We can specify char literals in Unicode representation
‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represent a.
4. Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';
Example:
// Java program to illustrate the
// application of char literals
public class Geeks {
public static void main(String[] args)
{
// single character literal within single quotes
char ch = 'a';
// invalid octal literal (causes compilation error)
// char b = 0789;
// Unicode representation
char c = '\u0061';
System.out.println(ch);
// commented out due to error
// System.out.println(b);
System.out.println(c);
// Escape character literal
System.out.println("\" is a symbol");
}}
Output
a
a
" is a symbol
Illustration:
// Java program to illustrate the
// application of String
literalspublic class Geeks {
public static void main(String[] args)
{
String s = "Hello";
// Without double quotes, it is treated as a variable and causes a compiler error // String s1
= Hello;
System.out.println(s);
// commented out due to error
// System.out.println(s1);
}}
Output
Hello
Boolean Literals in Java
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
boolean c = false;
Example:
// Java program to illustrate the
// application of boolean literals
public class Geeks{
public static void main(String[] args)
{
boolean b = true;
boolean c = false;
// The following lines cause compilation
// errors and are commented out
// boolean d = 0;
// boolean e = 1;
System.out.println(b);
System.out.println(c);
// System.out.println(d);
// System.out.println(e);
}}
Output
true
false
Output
Geeks!48255
Explanation: Whenever we are performing addition between a string and integer,
the overall result is converted into a string. The above program evaluation is done in
the following way:
"Geeks!" + first + '2' + second
"Geeks! " + 48 + '2' + 55
"Geeks!48" + '2' + 55
"Geeks!482" + 55
"Geeks!48255"
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
System.out.println("Age: " + age);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}}
Output
Age: 25
Name: GeeksforGeeks
Salary: 50000.5
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:
Varible Initialization
Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
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 java.io.*;
class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
// This variable is local to this main method only
System.out.println("Local Variable: " + var);
}}
Output
Local Variable: 10
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 java.io.*;
class Geeks {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor
// initializing Instance Variable
this.geek = "Sweta Dash";
}
// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();
// Displaying O/P
System.out.println("Geek name is: " + name.geek);
System.out.println("Default value for int is "+ name.i);
// toString() called internally
System.out.println("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 java.io.*;
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 Geeks.geek --> using the
// static variable
System.out.println("Geek Name is: " + Geeks.geek);
// 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
Typecasting in Java
In Java, typecasting is the process of converting one data type to another data type.
Types of Type Casting
There are two types of Type Casting in Java:
• Widening Type Casting
• Narrow Type Casting
Output
Integer:10
Long:10
Double: 10.0
Example:
// Java Program to demonstrate Narrow type casting
import java.io.*;
class Geeks {
public static void main(String[] args)
{
double i = 100.245;
// Narrowing Type Casting
short j = (short)i;
int k = (int)i;
System.out.println("Original Value before Casting" +i); System.out.println("After
Type Casting to short ” + j);
System.out.println("After Type Casting to int " + k);
}}
Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100
Output
The dog barks
2. Explicit Downcasting
When a subclass type refers to an object of the parent class, the
process is referred to as downcasting. If it is done manually, the
compiler issues a runtime ClassCastException error. It can only be
done by using the instanceof operator. Only the downcast of an
object that has already been upcast is possible.
Example:
// Java Program to demonstrate Explicit downcasting
import java.io.*;
class Animal {
public void eat()
{
System.out.println("The animal is eating.");
}}
class Cat extends Animal {
public void meow()
{
System.out.println("The cat is meowing.");
}}
class Geeks
{
public static void main(String[] args)
Output
The animal is eating.
The cat is meowing.
Java Operators
Java operators are special symbols that perform operations on variables or values.
These operators are essential in programming as they allow you to manipulate data
efficiently.
Example: Below code describes basic structure of operator. how to use operators
like the + and - operators are used to perform addition and subtraction on numeric
values."
// Java program to show the use of + and - operators
public class Geeks {
public static void main(String[] args)
{
// Declare and initialize variables
int num1 = 500;
int num2 = 100;
// Using the + (addition) operator
int sum = num1 + num2;
System.out.println("The Sum is: "+sum);
// Using the - (subtraction) operator
int diff = num1 - num2;
System.out.println("The Difference is: "+diff);
}}
Output
The Sum is: 600
The Difference is: 400
Explanation:
• A class named Geeks is created containing the main method.
• Two integer variables num1 and num2 are declared and initialized with values.
• The + operator is used to add the two numbers and store the result in sum.
• The result of addition is printed to the console.
• The - operator is used to subtract the second number from the first and store the
result in diff.
Types of Operators in Java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. An instance of an operator
Let's see all these operators one by one with their proper examples.
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on primitive
and non-primitive data types.
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• - : Subtraction
Note:
• Division (/) truncates decimal points for integers.
• Modulus (%) is useful for checking even/odd numbers.
Example: This example demonstrates the use of arithmetic operators on integers
and string-to-integer conversion for performing mathematical operations.
// Java Program to show the use of
// Arithmetic Operators
import java.io.*;
class Geeks {
public static void main (String[] args)
{
// Arithmetic operators on integers
int a = 10; int b = 3;
// Arithmetic operators on Strings
String n1 = "15";
String n2 = "25";
// Convert Strings to integers
int a1 = Integer.parseInt(n1);
int b1 = Integer.parseInt(n2);
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("a1 + b1 = " + (a1 + b1));
}}
Output
a + b = 13
a-b=7
a * b = 30
a/b =3
a%b=1
a1 + b1 = 40
2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or
negate a value.
• - , Negates the value.
• + , Indicates a positive value (automatically converts byte, char, or short to int).
• ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
• -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
• ! , Inverts a boolean value.
Example: This example demonstrates the use of unary operators for post-
increment, pre-increment, post-decrement, and pre-decrement operations.
// Java Program to show the use of
// Unary Operators
import java.io.*;
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Integer declared
int a = 10;
int b = 10;
// Using unary operators
System.out.println("Postincrement:"+ (a++));
System.out.println("Preincrement : " + (++a));
System.out.println("Postdecrement:"+(b--));
System.out.println("Predecrement : " + (--b));
}}
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
'=' The assignment operator is used to assign a value to any variable. It has right-to-
left associativity, i.e. value given on the right-hand side of the operator is assigned to
the variable on the left, and therefore right-hand side value must be declared before
using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5. Common
compound operators include:
• += , Add and assign.
• -= , Subtract and assign.
• *= , Multiply and assign.
• /= , Divide and assign.
• %= , Modulo and assign.
Example: This example demonstrates the use of various assignment operators,
including compound, bitwise, and shift operators, for modifying a variable.
// Java Program to show the use of
// Assignment Operators
import java.io.*; // Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR" operations,
similar to AND gate and OR gate in digital electronics. They have a short-circuiting
effect, meaning the second condition is not evaluated if the first is false.
Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Example: This example demonstrates the use of logical operators (&&, ||, !) to
perform boolean operations.
// Java Program to show the use of
// Logical operators
import java.io.*;
class Geeks {
// Main Function
public static void main (String[] args)
{
// Logical operators
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x)); }}
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary. The general format is,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the '?' else execute the statements after the ':'.
Example: This example demonstrates the use of the ternary operator to find the
maximum of three numbers.
// Java program to illustrate
// max of three numbers using// ternary operator.
public class Geeks {
Output
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby multiplying
or dividing the number by two, respectively. They can be used when we have to
multiply or divide a number by two. The general format ,
number shift_op number_of_places_to_shift;
• << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
• >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of two),
with the leftmost bit depending on the sign.
• >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit always
0.
Example: This example demonstrates the use of shift operators (<<, >>) to shift
the bits of a number left and right.
// Java Program to show the use of
// shift operators
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int a = 10;
// Using left shift
System.out.println("a<<1 : " + (a << 1));
// Using right shift
System.out.println("a>>1 : " + (a >> 1));
}}
Output
a<<1 : 20
a>>1 : 5
9. instanceof Operator
The instanceof operator is used for type checking. It can be used to test if an object
is an instance of a class, a subclass, or an interface. The general format,
object instance of class/subclass/interface
Example: This example demonstrates the use of the instanceof operator to
check if an object is an instance of a specific class or interface
// Java program to show the use of
// Instance of operator
public class Geeks {
public static void main(String[] args)
{
Person obj1 = new Person();
Person obj2 = new Boy();
// As obj is of type person, it is not an
// instance of Boy or interface
System.out.println("obj1 instanceof Person: "+ (obj1 instanceof Person));
System.out.println("obj1 instanceof Boy:” + (obj1 instanceof Boy)); System.out.println("obj1
instanceof MyInterface: "+ (obj1 instanceof MyInterface)); // Since obj2 is of type boy,
// whose parent class is person
// and it implements the interface Myinterface
// it is instance of all of these classes
Output
obj1 instanceof Person: true
obj1 instanceof Boy: false
obj1 instanceof MyInterface: false
obj2 instanceof Person: true
obj2 instanceof Boy: true
obj2 instanceof MyInterface: true
Precedence and associative rules are applied when dealing with hybrid equations
that involve more than one type of operator. In such cases, these rules determine
which part of the equation to consider first, as there can be many different valuations
for the same equation.
Operator Precedence in Java
In Java, operator precedence specifies the order in which operations are performed
within an expression. When an expression contains multiple operators, those with
higher precedence are evaluated before those with lower precedence.
For expression:
10+20*30
The expression contains two operators, + (addition) and * (multiplication). According
to operator precedence, multiplication (*) has higher precedence than addition (+),
so multiplication is checked first. After evaluating multiplication, the addition operator
is then evaluated to give the final result.
Operator Precedence
Example:
public class OperatorPrecedenceExample {
public static void main(String[] args)
{
Output
Result: 610
Explanation:
• In the following code (multiplication) has higher precedence than + (addition).
• So in 10 + 20 * 30, the multiplication happens first:
20 * 30 = 600 // first execute this expression
10 + 600 = 610// next execute this expression
Operator Precedence Table in Java
The table below illustrates the precedence of operators in decreasing order of
magnitude, with the top row representing the highest precedence and the bottom
row showing the lowest preced
ence.
Output
Final output 7
Explanation: Here, - and + have the same precedence and are left-associative, so
evaluation happens left to right.
2. Right-to-Left Associativity
Right-to-Left Associativity means that operators are evaluated from right to left when
they have the same precedence.
Operators with right-to-left associativity include:
• Assignment operators: =, +=, -=, etc.
• Unary operators: ++, --, !, ~
public class RightToLeftAssociativity {
public static void main(String[] args) { int a, b; a = b = 4; // evaluated as a = (b = 4)
System.out.println("a: " + a); // 4 System.out.println("b: " + b); // 4 }}
Outputa: 4
b: 4
Operator Precedence
Example: Now see how this expression evaluate:
int exp = 100 + 200 / 10 - 3 * 10;
public class OperatorPrecedence {
public static void main(String[] args)
{
int result = 100 + 200 / 10 - 3 * 10;
Output
Final Output: 90
Explanation:
• * and / have higher precedence than + and -
200 / 10 = 20
3 * 10 = 30 // Evaluate left to right:
• + and - have same precedence, evaluated left to right:
100 + 20 = 120
120 - 30 = 90 // Evaluate left to right
Java provides various Streams with its I/O package that helps the
user to perform all the input-output operations. These streams
support all the types of objects, data-types, characters, files, etc., to
fully execute the I/O operations.
The image below demonstrates the flow of data from a source to
a destination.
Output
GfG! GfG! GfG!
Output
GfG!
GfG!
GfG!
Output
Printing simple integer: x = 100
Formatted with precision: PI = 3.14
Formatted to specific width: n = 5.2000
Formatted to right margin: n = 2324435.2500
System.err Example
It is used to display the error messages. It works similarly to
System.out with print(), println(), and printf() methods.
Example:
// Java Program demonstrating System.err
public class Geeks {
// Using print()
System.err.print("This is an error message using print().\n");
// Using println()
System.err.println("This is another error message using println().");
//Using printf()
System.err.printf("Error code: %d, Message: %s%n", 404, "Not Found");
}
}
Output:
This is an error message using print().
This is another error message using println().
Error code: 404, Message: Not Found
Types of Streams
Depending on the type of operations, streams can be divided into
two primary classes:
1. Input Stream: These streams are used to read data that must
be taken as an input from a source array or file or any peripheral
device. For eg., FileInputStream, BufferedInputStream,
ByteArrayInputStream etc.
BufferedInputStrea
It is used for Buffered Input Stream.
m
BufferedOutputStre
This is used for Buffered Output Stream.
am
Example:
// Java Program illustrating the
// Byte Stream to copy
// contents of one file to another file.
import java.io.*;
public class Geeks {
public static void main(
String[] args) throws IOException
{
try {
sourceStream
= new FileInputStream("sorcefile.txt");
targetStream
= new FileOutputStream("targetfile.txt");
Output:
Shows contents of file test.txt
2. CharacterStream: In Java, characters are stored using Unicode
conventions (Refer this for details). Character stream automatically
allows us to read/write data character by character. Though it has
many classes, the FileReader and the FileWriter are the most
popular ones. FileReader and FileWriter are character streams
used to read from the source and write to the destination
respectively.
Here is the list of various CharacterStream Classes:
Stream class Description
Example:
// Java Program illustrating that
// we can read a file in a human-readable
// format using FileReader
try {
sourceStream = new FileReader("test.txt");
Note: Please make sure that the file test.txt is in the same
directory, this file contains the text which we want to read.
Vis