AJAVA Unit 1
AJAVA Unit 1
What Is Java?
Java is described as being a multi-purpose, strongly typed, and Object-Oriented Programming (OOP) language
Features
Java combines the power of compiled languages with the flexibility of interpreted languages.
The compiler (javac) compiles the source code into bytecode, then the Virtual Machine (JVM) executes this
bytecode by transforming it into machine-readable code.
The two-step compilation process is what lies behind Java’s most significant feature: platform independence, which
allows for portability.
Being platform-independent means a program compiled on one machine can be executed on any other machine,
regardless of the OS, as long as there is a JVM installed.
The portability feature refers to the ability to run a program on different machines. In fact, the same code will run
identically on different platforms, regardless of hardware compatibility or operating systems, with no changes
such as recompilation or tweaks to the source code.
Object-Oriented
Java strongly supports Object-Oriented Programming concepts such as encapsulation, abstraction, and inheritance.
All the instructions and data in a Java program have to be added inside a class or object.
Robust and Secure
Java includes several useful features that help us write robust and secure applications.
One of the most important ones is the memory management system, along with automatic garbage collection.
Compared to languages like C/C++, Java avoids the concept of explicit pointers, and doesn’t require programmers to
manually manage the allocated memory.
Instead, the GC will take care of deleting unused objects to free up memory.
In addition, Java is a strongly-typed language, which is a feature that can help lower the number of bugs in an
application, and provides error handling mechanisms.
Distributed
This feature is helpful when we develop large projects. We can split a program into many parts and store these parts
on different computers. As a result, we can easily create distributed and scalable applications that run on
multiple nodes.
First, Java is simple thanks to its coding style, which is very clean and easy to understand. Also, it doesn’t use
complex and difficult features of other languages, such as the concept of explicit pointers.
Finally, Java is familiar since it’s based on existing languages like C++ and incorporates many features from these
languages.
To be able to run a software application, it must have an environment that allows it to function – typically, an
operating system such as Linux, Unix, Microsoft Windows, or macOS. In the absence of other supporting
environments, programs are limited by the capabilities of the operating system and its resources.
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types
in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional methods.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Java Control Statements
Java compiler executes the code from top to bottom. The statements in the code are executed according to the order
in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth
flow of program.
Decision-Making statements:
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the
specific condition.
Simple if statement
if(condition) {
statement 1; //executes when condition is true
}
if-else statement
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
if-else-if ladder:
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Nested if-statement
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code
called cases and a single case is executed based on the variable which is being switched. The switch statement is
easier to use instead of if-else-if statements. It also enhances the readability of the program.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
2
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true.
However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
1. for loop
2. while loop
3. do-while loop
for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
for-each loop
for(data_type var : array_name/collection_name){
//statements
}
Calculation.java
Java
C
C++
Python
JavaScript
while loop
while(condition){
//looping statements
}
do-while loop
do
{
//statements
} while (condition);
As the name suggests, the break statement is used to break the current flow of the program and transfer the control
to the next statement outside a loop or switch statement. However, it breaks only the inner loop in the case of the
nested loop.
System.out.println(i);
if(i==6) {
break;
Output:
6
continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific part of the loop
and jumps to the next iteration of the loop immediately.
if(j == 4) {
continue;
System.out.println(j);
Output:
3
5
Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
class Bicycle {
// state or field
// behavior or method
System.out.println("Working of Braking");
} }
Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class then MountainBicycle,
SportsBicycle, TouringBicycle, etc can be considered as objects of the class.
For example, if we want to store the names of 100 people then we can create an array of the string type that can store
100 names.
Syntax
dataType[] arrayName;
String[] array = new String[100];
// declare an array
double[] data;
// allocate memory
data = new double[10];
Here, the array can store 10 elements. We can also say that the size or length of the array is 10.
In Java, we can declare and allocate the memory of an array in one single statement. For example,
// create an array
int[] age = {12, 4, 5, 2, 5};
A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself.
For example,
class Testarray3{
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
int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = value;
value++;
}
}
Java String
In Java, string is basically an object that represents sequence of char values. An array of characters works same as
Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";
Create String Using Literals vs. New Keyword
Now that we know how strings are created using string literals and the new keyword, let's see what is the major
difference between them.
In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing
the strings.
1. While creating strings using string literals,
If the string already exists, the new string is not created. Instead, the new reference, example points to the already
existing string (Java).
If the string doesn't exist, a new string (Java) is created.
2. While creating strings using the new keyword,
// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);
// create second
String second = "Programming";
System.out.println("Second String: " + second);
// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";
FunctionExample.java
import java.util.Scanner;
public class FunctionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Output:
Enter a number: 5
Enter another number: 7
The sum of 5 and 7 is 12.
Inheritance
Inheritance is one of the key features of OOP that allows us to create a new class from an existing class.
The new class that is created is known as subclass (child or derived class) and the existing class from where the child class is derived
is known as superclass (parent or base class).
Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example
2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same subclass acts as a superclass for another class. For
example,
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,
4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple superclasses. For example,
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,
Java Interface
An interface is a fully abstract class. It includes a group of abstract methods (methods without a body).
/ create an interface
interface Color {
void getColor(String name);
}
class MainClass {
public static void main(String[] args) {
Car objcar = new Car();
objcar. getColor ("Black");
}
}
Characteristics of static keyword: Shared memory allocation, Accessible without object instantiation, Associated with class, not
objects.
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
JECRC
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:variable,method,class
final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example:
class FinalVar{
final string university="JECRC";//final variable
void run(){
university="Amity";
}
public static void main(String args[]){
FinalVar obj=new FinalVar();
obj.run();
}
}
Output
final method
If you make any method as final, you cannot override it.
Example:
class FinalMethod{
final void show()
{
System.out.println("Welcome");
}
}
Ans) Yes, final method is inherited but you cannot override it.
final class
If you make any class as final, you cannot extend it.
Example:
final class FinalClass{
void Show()
{System.out.println("Final class demo");
}
}
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class SuperMethod{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
output:
eating...
barking...
super is used to invoke parent class constructor
The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
Example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class SuperClass{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
Note: call to super must be first statement in constructor.
this keyword in Java
In Java, this is a reference variable that refers to the current object. The this keyword can be used to refer current class instance
variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Example1:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class This{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
Example2:
class Student{
int rollno;
String name;
float fee;
void Set(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class This1{
public static void main(String args[]){
Student s1=new Student();
s1.Set(111,"ankit",5000f);
s1.display();
}}
Output
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form,
built-in package and user-defined package.
Built-in Packages
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This
package is automatically imported.
2) java.io: Contains classed for supporting input / output operations
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date /
Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
user-defined package
Create a package with class
package mypkg;
public class Pkgdemo{
public void msg()
{
System.out.println("From package mypkg ");}
}
Compile package as:
javac -d . Pkgdemo.java
Write code to Use created package
import mypkg.Pkgdemo;
class Pkguse{
public static void main(String []args)
{
System.out.println("Current program");
Pkgdemo objP=new Pkgdemo();
objP.msg();
}
}
Compile and run new program
javac Pkguse.java
java Pkguse
output:
Current program
From package mypkg