0% found this document useful (0 votes)
4 views

AJAVA Unit 1

Java is a widely-used programming language created by Sun Microsystems, now owned by Oracle. It features platform independence, strong support for Object-Oriented Programming, and a robust memory management system. The document also covers Java's data types, control statements, classes, objects, arrays, and string operations.

Uploaded by

solankiaryamann2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

AJAVA Unit 1

Java is a widely-used programming language created by Sun Microsystems, now owned by Oracle. It features platform independence, strong support for Object-Oriented Programming, and a robust memory management system. The document also covers Java's data types, control statements, classes, objects, arrays, and string operations.

Uploaded by

solankiaryamann2
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit I

A Brief History of the Java


Java is one of the most popular programming languages worldwide. It was created by James Gosling and Patrick
Naughton, employees of Sun Microsystems, with support from Bill Joy, co-founder of Sun Microsystems.
Sun officially presented the Java language at SunWorld on May 23, 1995. Then, in 2009, the Oracle company
bought the Sun company, which explains why the language now belongs to Oracle.

What Is Java?

Java is described as being a multi-purpose, strongly typed, and Object-Oriented Programming (OOP) language

Features

Compiled(c ,C++) and Interpreted(php and pyton)

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.

Platform Independent and Portable

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.

Simple and Familiar

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.

Multi-Threaded and Interactive

Also known as Thread-based Multitasking, multithreading is a feature that allows executing


multiple threads simultaneously.
In short, we can write Java programs that deal with many tasks at once by defining multiple threads. The advantage
of multithreading is that it doesn’t occupy memory for each thread – all threads share a common memory area.

Usefulness of Java Runtime Environment

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 in Java

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.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

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

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII value

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.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

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

Syntax of if statement is given below.

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

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}
Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

while loop
while(condition){
//looping statements
}
do-while loop
do
{
//statements
} while (condition);

Jump Statements: break statement and continue statement


break statement

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.

public class BreakExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 10; i++) {

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.

public class ContinueExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

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.

Create a class in Java

We can create a class in Java using the class keyword. For example,

class ClassName {

// fields

// methods

class Bicycle {

// state or field

private int gear = 5;

// behavior or method

public void braking() {

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.

Creating an Object in Java

Here is how we can create an object of a class.

className object = new className();

// for Bicycle class

Biycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();


Java Arrays
An array is a collection of similar types of data.

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,

double[] data = new double[10];


How to Initialize Arrays in Java?
In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array


int[] age = {12, 4, 5, 2, 5};
How to Access Elements of an Array in Java?
Access Array Elements
class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Output
Accessing Elements of Array:
First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5
Multidimensional Arrays
Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional
arrays in Java.

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

public class TwoDArray {


public static void main(String[] args) {
int rows = 4;
int columns = 4;

int[][] array = new int[rows][columns];

int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
array[i][j] = value;
value++;
}
}

System.out.println("The 2D array is: ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}

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,

String example = "Java";


Here, we are directly providing the value of the string (Java). Hence, the compiler first checks the string pool to see
if the string already exists.

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,

String example = new String("Java");


Here, the value of the string is not directly provided. Hence, a new "Java" string is created even though "Java" is
already present inside the memory pool.
Java String Operations
class Mainclass {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
System.out.println("String: " + greet);

// get the length of greet


int length = greet.length();
System.out.println("Length: " + length);
}
} Output

String: Hello! World


Length: 12
Join Two Java Strings
class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
System.out.println("First String: " + first);

// create second
String second = "Programming";
System.out.println("Second String: " + second);

// join two strings


String joinedString = first.concat(second);
System.out.println("Joined String: " + joinedString);
}
}
Output

First String: Java


Second String: Programming
Joined String: Java Programming

Compare Two Strings


class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = first.equals(second);
System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = first.equals(third);
System.out.println("Strings first and third are equal: " + result2);
}
}
Output

Strings first and second are equal: true


Strings first and third are equal: false

Java String Class Methods


The java.lang.String class provides a lot of built-in methods that are used to manipulate string in Java. By the help of
these methods, we can perform operations on String objects such as trimming, concatenating, converting,
comparing, replacing strings etc.
toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this String into uppercase letter and String toLowerCase() method
into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
trim() method
The String class trim() method eliminates white spaces before and after the String.
String s=" Sachin ";
System.out.println(s);// Sachin
charAt() Method
String s="Sachin";
System.out.println(s.charAt(0));//S
length() Method
The String class length() method returns length of the specified String.
String s="Sachin";
System.out.println(s.length());//6
replace() Method
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"
System.out.println(replaceString);
Output:

Kava is a programming language. Kava is a platform. Kava is an Island.


charAt() Method
The String class charAt() method returns a character at specified index.
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h
Function
Functions in Java are blocks of code that perform a specific task, and they are used to organize code and make it
more modular and reusable. In this article, we will explore the basics of Java functions, including how to define
them, how to pass parameters, and how to return values.
public void sayHello() {
System.out.println("Hello, world!");
}

Passing Parameters to a Function


public int add(int a, int b) {
return a + b;
}
Returning Values from a Java Function
public int doubleValue(int a) {
return a * 2;
}

FunctionExample.java

import java.util.Scanner;
public class FunctionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int num1 = scanner.nextInt();
System.out.print("Enter another number: ");
int num2 = scanner.nextInt();
int sum = add(num1, num2);
System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum + ".");
public static int add(int a, int b) {
return a + b;
}
}

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).

The extends keyword is used to perform inheritance in Java. For example,


class Animal {
// methods and fields
}
// use of extends keyword
// to perform inheritance
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}
Example:
class One {
public void print_one()
{
System.out.println("From one");
}
}

class Two extends One {


public void print_tow()
{
System.out.println("From two");
}
}
public class MainClass {
public static void main(String[] args)
{
Two objt = new Two();
objt.print_one();
objt.print_tow() ;
}
}

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 Access Modifiers

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 implements interface


class Car implements Color {

// implementation of abstract method


public void getColor(String name) {
System.out.println("Color is: " + name);
}
}

class MainClass {
public static void main(String[] args) {
Car objcar = new Car();
objcar. getColor ("Black");
}
}

static Keyword in Java


The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or
method of a given class.The static keyword is used for a constant variable or a method that is the same for every instance of a class.

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");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}
Java Static Class
We can declare a class static by using the static keyword. A class can be declared static only if it is
a nested class.
public class JavaStaticClassExample
{
private static String s= "JECRC";
//Static and nested class
static class StaticNestedClass
{
//non-static method of the nested class
public void show()
{
//prints the string defined in base class
System.out.println(s);
}
}
public static void main(String args[])
{
JavaStaticClassExample.StaticNestedClass obj = new JavaStaticClassExample.StaticNestedClass();
//invoking the method of the nested class
obj.show();
}
}
Output:

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");
}
}

class A extends FinalMethod{


void show()
{
System.out.println("Welcome Again");

public static void main(String args[]){


A objA= new A();
objA.show();
}
}
Output

Is final method inherited?

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 Chiled extends FinalClass


{
void run()
{
System.out.println("Chiled Class");
}

public static void main(String args[]){


Chiled objC= new Chiled();
objC.run();
}
}

Java super keyword


The super keyword in Java is used in subclasses to access superclass members (attributes, constructors
and methods).
Uses of super keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable


We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same
fields.
Example:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class SuperVariable{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
Example:

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:

111 ankit 5000.0


112 sumit 6000.0

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

You might also like