Chap 1 Introduction To Java
Chap 1 Introduction To Java
1 : Java Fundamentals
Introduction to Java:
• Java is one of the most popular programming languages.
• Java's slogan is "Write once, run anywhere". Java programs can run on different platforms,
including mobile, desktop, and other portable systems. You can use Java to build apps,
games, banking applications, web apps, and much more!
• Java is a popular high-level, object-oriented programming language that was originally
developed by Sun Microsystems and released in 1995. Currently, Java is owned by Oracle,
and more than 3 billion devices run Java.
• The first example in Java is to print "Hello, World!" on the screen.
Java Features:
Java is a feature-rich language. Java is evolving continuously with every update, and updates are
coming every six months. Following are some of the main features of the Java language:
Basics of Java:
❖ Data Types:
Java data types define the type and value range of the data for the different types of variables,
constants, method parameters, return types, etc. The data type tells the compiler about the type of
data to be stored and the required memory. To store and manipulate different types of data, all
variables must have specified data types.
Based on the data type of a variable, the operating system allocates memory and decides what can
be stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals, or characters in these variables.
The Java data types are categorized into two main categories −
1. Primitive Data Types
2. Reference/Object Data Types
1. Java Primitive Data Types
Primitive data types are predefined by the language and named by a keyword. There are eight
primitive data types supported by Java. Below is the list of the primitive data types:
❖ byte
❖ short
❖ int
❖ long
❖ float
❖ double
❖ boolean
Example:-
public class JavaTester {
public static void main(String args[]) {
byte byteValue1 = 2;
byte byteValue2 = 4;
byte byteResult = (byte)(byteValue1 + byteValue2);
System.out.println("Byte: " + byteResult);
short shortValue1 = 2;
short shortValue2 = 4;
short shortResult = (short)(shortValue1 + shortValue2);
System.out.println("Short: " + shortResult);
int intValue1 = 2;
int intValue2 = 4;
int intResult = intValue1 + intValue2;
System.out.println("Int: " + intResult);
The non-primitive data types are not predefined. The reference data types are created using defined
constructors of the classes. They are used to access objects. These variables are declared to be of
a specific type that cannot be changed. For example, Employee, Puppy, etc.
The following are the non-primitive (reference/object) data types −
• String: The string is a class in Java, and it represents the sequences of characters.
• Arrays: Arrays are created with the help of primitive data types and store multiple values
of the same type.
• Classes: The classes are the user-defined data types and consist of variables and methods.
• Interfaces: The interfaces are abstract types that are used to specify a set of methods.
The default value of any reference variable is null. A reference variable can be used to refer to any
object of the declared type or any compatible type.
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.
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;-
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.
Variables Types
• Local variables
• Instance variables
• Class/Static variables
1. 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.
2. 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.
import java.io.*;
public class Employee {
Output:-
name : Ransika
salary :1000.0
3. 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.
• Static variables can be accessed by calling with the class name ClassName.VariableName.
import java.io.*;
public class Employee {
output:-
Development average salary:1000
Expression
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.
operators
Java operators are the symbols that are used to perform various operations on variables and values.
By using these operators, we can perform operations like addition, subtraction, checking less than
or greater than, etc.
There are different types of operators in Java, we have listed them below −
• Arithmetic Operators
• Assignment Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Misc Operators
Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators −
Operator Description
+ (Addition) Adds values on either side of the operator.
Example
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 5;
// Addition
System.out.println("a + b = " + (a + b)); // 15
// Subtraction
System.out.println("a - b = " + (a - b)); // 5
// Multiplication
System.out.println("a * b = " + (a * b)); // 50
// Division
System.out.println("a / b = " + (a / b)); // 2
// Modulus
System.out.println("a % b = " + (a % b)); // 0
}
}
OUTPUT:-
a + b = 15
a-b=5
a * b = 50
a/b=2
a%b=0
Assignment Operators:
Assignment Operators are used to assign values to variables. These operators modify the value of
a variable based on the operation performed. The most commonly used assignment operator is =,
but Java provides multiple compound assignment operators for shorthand operations.
+= Add AND assignment operator. It adds right operand to the left operand
and assign the result to left operand.
/= Divide AND assignment operator. It divides left operand with the right
operand and assign the result to left operand.
Example:-
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
Relational Operators:
Relational operators are used to compare two values. These operators return a boolean result: true
if the condition is met and false otherwise. Relational operators are commonly used in decision-
making statements like if conditions and loops.
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then –
Operator Description
== (equal to) Checks if the values of two operands are equal or not, if yes then condition
becomes true.
!= (not equal to) Checks if the values of two operands are equal or not, if values are not equal
then condition becomes true.
> (greater than) Checks if the value of left operand is greater than the value of right operand, if
yes then condition becomes true.
< (less than) Checks if the value of left operand is less than the value of right operand, if
yes then condition becomes true.
>= (greater than or Checks if the value of left operand is greater than or equal to the value of right
equal to) operand, if yes then condition becomes true.
<= (less than or Checks if the value of left operand is less than or equal to the value of right
equal to) operand, if yes then condition becomes true.
Example:-
public class RelationalExample {
public static void main(String[] args) {
int A = 10, B = 5;
Logical Operators
Logical operators are used to perform logical operations on boolean values. These operators are
commonly used in decision-making statements such as if conditions and loops to control program
flow.
The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −
Example:-
public class LogicalExample {
public static void main(String[] args) {
boolean A = true, B = false;
Bitwise Operators:
Bitwise operators are used to perform operations at the binary (bit) level. These operators work on
individual bits of numbers. They are commonly used in low-level programming, encryption, and
performance optimization.
Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13;
now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
<< (left shift) Binary Left Shift Operator. The left operands A << 2 will give 240 which is
value is moved left by the number of bits specified 1111 0000
by the right operand.
>> (right shift) Binary Right Shift Operator. The left operands A >> 2 will give 15 which is
value is moved right by the number of bits 1111
specified by the right operand.
>>> (zero fill Shift right zero fill operator. The left operands A >>>2 will give 15 which is
right shift) value is moved right by the number of bits 0000 1111
specified by the right operand and shifted values
are filled up with zeros.
Example
public class BitwiseExample {
public static void main(String[] args) {
int A = 60; // 0011 1100
int B = 13; // 0000 1101
Constants in Java
A constant is a variable whose value cannot be changed once it has been initialized. Java doesn't
have built-in support for constants. To define a variable as a constant, we just need to add the
keyword "final" in front of the variable declaration.
It is not mandatory that we assign values to constants during declaration.
The above statement declares the float variable "pi" as a constant with a value of 3.14f. We cannot
change the value of "pi" at any point in time in the program. Later, if we try to do that by using a
statement like "pi=5.25f", Java will throw errors at compile time itself.
Execution: -
• Java is a platform-independent language, meaning the same program can run on different
operating systems like Windows, Linux, or macOS.
• This platform independence is possible because of the Java Virtual Machine (JVM), which
can run Java bytecode on any system that has a compatible JVM installed.
• We write code in Java using .java files, which are human-readable source code.
• This Java code is compiled by the Java Compiler (javac) into bytecode, which is stored in
.class files.
• Bytecode is a platform-independent, intermediate code that JVM understands, not human-
readable, and not tied to any specific operating system.
• The JVM reads the bytecode and converts it into machine-specific instructions, producing
the final program output.
• We cannot write bytecode directly; we always write Java source code and compile it to
generate bytecode.
• To run a Java program, we must indicate which class contains the main() method, because
it's the starting point of execution for the JVM.
Implementation:
Consider simple printing program is written somewhere on the local directory in a machine.
// Main class
class GFG {
// Print command
System.out.print("Welcome to Java");
}
}
Output:-
Welcome to Java
Let us understand the real compilation and execution process.
Step 1: Let us create a file writing simple printing code in a text file and saving it with ".java"
extension.
Step 2: Open the terminal(here we are using macOS)and go to the Desktop directory using the
command below as follows.
cd /Users/mayanksolanki/GFG.java
Step 3: Let us try to compile our program with the below command
javac GFG.java
Step 4: Lastly, run it with the below command as follows:
java GFG
Example:
/*Slip 11A – Write a menu driven java program using command line arguments for the following:
1. Addition
2. Subtraction
3. Multiplication
4. Division*/
package com.slipsprogram;
switch (op.toLowerCase()) {
case "add":
System.out.println("Addition: " + (a + b));
break;
case "sub":
System.out.println("Subtraction: " + (a - b));
break;
case "mul":
System.out.println("Multiplication: " + (a * b));
break;
case "div":
if (b != 0)
System.out.println("Division: " + ((float) a / b));
else
System.out.println("Cannot divide by zero");
break;
default:
System.out.println("Invalid operation");
}
}
}
Steps to Run the programs:-
1. Right click on program
2.
3. Select your project and main class and Click on Apply
4. Go to Arguments Tab give the arguments in program arguments click on apply and click
on run
Arrays in Java :
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
java.lang.Object class. This allows you to invoke methods defined in Object (such as
toString(), equals() and hashCode()).
• Arrays have a built-in length property, which provides the number of elements in the array
• The index of an array starts from 0.
public class Hello {
public static void main(String[] args) {
// initializing array
int[] arr = { 40,55,63,17,22,68,89,97,89};
// size of array
int n = arr.length;
// traversing array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
Output:
40 55 63 17 22 68 89 97 89
One-Dimensional Array
• One of the most commonly used types of arrays is the one-dimensional array. It represents
a simple list of elements where each item can be accessed using a single index.
• Basic operations on a one-dimensional array is include the accessing elements, inserting
elements, deleting elements, searching for elements and sorting elements.
• This Java program demonstrates the implementation of the one-dimensional array and it
performs the basic operations like initialization, accessing elements, inserting elements,
deleting elements, searching for elements and sorting elements:
import java.util.Arrays;
// Driver Class
public class Hello {
// Main Function
public static void main(String[] args)
{
// Initializing an array
int[] numbers = new int[5];
System.out.println(
"Array after deleting element at index 2: "
+ Arrays.toString(numbers));
arr[arr.length - 1] = 0;
// Set the last element to 0 or default
// value
}
}
Output:-
Element at index 0: 10
Element at index 3: 50
Array after deleting element at index 2: [10, 30, 50, 40, 0]
Element 30 found at index 1
Sorted array: [0, 10, 30, 40, 50]
syntax:-
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]....[sizeN];
Parameters:
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created. For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, ..., sizeN: Sizes of the dimensions respectively.
Examples:
Program:-
import java.io.*;
String represents sequence of characters enclosed within the double quotes. “abc”, “JAVA”,
“123”, “A” are some examples of strings. In many languages, strings are treated as character
arrays. But In java, strings are treated as objects. To create and manipulate the strings, Java
provides three classes.
• All these three classes are members of java.lang package and they are final classes. That
means you can’t create subclasses to these three classes.
• All three classes implement Serializable and CharSequence interface.
• java.lang.String objects are immutable in java. That is, once you create String objects, you
can’t modify them. Whenever you try to modify the existing String object, a new String
object is created with modifications. Existing object is not at all altered. Where as
java.lang.StringBuffer and java.lang.StringBuilder objects are mutable. That means, you
can perform modifications to existing objects.
• Only String and StringBuffer objects are thread safe. StringBuilder objects are not thread
safe. So whenever you want immutable and thread safe string objects, use java.lang.String
class and whenever you want mutable as well as thread safe string objects then use
java.lang.StringBuffer class.
• In all three classes, toString() method is overrided. So. whenever you use reference
variables of these three types, they will return contents of the objects not physical address
of the objects.
• hashCode() and equals() methods are overrided only in java.lang.String class but not in
java.lang.StringBuffer and java.lang.StringBuilder classes.
• There is no reverse() and delete() methods in String class. But, StringBuffer and
StringBuilder have reverse() and delete() methods.
• In case of String class, you can create the objects without new operator. But in case of
StringBuffer and StringBuilder class, you have to use new operator to create the objects.
In Java, Packages are used to avoid naming conflicts and to control the access of classes, interfaces,
sub-classes, etc. A package can be defined as a group of similar types of classes, sub-classes,
interfaces, or enumerations, etc. Using packages makes it easier to locate or find the related classes
and packages provide a good structure or outline of the project with a huge amount of classes and
files.
Types of Packages in Java
Packages are divided into two parts, which are listed below:
• Built-in packages: These are the predefined packages provided by the JDK (Java
Development Kit). They are present in the .jar files and include packages such as java.lang,
java.util, and java.io
• User-defined packages: These packages are created by us to organize our own classes and
interfaces in a meaningful way.
Provides classes that are fundamental to the design of the Java programming language. The most
important classes are Object, which is the root of the class hierarchy, and Class, instances of which
represent classes at run time.
Following are the Important Classes in Java.lang package :
• Boolean: The Boolean class wraps a value of the primitive type boolean in an object.
• Byte: The Byte class wraps a value of primitive type byte in an object.
• Character – Set 1, Set 2: The Character class wraps a value of the primitive type char in an
object.
• Character.Subset: Instances of this class represent particular subsets of the Unicode character
set.
• Character.UnicodeBlock: A family of character subsets representing the character blocks in
the Unicode specification.
• Class – Set 1, Set 2 : Instances of the class Class represent classes and interfaces in a running
Java application.
• ClassLoader: A class loader is an object that is responsible for loading classes.
• ClassValue: Lazily associate a computed value with (potentially) every type.
• Compiler: The Compiler class is provided to support Java-to-native-code compilers and
related services.
• Double: The Double class wraps a value of the primitive type double in an object.
• Enum: This is the common base class of all Java language enumeration types.
• Float: The Float class wraps a value of primitive type float in an object.
• InheritableThreadLocal: This class extends ThreadLocal to provide inheritance of values
from parent thread to child thread: when a child thread is created, the child receives initial
values for all inheritable thread-local variables for which the parent has values.
• Integer :The Integer class wraps a value of the primitive type int in an object.
• Long: The Long class wraps a value of the primitive type long in an object.
• Math – Set 1, Set 2: The class Math contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric functions.
• Number: The abstract class Number is the superclass of classes BigDecimal, BigInteger, Byte,
Double, Float, Integer, Long, and Short.
• Object: Class Object is the root of the class hierarchy.
• Package: Package objects contain version information about the implementation and
specification of a Java package.
• Process: The ProcessBuilder.start() and Runtime.exec methods create a native process and
return an instance of a subclass of Process that can be used to control the process and obtain
information about it.
• ProcessBuilder: This class is used to create operating system processes.
• ProcessBuilder.Redirect: Represents a source of subprocess input or a destination of
subprocess output.
• Runtime: Every Java application has a single instance of class Runtime that allows the
application to interface with the environment in which the application is running.
• RuntimePermission: This class is for runtime permissions.
• SecurityManager: The security manager is a class that allows applications to implement a
security policy.
• Short: The Short class wraps a value of primitive type short in an object.
• StackTraceElement: An element in a stack trace, as returned by Throwable.getStackTrace().
• StrictMath- Set1, Set2: The class StrictMath contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and trigonometric
functions.
• String- Set1, Set2: The String class represents character strings.
• StringBuffer: A thread-safe, mutable sequence of characters.
• StringBuilder: A mutable sequence of characters.
• System: The System class contains several useful class fields and methods.
• Thread: A thread is a thread of execution in a program.
• ThreadGroup: A thread group represents a set of threads.
• ThreadLocal: This class provides thread-local variables.
• Throwable: The Throwable class is the superclass of all errors and exceptions in the Java
language.
• Void: The Void class is an uninstantiable placeholder class to hold a reference to the Class
object representing the Java keyword void.