java unit 1
java unit 1
I. INTRODUCTION TO JAVA
What is Java
Java is a high Level programming language and it is also called as
a platform. Java is a secured and robust high level object-oriented
programming language.
Platform: Any software or hardware environment in which a
program runs is known as a platform. Java has its own runtime
environment (JRE) and API so java is also called as platform.
Java fallows the concept of Write Once, Run Anywhere.
Application of java
1. Desktop Applications
2. Web Applications
3. Mobile
4. Enterprise Applications
5. Smart Card
6. Embedded System
7. Games
8. Robotics etc
History of Java
The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for digital
devices such as set-top boxes, televisions, etc. However, it was best suited
for internet programming. Later, Java technology was incorporated by
Netscape.
The principles for creating Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was
developed by James Gosling, who is known as the father of Java, in 1995.
James Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices,
games, e-business solutions, etc. Following are given significant
points that describe the history of Java.
11) In 1995, Time magazine called Java one of the Ten Best
Products of 1995.
Java Comments
The java comments are statements that are not executed by the
compiler and interpreter. The comments can be used to provide
information or explanation about the variable, method, class or
any statement. It can also be used to hide program code for
specific time.
Types of Java Comments
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
Example:
1. public class CommentExample2 {
2. public static void main(String[] args) {
3. /* Let's declare and
4. print variable in java. */
5. int j=10;
6. System.out.println(j);
7. }
8. }
short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768
Maximum value is 32,767
Short data type can also be used to save memory as byte
data type. A short is 2 times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648
Maximum value is 2,147,483,647
Integer is generally used as the default data type for integral
values unless there is a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808
Maximum value is 9,223,372,036,854,775,807
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating
point
Float is mainly used to save memory in large arrays of
floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as
currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754
floating point
This data type is generally used as the default data type for
decimal values, generally the default choice
Double data type should never be used for precise values
such as currency
Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false
conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
byte 0 1byte
short 0 2byte
int 0 4byte
long 0L 8byte
Java Variables
A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
o local variable
o instance variable
o static variable
o Example:
o int age = 27; // integer
variable having value 27
DataType Name;
Int count;
From the image, it can be easily perceived that while
declaring a variable, we need to take care of two things that are:
1. datatype: Type of data that can be stored in this variable.
2. data_name: Name was given to the variable.
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
1) local,
2) instance,
3) Static variable and
1) Local Variable
You can use this variable only within that method and the other
methods in the class aren't even aware that the variable exists.
1. public SumExample
2. {
3. public void calculateSum() {
4. int a = 5; // local variable
5. int b = 10; // local variable
6. int sum = a + b;
7. System.out.println("The sum is: " + sum);
8. } // a, b, and sum go out of scope here
9. }
Output:
2) Instance Variable
A variable declared inside the class but outside the body of the
method, is called an instance variable. It is not declared as static.
3)Static Variables:
A variable that is declared as static is called a static variable. It
cannot be local. You can create a single copy of the static variable
and share it among all the instances of the class.
class Employee {
// Static variable
static int companyCode = 12345;
// Instance variables
String name;
int id;
// Constructor
Employee(String name, int id) {
this.name = name;
this.id = id;
}
Constants
In Java, a constant is a variable whose value cannot be changed
once it has been initialized. Constants are typically declared using
the final keyword. They are often combined with static to ensure
there is only one copy shared across all instances of a class.
class ConstantsExample {
// Defining constants
static final double PI = 3.14159; // Static constant
final int MAX_VALUE = 100; // Instance-level constant
Output:
yaml
Copy code
Value of PI: 3.14159
Max Value: 100
Example of Enumeration
1. public class EnumExample
2. {
3. //defining the enum
4. public enum Color {Red, Green, Blue, Purple, Black, White, Pink,
Gray}
5. public static void main(String[] args)
6. {
7. //traversing the enum
8. for (Color c : Color.values())
9. System.out.println(c);
10. }
11. }
Output:
Explanation
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
postfix expr++expr--
Unary
prefix ++expr--expr+expr-expr~!
multiplicative */%
Arithmetic
additive + -
bitwiseAND &
Bitwise bitwiseexclusiveOR ^
bitwiseinclusiveOR |
logicalAND &&
Logical
logicalOR ||
Ternary ternary ? :
=+=-=*=/=%=&=^=|=<<=>>=
Assignment assignment
>>>=
Hierachy Expressions
In Java, the order in which expressions are evaluated is
determined by operator precedence. This hierarchy dictates
which operations are performed first when an expression contains
multiple operators.
Here's a breakdown of the hierarchy:
Highest Precedence (Evaluated First)
Parentheses: ()
Member Access: ., []
Unary Operators: ++, --, +, -, !, ~ (pre-increment, pre-
decrement, unary plus, unary minus, logical NOT, bitwise NOT)
Multiplicative Operators: *, /, % (multiplication, division,
modulus)
Additive Operators: +, - (addition, subtraction)
Shift Operators: <<, >>, >>> (left shift, signed right shift,
unsigned right shift)
Relational Operators: <, >, <=, >=, instanceof (less than,
greater than, less than or equal to, greater than or equal to,
instance of)
Equality Operators: ==, != (equal to, not equal to)
Bitwise AND: &
Bitwise XOR: ^
Bitwise OR: |
Logical AND: &&
Logical OR: ||
Ternary Operator: ?:
Assignment Operators: =, +=, -=, *=, /=, %=, &=, |=, ^= etc.
(assignment, addition assignment, subtraction assignment,
multiplication assignment, etc.)
Lowest Precedence (Evaluated Last)
Example:
Java
int x = 2;
int y = 3;
int z = 4;
Enumerated types
In Java, enumerated types (enums) are a special data type that
allows you to define a set of named constants. Here's how you
can use them:
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY
}
switch (today) {
case MONDAY:
System.out.println("It's Monday!");
break;
case THURSDAY:
System.out.println("It's Thursday!");
break;
default:
System.out.println("It's another
day.");
}
}
}
Explanation:
enum keyword: This keyword is used to define an enum type.
Day: This is the name of the enum type.
SUNDAY, MONDAY, ...: These are the enum constants, which
are named values that represent the possible values of the enum
type.
today: This variable is declared to be of type Day.
switch statement: This statement is used to check the value of
the today variable and execute the corresponding code block.
Block Scope
A block of code refers to all of the code between curly braces {}.
Example
public class Main {
public static void main(String[] args) {
{ // This is a block
int x = 100;
}
}
A block of code may exist on its own or it can belong to
an if, while or for statement. In the case of for statements,
variables declared in the statement itself are also available inside
the block's scope.
IF Statement
The Java if statement tests the condition. It executes the if
block if condition is true. The following is the
syntax
1. if(condition){
2. //code to be executed
3. }
Example
1. public class Example {
2. public static void main(String[] args) {
3. int k=35;
4. if(k>18){ System.out.print("Hello");
5. } } }
IF-else Statement
The if-else statement in java tests the condition. It executes
the if block if condition is true otherwise else block is
executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is false
5. }
Example
public class Sample {
public static void main(String[] args) {
int n=23;
if(number%2==0){
System.out.println("even ");
}else{
System.out.println("odd ");
}}
}
Example:
1. public class Sample {
2. public static void main(String[] args) {
3. int k=20;
4. switch(k){
5. case 10: System.out.println("10");break;
6. case 20: System.out.println("20");break;
7. case 30: System.out.println("30");break;
8. default:System.out.println("Not in 10, 20 or 30");
9. } }
10. }
Example:
1. public class Sample {
2. public static void main(String[] args) {
3. for(int i=1;i<=20;i++){
4. System.out.println(i);
5. }
6. }
7. }
Compilation Flow:
• When we compile Java program using javac tool, the Java
compiler converts the source code into byte code.
Parameters used in First Java Program:
• Let's see what is the meaning of class, public, static, void,
main, String[], System.out.println().
• class keyword is used to declare a class in Java.
public keyword is an access modifier that represents
visibility. It means it is visible to all.
• static is a keyword. If we declare any method as static, it is
known as the static method.
• The core advantage of the static method is that there is no
need to create an object to invoke the static method.
• The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So,
it saves memory.
• void is the return type of the method. It means it doesn't
return any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line
argument.
• System.out.println() is used to print statement. Here,
System is a class, out is an object of the PrintStream class,
println() is a method of the PrintStream class.
• To write the simple program, you need to open notepad
by start menu -> All Programs -> Accessories ->
Notepad and write a simple program as we have shown
below:
Arrays in Java
• Normally, an array is a collection of similar type of elements
which has contiguous memory location.
• Java array is an object which contains elements of a similar
data type.
• Additionally, The elements of an array are stored in a
contiguous memory location.
• It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
• String[] cars;
• System.out.println(cars[0]);
• // Outputs Volvo
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
// Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use
the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Advantages:
• Code Optimization: It makes the code optimized, we can
retrieve or sort the data efficiently.
• Random access: We can get any data located at an index
position.
Disadvantages:
Size Limit: We can store only the fixed size of elements in
the array. It doesn't grow its size at runtime. To solve this
problem, collection framework is used in
class MDArray
{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output:
123
245
445
Java Console
Console Input
For console input, Java provides multiple methods. The most common is using the
Scanner class from the java.util package.
a) Using Scanner
The Scanner class provides methods to read different types of input (e.g.,
nextInt(), nextDouble(), nextLine()).
Example:
java
Copy code
import java.util.Scanner;
String input =
String nextLine()
scanner.nextLine();
double num =
Double nextDouble()
scanner.nextDouble();
boolean flag =
Boolean nextBoolean()
scanner.nextBoolean();
The BufferedReader class reads text from the console more efficiently but
requires explicit conversion for numeric input.
Example:
java
Copy code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
Formatting output
In Java, you can format output using
the System.out.printf() method, which is similar to
the printf() function in C.
Here's how to use it:
Basic Formatting:
Explanation:
%.2f specifies that the floating-point number (pi) should be
formatted with 2 decimal places.
Constructors in java
• In Java, a constructor is a block of codes similar to the
method. It is called when an instance of the class is created.
At the time of calling constructor, memory for the object is
allocated in the memory.
• Parameterized constructor
<class_name>( )
class Bike1
System.out.println("Bike is created");
class Student2
int id;
String name;
Student2(int i,String n)
{
id = i;
name = n;
void display()
System.out.println(id+" "+name);
s1.display();
s2.display();
Output:
111 Karan
222 Aryan
Methods
A method is a block of code which only runs when it is called.
Methods are used to perform certain actions, and they are also
known as functions.
Why use methods? To reuse code: define the code once, and use
it many time
Create a Method
A method must be declared within a class. It is defined with the
name of the method, followed by parentheses (). Java provides
some pre-defined methods, such as System.out.println(),
but you can also create your own methods to perform certain
actions:
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class
and not an object of the Main class. You will learn more
about objects and how to access methods through objects
later in this tutorial.
void means that this method does not have a return
value. You will learn more about return values later in this
chapter
Call a Method
To call a method in Java, write the method's name followed by
two parentheses () and a semicolon;
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
Parameter Passing Techniques in Java with
Examples
Parameter passing in Java refers to the mechanism of transferring data
between methods or functions. Java supports two types of parameters
passing techniques.
1. Call-by-value.
2. Call-by-reference.
Types of Parameters:
1. Formal Parameter:
A variable and its corresponding data type are referred to as formal
parameters when they exist in the definition or prototype of a function or
method. As soon as the function or method is called and it serves as a
placeholder for an argument that will be supplied. The function or
method performs calculations or actions using the formal parameter.
Syntax:
Syntax:
functionName(argument)
1. Call-by-Value:
In Call-by-value the copy of the value of the actual parameter is passed
to the formal parameter of the method. Any of the modifications made to
the formal parameter within the method do not affect the actual
parameter.
1. import java.util.*;
2. public class CallByValueExample
3. {
4. public static void main(String[] args)
5. {
6. int num = 10;
7. System.out.println("Before calling method:"+num);
8. modifyValue(num); // Calling the method and passing the value
of 'num'
9. System.out.println("After calling method:"+num);
10. }
11.
12. public static void modifyValue(int value) {
13.
14. // Modifying the formal parameter
15. value=20; // Assigning a new value to the formal paramet
er as value
16. System.out.println("Inside method:"+value);
17. }
18. }
Output:
Call-by-Reference:
call by reference" is a method of passing arguments to functions or
methods where the memory address (or reference) of the variable is
passed rather than the value itself. This means that changes made to
the formal parameter within the function affect the actual parameter in
the calling environment.
CallByReferenceExample.java
1. import java.util.*;
2.
3. // Callee
4. class CallByReference
5. {
6. int a,b;
7.
8. // Constructor to assign values to the class variables
9. CallByReference(int x,int y)
10. {
11. a=x;
12. b=y;
13. }
14.
15. // Method to change the values of class variables
16. void changeValue(CallByReference obj)
17. {
18. obj.a+=10;
19. obj.b+=20;
20. }
21. }
22.
23. // Caller
24. public class CallByReferenceExample
25. {
26. public static void main(String[] args)
27. {
28. // Create an instance of CallByReference and assign values using the constructor
29. CallByReference object=new CallByReference(10, 20);
30.
31. System.out.println("Value of a: "+object.a +" & b: " +object.b);
32.
33. // Call the changeValue method and pass the object as an argument
34. object.changeValue(object);
35.
36. // Display the values after calling the method
37. System.out.println("Value of a:"+object.a+ " & b: "+object.b);
38. }
39. }
Output:
Value of a: 10 & b: 20
Value of a: 20 & b: 40
Complexity Analysis:
className.methodName();
static variable
If you declare any variable as static, it is known as a static
variable.
The static variable can be used to refer to the common
property of all objects (which is not unique for each object),
for example, the company name of employees, college name
of
students, etc.
The static variable gets memory only once in the class area
at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves
memory).
static method
If you apply static keyword with any method, it is known as
static method.
A static method belongs to the class rather than the
object of a class.
A static method can be invoked without the need for
creating an instance of a class.
A static method can access static data member and can
change the value of it.
class Student
{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change()
{
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
}
//Test class to create and display the values of object
public class TestStaticMethod
{
public static void main(String args[])
{
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
static block
Is used to initialize the static data member.
It is executed before the main method at the time of
classloading.
class A2
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
Access Controls
Modifiers
By now, you are quite familiar with the public keyword that
appears in almost all of our examples:
Access modifiers
Public The code is accessible for all classes
Private The code is only accessible within the declared
class
Default The code is only accessible in the same package.
This is used when you don't specify a modifier.
Protected The code is accessible in the same package
and subclasses.
Recursion in Java
Recursion in Java (or any programming language) is a technique
where a method calls itself in order to solve a problem. A
recursive method typically has two main parts:
n! = n * (n - 1)!
Base case: 0! = 1 and 1! = 1
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage c
ollection
3) By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This
method is defined in Object class as:
gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
Java String
In Java, the String class is a widely used class that represents a
sequence of characters. It is part of the java.lang package and
provides a variety of methods to manipulate and work with strings
effectively.
Key Features of Strings in Java
CharSequence Interface
1.String Literal
String str = "Hello, World!";
Here are some of the most commonly used methods of the String class:
Method Description
length() Returns the length of the string.
charAt(index) Returns the character at the specified index.
substring(start, end) Extracts a substring from the string.
equals(str) Compares two strings for equality.
Method Description
equalsIgnoreCase(str) Compares two strings, ignoring case
differences.
compareTo(str) Compares two strings lexicographically.
toUpperCase() Converts all characters to uppercase.
toLowerCase() Converts all characters to lowercase.
trim() Removes leading and trailing whitespaces.
replace(oldChar, Replaces all occurrences of a character with
newChar) another character.
contains(substring) Checks if the string contains the specified
sequence of characters.
startsWith(prefix) Checks if the string starts with the specified
prefix.
endsWith(suffix) Checks if the string ends with the specified
suffix.
split(delimiter) Splits the string into an array based on the
specified delimiter.
indexOf(char) Returns the index of the first occurrence of a
character or substring.
lastIndexOf(char) Returns the index of the last occurrence of a
character or substring.
isEmpty() Checks if the string is empty.
concat(str) Concatenates the specified string to the end of
the current string.
valueOf(data) Converts other data types to strings (e.g.,
integers, floats, etc.).