Java Programming Basics and Features
Java Programming Basics and Features
Platform Independent:
Java is famous for its Write Once, Run Anywhere (WORA)
feature. This means we can write our Java code once, and it
will run on any device or operating system if Java Virtual
Machine is installed.
Simple:
No complex features like pointers and multiple inheritance,
which makes it a good choice for beginners.
Object-Oriented:
This makes code clean and reusable.
Secured:
Since there are no pointers, it has built-in protections to keep
our programs secure from common problems like memory
leakage and segment fault.
Multithreading:
Programs can do many things at the same time using multiple
threads. This is useful for handling complex tasks like
processing transactions.
Just-In-Time (JIT) Compiler:
Java uses a JIT compiler. It improves performance by converting
the bytecode into machine readable code at the time of
execution.
Example Of 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.
Example:
Output:
Hello World
2. Non-Primitive:
String
Arrays
Classes
Interfaces
Objects
Output:
byte: 100
short: 30000
int: 100000
long: 10000000000
float: 3.14
double: 3.14159265359
char: A
boolean: true
String: Hello, Java
Array: 1 2 3 4 5
Wrapper Integer: 50
StringBuilder: Java
Variables In Java:
Syntax:
Data type Variable Name= “Value”;
Now let us discuss different types of variables which are listed as follows:
Local Variables
Instance Variables
Static Variables
1. Local Variables :
[Link] Variables:
[Link] 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.
Keywords:
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.
List out:
Abstract
Boolean
Char
Break
Byte
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.
1. Arithmetic Operators:
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
- : Subtraction
Example:
class Geeks
{
public static void main (String[] args)
{
}
}
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:
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
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.
Example:
// Driver Class
class Geeks {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
[Link]("f ^= 0b1010: " + (f ^= 0b1010));
[Link]("f <<= 2: " + (f <<= 2));
[Link]("f >>= 1: " + (f >>= 1));
[Link]("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
4. Relational Operators
Relational Operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements.
The general format is ,
variable relation_operator value
Example:
// Driver Class
class Geeks {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
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:
// Java Program to show the use of
// Logical operators
import [Link].*;
class Geeks {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
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:
Output:
Max of three numbers = 30
7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual
bits of a number and with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
& (Bitwise AND): returns bit-by-bit AND of input values.
| (Bitwise OR): returns bit-by-bit OR of input values.
^ (Bitwise XOR): returns bit-by-bit XOR of input values.
~ (Bitwise Complement): inverts all bits (one's complement).
Example:
class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
Output:
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
Expressions:
An expression is a combination of operators, constants and
variables. An expression may consist of one or more operands, and zero
or more operators to produce a value.
Example:
Result = a + b * c ..
Types of Expressions:
Constant expressions
Integral expressions
Floating expressions
Relational expressions
Logical expressions
Pointer expressions
Bitwise expressions
Constant expressions:
Constant Expressions consists of only constant values. A
constant value is one that doesn't change.
Examples:
5, 10 + 5 / 6.0, 'x’
Integral expressions:
Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Examples:
x, x * y, x + int( 5.0)
Examples:
x + y, 10.75
where x and y are floating point variables.
Relational expressions:
Relational Expressions yield results of type bool which takes
a value true or false. When arithmetic expressions are used on
either side of a relational operator, they will be evaluated first and
then the results compared.
Relational expressions are also known as Boolean expressions.
Examples:
x <= y, x + y > 2
Logical expressions:
Logical Expressions combine two or more relational
expressions and produces bool type results.
Examples:
x > y && x == 10, x == 10 || y == 5
Pointer expressions:
Pointer Expressions produce address values. Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate
data at bit level. They are basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right. Shift operators are often used for
multiplication and division by powers of two.
Control statements:
If
If-else
Nested if
if-else-if
switch case
jump- break, continue, return.
If Statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or not
i.e. if a certain condition is true then a block of statements is executed otherwise
not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Example:
import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
Output:
Inside If block
10 is less than 15
I am Not in if
If-else Statement:
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won't. But what if we want to do
something else if the condition is false? Here, comes the "else" statement.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
Example:
import [Link].*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}
Output:
i is smaller than 15
Nested if :
Nested if in Java refers to having one if statement inside another if
statement. If the outer condition is true the inner conditions are checked and
executed accordingly. Nested if condition comes under decision-making statement
in Java, enabling multiple branches of execution.
Syntax of Nested if:
if (condition1) {
if (condition2) {
if (condition3) {
// statements;
}
}
}
Example:
class Geeks {
public static void main(String args[]) {
int i = 10;
// Outer if statement
if (i < 15) {
[Link]("i is smaller than 15");
// Nested if statement
if (i == 10) {
[Link]("i is exactly 10");
}
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too
If-else-if:
The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that 'if' is
executed, and the rest of the ladder is bypassed.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
Example:
import java. util.*;
class Geeks {
public static void main(String args [])
{
int i = 20;
if (i == 10)
System. out. println("i is 10");
else if (i == 15)
System. out. println("i is 15");
else if (i == 20)
System. out. println("i is 20");
else
System. out. println("i is not present");
}
}
Output:
i is 20
Switch Case:
The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}
Example:
import [Link].*;
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
[Link]("It is 5");
break;
case 10:
[Link]("It is 10");
break;
case 15:
[Link]("It is 15");
break;
case 20:
[Link]("It is 20");
break;
default:
[Link]("Not present");
}
}
}
Output:
It is 20
6. jump Statements:
Java supports three jump statements: break, continue and return.
These three statements transfer control to another part of the program.
import [Link].*;
class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
Output:
13579
Return Statement:
The return statement is used to explicitly return from a method. That is, it
causes program control to transfer back to the caller of the method.
Example:
import [Link].*;
public class Geeks {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if (t)
return;
Output:
Before the return.
// File: [Link]
class Student {
int id;
String n;
// File: [Link]
public class Main {
public static void main(String[] args) {
[Link]([Link]);
[Link](s1.n);
}
}
Output:
10
Alice
access_modifier class<class_name> {
data member;
method;
constructor;
nested class;
interface
;
}
Constructors:
constructors play an important role in object creation. A constructor is a
special block of code that is called when an object is created.
Its main job is to initialize the object, to set up its internal state, or to
assign default values to its attributes.
This process happens automatically when we use the "new" keyword to
create an object.
Syntax:
class Geek
{
......
// A Constructor
Geek() {
}
.......
}
// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Geek obj = new Geek();
Default Constructor
Parameterized Constructor
Copy Constructor
Example:
// Driver class
class Geeks{
// Default Constructor
Geeks() {
[Link]("Default constructor");
}
// Driver function
public static void main(String[] args)
{
Geeks hello = new Geeks();
}
}
Output:
Default constructor
Example:
// Java Program for Parameterized Constructor
import [Link].*;
class Geeks {
String name;
int id;
[Link] = name;
[Link] = id;
}
class GFG
Output:
GeekName: Sweta and GeekId: 68
Example:
// Java Program for Copy Constructor
import [Link].*;
class Geeks {
int id;
// Parameterized Constructor
[Link] = name;
[Link] = id;
// Copy Constructor
Geeks(Geeks obj2)
[Link] = [Link];
[Link] = [Link];
class GFG {
[Link]("First Object");
[Link]();
[Link](
Output:
First Object
When there are overloaded methods that accept both a parent type and a
child type, and the provided argument could match either one, Java prefers
the method that takes the more specific (child) type.
Overloading does not depend on the return type of the method, two
methods cannot be overloaded by just changing the return type.
Example:
// Java program to demonstrate working of method
// overloading in Java
// Overloaded sum()
return (x + y + z);
// Overloaded sum()
return (x + y);
// Driver code
[Link]([Link](10, 20));
[Link]([Link](10.5, 20.5));
}
Output:
30
60
31.0
Number of Parameters:
Method overloading can be achieved by changing the number of
parameters while passing to different methods.
Type of Parameters:
methods can be considered overloaded if they have the same name but
have different parameter types, methods are considered to be overloaded.
For example, if the parameters of method 1 are (String name, int roll_no)
and the other method is (int roll_no, String name) but both have the same name,
then these 2 methods are considered to be overloaded with different sequences
of parameters.
Arrays in Java:
an array is an important linear data structure that allows us to store
multiple values of the same type.
Arrays in Java are objects, like all other objects in Java, arrays implicitly
inherit from the [Link] class. This allows you to invoke
methods defined in Object (such as toString(), equals() and
hashCode()).
Example:
public class Geeks {
// initializing array
// size of array
int n = [Link];
// traversing array
Output:
40 55 63 17 22 68 89 97 89
// Method 1:
int arr[];
// Method 2:
int[] arr;
The element type determines the data type of each element that comprises the
array. Like an array of integers, we can also create an array of other primitive data
types like char, float, double, etc. or user-defined data types (objects of a class).
Array Declaration is generally static, but if the size in not defined, the Array
is Dynamically sized.
class Geeks {
int[] arr;
arr[0] = 2;
arr[1] = 4;
arr[2] = 8;
arr[3] = 12;
arr[4] = 16;
}
}
Output
Element at index 0 : 2
Element at index 1 : 4
Element at index 2 : 8
Element at index 3 : 12
Element at index 4 : 16
Strings In Java:
String is the type of object that can store a sequence of characters
enclosed by double quotes and every character is stored in 16 bits.
Example:
String name = "Geeks";
String num = "1234";
Program:
public class Geeks {
// Main Function
[Link](str);
Output:
Geeks
String Literal
Example:
String str = “GeeksforGeeks”;
In such a case, JVM will create a new string object in normal (non-pool)
heap memory and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in the heap (non-pool)
Example:
String str = new String (“GeeksforGeeks”);
1. String:
String is an immutable class in Java, which means that once a String object
is created, its value cannot be changed. If you want to modify a string a new
String object is created and the original remains unchanged.
Syntax:
// Method 1
String str= "geeks";
// Method 2
String str= new String("geeks");
2. StringBuffer:
StringBuffer is a peer class of String, it is mutable in nature and it is
thread safe class , we can use it when we have multi threaded
environment and shared object of string buffer i.e, used by mutiple
thread.
Syntax:
StringBuffer demoString = new StringBuffer("GeeksforGeeks");
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer
Class, as it creates a mutable sequence of characters and it is not thread
safe.
Syntax:
StringBuilder demoString = new StringBuilder();
[Link]("GFG");
4. StringTokenizer:
StringTokenizer class in Java is used to break a string into tokens.
Syntax:
public StringJoiner(CharSequence delimiter)
Inheritance in Java:
Java Inheritance is a fundamental concept in OOP(Object-Oriented
Programming). It is the mechanism in Java by which one class is allowed
to inherit the features(fields and methods) of another class.
Example:
In the following example, Animal is the base class and Dog, Cat and
Cow are derived classes that extend the Animal class.
Implementation:
// Parent class
class Animal {
void sound() {
// Child class
void sound() {
[Link]("Dog barks");
// Child class
void sound() {
[Link]("Cat meows");
// Child class
void sound() {
[Link]("Cow moos");
// Main class
a = new Dog();
[Link]();
a = new Cat();
[Link]();
a = new Cow();
[Link]();
Output:
Dog barks
Cat meows
Cow moos
Constructors in Inheritance:
In Java, when a class inherits another class, the constructor of the parent
class is executed first, followed by the constructor of the child class. This ensures
that the base class is properly initialized before the derived class adds its own
functionality.
Example:
class Parent {
Parent() {
Child() {
Output:
Parent class constructor called
Child class constructor called
Explanation:
Constructor chaining refers to the process where one constructor calls another
constructor in the same or parent class using this() or super() .
Example:
class A {
A() {
[Link]("Constructor of A");
class B extends A {
B() {
[Link]("Constructor of B");
}
class C extends B {
C() {
[Link]("Constructor of C");
Output:
Constructor of A
Constructor of B
Constructor of C
Explanation:
The super() calls ensure that constructors are called from the base class to
the derived class in the correct order.
The method in the child class must have the same name as in the
parent class.
Example:
// Parent class
class Animal {
void makeSound() {
// Child class
class Dog extends Animal {
@Override
void makeSound() {
[Link]("Dog barks");
// Main class
Output:
Animal makes a sound
Dog barks
Super Class in Java:
The super keyword in Java is a reference variable that is used to refer to the
parent class when we are working with objects. You need to know the basics
of Inheritance and Polymorphism to understand the Java super keyword.
Accessing Parent Class Fields: Fields from the parent class can also be
accessed using the super keyword in the subclass.
Not Always Required: We know that the super keyword is used to call the
methods from the parent class. If a method is not overridden in the
subclass, then calling it without the super keyword will invoke the parent
class's implementation.
Use of super Class in Java
Super Keyword are mainly used in the following contexts which are listed
below:
1. Use of super with Variables:
This scenario occurs when a derived class and base class have the same data
members. In that case, there is a possibility of ambiguity for the JVM.
Real-world example: Suppose there is a child, whose name is "Max" and the child
has also a parent named "Max". Normally, to refer to the parent, we would say
"parent Max", this is similar to using [Link].
Program:
// Super keyword with variable
class Vehicle {
void display()
// using super
// Driver Program
class Test {
[Link]();
Output
Maximum Speed: 120
Program:
// superclass Person
class Person {
void message()
// Subclass Student
void message()
void display()
message();
// will invoke or call parent
[Link]();
// Driver Program
class Test {
[Link]();
Output
This is student class
Real-world Example: Before a child born, first the parent exists. Similarly, the
parent class constructor must be called before the child's constructor finishes it's
work.
Program:
// superclass Person
class Person {
Person()
Student()
super();
}
// Driver Program
class Test {
Output
Person class Constructor
Subclasses can override methods and can access fields and methods from
their parent class with the help of super keyword, because of this the code
becomes more flexible.
With the help of super keyword we can easily access the methods and
fields from the parent class without recreating it in the subclass.
Example:
Shape(String name) {
[Link] = name;
super(name);
[Link] = length;
[Link] = width;
}
// Implementation of draw method for rectangle
@Override
@Override
double pi = 3.14;
int radius;
[Link] = radius;
@Override
@Override
[Link](1, 2);
[Link]();
[Link](2, 4);
Output
Area of rectangle: 6.0
Interface in Java
Definition: An interface is a reference type in Java, it is similar to a class,
and it is a collection of abstract methods and static constants.
Example:
interface Drawable {
void draw();
interface Movable {
Circle(int radius) {
[Link] = radius;
@Override
@Override
[Link]();
[Link](2, 4);
Output:
Example:
if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed. Here is an example that illustrates
dynamic method dispatch:
Program:
class A
void m1()
class B extends A
// overriding m1()
void m1()
{
[Link]("Inside B's m1 method");
class C extends A
// overriding m1()
void m1()
// Driver class
class Dispatch
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
A ref;
ref = a;
ref.m1();
ref = b;
ref.m1();
ref = c;
// calling C's version of m1()
ref.m1();
Output:
Inside A's m1 method
Packages in Java:
Packages are used for organizing and sharing code in Java.
The 'import' keyword is used to import a package into an existing Java file.
[Link].*: The java package is the main package and serves as the default
package. The lang package is a subpackage.
class Shape {
void color() {
void cal_area() {
[Link]("Calculating area.");
}
void cal_square() {
[Link]("Calculating square");
1. Built-in Exceptions
Checked Exception
Unchecked Exception
2. user-defined Exceptions
1. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to
handle common errors during program execution. There are two type of built-in
exception in java.
Checked Exceptions
Unchecked Exceptions
The unchecked exceptions are just opposite to the checked exceptions. The
compiler will not check these exceptions at compile time.
2. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called "user-
defined Exceptions".
Methods to Print the Exception Information
1. printStackTrace(): Prints the full stack trace of the exception, including the
name, message and location of the error.
Try-Catch Block
Java Virtual Machine starts executing the code inside the try block.
If an exception occurs, the remaining code in the try block is skipped and
the JVM starts looking for the matching catch block.
After the catch block, control moves to the finally block (if present).
The final block is executed after the try catch block. regardless of whether
an exception occurs or not.
Syntax:
try {
} catch (ExceptionType e) {
Nested try-catch:
In Java, you can place one try-catch block inside another to handle exceptions at
multiple levels.
try {
try {
} catch (ArithmeticException e) {
} catch (NullPointerException e) {
finally Block:
The finally block is used to execute important code regardless of whether an
exception occurs or not.
Syntax:
try {
catch (ExceptionType e) {
finally{
// cleanup code
Propagation of errors.