Unit 1
Unit 1
Unit – 1
Introduction to Java
Introduction to Java: Basics of Java programming, Data types, Variables,
Operators, Control structures including selection, Looping, Java methods,
Overloading, Math class, Arrays in java.
What is java?
java is a high-level, general-purpose, object-oriented, and secure programming
language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is
formally known as OAK. In 1995, Sun Microsystem changed the name to Java.
The programming environment of Java consists of three components mainly
JDK
JRE
JVM
What is JDK?
JDK (Java Development Kit) is a software development kit required to develop
applications in Java. When you download JDK, JRE is also downloaded with it.
What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.
What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run
a Java program.
Features of Java
Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or
reimplemented in Java. For example, pointer and operator overloading are not used in
Java.
Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
Robust: Java makes an effort to check error at run time and compile time. It uses a
strong memory management system called garbage collector. Exception handling and
garbage collection features make it strong.
Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines
the access of Java classes.
Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.
COMMENTS IN JAVA
In Java there are three types of comments:
Single-line comments.
//Comments here( Text in this line only is considered as comment )
DATA TYPES
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
1)Local Variable
A variable that is declared and used inside the body of methods, constructors, or
blocks is called local variable in java. It is called so because local variables are not
available for use from outside.
public void mySchool()
{
// Declaration of local variables.
String schoolName; // Compilation error due to not initializing of value.
System.out.println("Name of School: " +schoolName);
}
2) Instance Variable
A variable that is declared inside the class but outside the body of the methods,
constructors, or any blocks is called instance variable in java.
2.Unary Operators
Unary operators need only one operand. They are used to increment, decrement or
negate a value.
4.Relational Operators
These operators are used to check for relations like equality, greater than, less than.
7.Ternary Operator
A ternary operator evaluates the test condition and executes a block of code based on
the result of the condition. Syntax condition ? expression1 : expression2;
Here, condition is evaluated and
if condition is true, expression1 is executed.
And, if condition is false, expression2 is executed.
if-else statement: An if-else statement, there are two blocks one is if block and
another is else block. If a certain condition is true, then if block executes otherwise
else block executes.
public class IfElseStatementExample
{
public static void main(String arg[]) { int a = 10; int b = 50;
// Evaluating the expression that will return true or false
if (a > b)
{
System.out.println("a is greater than b");
} else
{
System.out.println("b is greater than a");
}
}
}
Switch statement: The switch statement is like the if-else-if ladder statement. To
reduce the code complexity of the if-else-if ladder switch statement
comes. In a switch, the statement executes one statement from multiple
statements based on condition. In the switch statements, we have a number of choices
and we can perform a different task for each choice.
{
public static void main(String arg[]) {
int a = 10;
// Evaluating the expression that will return true or false
switch(a)
{ case 1:
System.out.println("Value of a: 1"); break; case 5:
System.out.println("Value of a: 5"); break; case 10:
System.out.println("Value of a: 10"); break; default:
System.out.println("else block"); break;
}
}
}
Do..while
The do-while loop is similar to the while loop, the only difference being that the
condition in the do-while loop is evaluated after the execution of the loop body. This
guarantees that the loop is executed at least once
Syntax
do{
//code to be executed
}while(condition); Example
public class Main
{
public static void main(String args[])
{
int i = 20; do
{
System.out.println(i); i = i+1;
} while (i <= 20);
}
Method in Java
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code,
Method Declaration
The method declaration provides information about method attributes, such as
visibility, return-type, name, and arguments. It has six components that are known as
method header,
Naming a Method
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
Types of Method
There are two types of methods in Java:
1.Predefined Method
In Java, predefined methods are the method that is already defined in the Java class
libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in
the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
2.User-defined Method The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.
public static void findEvenOdd(int num)
{
//method body if(num%2==0)
System.out.println(num+" is even"); else
System.out.println(num+" is odd");
}
Method Overloading in Java
Method Overloading is a feature that allows two or more methods may have the same
name but different in parameters, These methods are called overloaded methods and
this feature is called method overloading.
The method written by the user or programmer is known as a user-defined method.
These methods are modified according to the requirement.
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded. These methods have the same name but accept
different arguments.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array OR
int[] intArray = new int[20]; // combining both statements in one
Array of objects
Java programming language is all about classes and objects as it is an object-oriented
programming .The array of objects, as defined by its name, stores an array of objects
Object - Any entity that has state and behavior is known as an object.
For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
SYNTAX OF OBJECT
CLASS_NAME OBJ_NAME=NEW CLASSNAME();
Class
A class is a template or blueprint that is used to create objects.
Class representation of objects and the sets of operations that can be
applied to such objects.
A class consists of Data members and methods.
SYNTAX
public class class_name
{
Data Members;
Methods;
}
Example:
public class Car
{
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.
It is a special type of method which is used to initialize the object.
static keyword:
Static is a keyword that acts as a non-access modifier in Java that is used mainly to
manage memory.
A Static method cannot access an instance variable.
If a Class contains any static blocks, then that block will be executed only when the
Class is loaded in JVM.
Programmers can apply the Java keyword static with different programming objects
like:
1.variables
2. methods
3. initialization - block
4. nested class
} }
Output:
Maximum number of x and y is: 28.0
Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
Example:
class Emp {
int e_id;
String name;
Emp(int e_id, String name) {
this.e_id = e_id;
this.name = name;
}
void show() {
System.out.println(e_id + " " + name);
}
public static void main(String args[]) {
Emp e1 = new Emp(1006, "Karlos");
Emp e2 = new Emp(1008, "Ray");
e1.show();
e2.show();
}
}
Example:
String s1="Welcome";
String s2="Welcome";
By new keyword
String s=new String("Welcome");//creates two objects and one reference variable In
such 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.
Example
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
Private:
❖ The access level of a private modifier is only within the class.
❖ It cannot be accessed from outside the class.
Example
class A{
private int data=40;
private void msg()
{
Default:
❖ The access level of a default modifier is only within the package.
❖ It cannot be accessed from outside the package.
❖ If you do not specify any access level, it will be the default.
❖ If you don't use any modifier, it is treated as default by default.
Example
Class A{
public void msg(){
System.out.println("Hello");
}
Protected:
❖ The access level of a protected modifier is within the package and outside the
package through child class.
❖ If you do not make the child class, it cannot be accessed from outside the
package.
Example
class A{
protected void msg()
{
System.out.println("Hello");
}
}
❖ Java File Handling The File class from the java.io package, allows us to work with
files.
❖ To use the File class, create an object of the class, and specify the filename or
directory name.
Example
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename If you don't know
what a package is, read our Java Packages Tutorial.