Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java (1)

Java is an object-oriented programming language developed by James Gosling in 1995, known for its platform independence and key features such as simplicity, robustness, and multithreading. The document covers various aspects of Java including data types, operators, arrays, classes, objects, constructors, access modifiers, method overloading, overriding, inheritance, interfaces, and multithreading. It provides examples and explanations of each concept, highlighting their importance and usage in Java programming.

Uploaded by

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

Java (1)

Java is an object-oriented programming language developed by James Gosling in 1995, known for its platform independence and key features such as simplicity, robustness, and multithreading. The document covers various aspects of Java including data types, operators, arrays, classes, objects, constructors, access modifiers, method overloading, overriding, inheritance, interfaces, and multithreading. It provides examples and explanations of each concept, highlighting their importance and usage in Java programming.

Uploaded by

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

Java is a object-oriented programming language Java was developed by James

Gosling in May 1995 and later acquired by Oracle Corporation and is widely used
for developing applications for desktop, web, and mobile devices.
Key Features of Java
1. Platform Independent 2. 2. Object-Oriented Programming
3. Simplicity 4. Robustness 5. Security 6. Distributed
7. Multithreading 8. Portability 9. High Performance

Data types in Java are of different sizes and values that can be stored in the
variable.
Primitive Data Type: such as boolean, char, int, short, byte, long, float, and
double.
Non-Primitive (Reference) Data Types
1. Strings 2. Class 3.Object 4.Interface 5. Array

Literal: Any constant value which can be assigned to the variable is called
literal/constant.

Java Operators
Java operators are special symbols that perform operations on variables or
values. They can be classified into several categories based on their
functionality. These operators play a crucial role in performing arithmetic,
logical, relational, and bitwise operations etc.

Arrays in Java
Arrays are fundamental structures in Java that allow us to store multiple values
of the same type in a single variable. They are useful for storing and managing
collections of data.
For primitive arrays, elements are stored in a contiguous memory location.
For non-primitive arrays, references are stored at contiguous locations, but the
actual objects may be at different locations in memory.

1. Single-Dimensional Arrays:- These are the most common type of arrays,


where elements are stored in a linear order.
int[] singleDimArray = {1, 2, 3, 4, 5};
2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
Vector Class in Java
The Vector class implements a growable array of objects. Vectors fall in legacy
classes, but now it is fully compatible with collections. It is found in java.util
package and implement the List interface.

 Thread-Safe: All methods are synchronized, making it suitable for multi-


threaded environments. However, this can lead to performance overhead in
single-threaded scenarios.
 Allows Nulls: Can store null elements.
 Enumeration Support: Provides backward compatibility with Enumeration,
a legacy way of iterating over elements.

Java Classes
A class in Java is a set of objects which shares common characteristics and
common properties. It is a user-defined blueprint or prototype from which
objects are created. For example, Student is a class while a particular student
named Ravi is an object.
Properties of Java Classes
 Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
 Class does not occupy memory.
 Class is a group of variables of different data types and a group of
methods.

Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class. A typical Java
program creates many objects, which as you know, interact by invoking
methods. An object consists of:

 State: It is represented by attributes of an object. It also reflects


the properties of an object.
 Behavior: It is represented by the methods of an object. It also
reflects the response of an object with other objects.
 Identity: It gives a unique name to an object and enables one
object to interact with other objects.
Java Constructors
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is
created. It can be used to set initial values for object attributes.
import java.io.*;
class solution {
solution ()
{
super();
System.out.println("Constructor Called");
}
public static void main(String[] args)
{
solution soln = new solution ();
}
}
Types of Constructors in Java
 Default Constructor:- A constructor that has no parameters is known as
default constructor. A default constructor is invisible.
import java.io.*;
class solution {
solution () {
System.out.println("Default constructor");
}
public static void main(String[] args)
{
solution hello = new solution ();
}
}
 Parameterized Constructor:- A constructor that has parameters is
known as parameterized constructor. If we want to initialize fields of the
class with our own values, then use a parameterized constructor.
// Java Program for Parameterized Constructor
import java.io.*;
class Geek {
String name;
int id;
Geek(String name, int id) {
this.name = name;
this.id = id;
}
}

class GFG
{
public static void main(String[] args)
{
Geek geek1 = new Geek("Avinash", 68);
System.out.println("GeekName :" + geek1.name + " and GeekId :" +
geek1.id);
}
}

In Java, Access modifiers helps to restrict the scope of a


class, constructor, variable, method, or data member. It
provides security, accessibility, etc. to the user depending upon the
access modifier used with the element.
1. Public
 Visibility: Accessible from any other class.
 Usage: When you want your class, method, or variable to be
accessible from anywhere in your application.
public class MyClass {
public int myVariable;
public void myMethod() {
//code
}
}
2. Private
 Visibility: Accessible only within the class it is declared.
 Usage: When you want to restrict access to the class members
and encapsulate the data.

public class MyClass {


private int myVariable;
private void myMethod() {
// code
}
}
3. Protected
 Visibility: Accessible within the same package and subclasses
(even if they are in different packages).
 Usage: When you want to allow access to subclasses and classes
in the same package.
public class MyClass {
protected int myVariable;
protected void myMethod() {
// code
}
}
4. Default (Package-Private)
 Visibility: Accessible only within the same package. No keyword is
used.
 Usage: When you want to restrict access to classes within the
same package.
class MyClass {
int myVariable;
void myMethod() {
// code
}
}

METHOD OVERLOADING
Method Overloading allows different methods to have the same
name, but different signatures where the signature can differ by the
number of input parameters or type of input parameters, or a mixture
of both.
Method overloading in Java is also known as Compile-time
Polymorphism, Static Polymorphism, or Early binding. In Method
overloading compared to the parent argument, the child argument
will get the highest priority.
E.g.
public class Sum {
public int sum(int x, int y) { return (x + y); }
public int sum(int x, int y, int z)
{
return (x + y + z);

}
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Overriding in Java
Overriding in Java occurs when a subclass implements a method
which is already defined in the superclass or Base Class. The
method in the subclass must have the same signature as in the
superclass. It allows the subclass to modify the inherited methods.
E.g.
class Animal {
void move() {
System.out.println( "Animal is moving.");
}
void eat() {
System.out.println( "Animal is eating.");
}
}
class Dog extends Animal {
@Override void move() {
System.out.println("Dog is running.");
}
void bark() { System.out.println("Dog is barking."); }
}
public class Geeks {
public static void main(String[] args)
{
Dog d = new Dog();
d.move();
d.eat();
d.bark();}
}
Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method
that is already provided by its superclass.
2. Method overriding is used for runtime polymorphism.
3. Method overriding allows subclasses to reuse and build upon the functionality
provided by their superclass, reducing redundancy and promoting modular code
design.
4. Subclasses can override methods to tailor them to their specific needs or to
implement specialized behavior that is unique to the subclass.
5. Method overriding enables dynamic method dispatch, where the actual
method implementation to be executed is determined at runtime based on the
type of object, supporting flexibility and polymorphic behavior.

What is Abstract Class in Java?


Java abstract class is a class that can not be instantiated by itself, it needs to be
subclassed by another class to use its properties. An abstract class is declared
using the “abstract” keyword in its class definition.
E.g.
abstract class Sunstar {
abstract void printInfo();
}
class Employee extends Sunstar {
void printInfo(){
String name = "avinash";
int age = 21;
float salary = 222.2F;
System.out.println(name);
System.out.println(age);
System.out.println(salary);}
}
class Base {
public static void main(String args[]){
Sunstar s = new Employee();
s.printInfo(); }
}
Inheritance in Java
Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields
and methods) of another class. In Java, Inheritance means creating new classes
based on existing ones.

Why Do We Need Java Inheritance?


 Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide
all details, is achieved through inheritance. Abstraction only shows the
functionality to the user.
Java Inheritance Types
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits
the properties and behavior of a single-parent class.
import java.util.*;
class One {
public void print_value()
{
System.out.println("Value 1");
}
}
class Two extends One {
public void print_for() {
System.out.println("for");
}
}
public class Main {
public static void main(String[] args)
{
Two g = new Two();
g.print_value();
g.print_for();
g.print_value();
}
}

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as
well as the derived class also acts as the base class for other classes.
E.g.
class One {
public void printOne() {
System.out.println("printOne() method of One class.");
}
}
class Two extends One {
public void printTwo() {
System.out.println("printTwo() method of Two class.");
}
}
public class Main extends Two {
public static void main(String args[]) {

obj.printOne(); obj.printTwo();
}
}

3. Java Hierarchical Inheritance


The inheritance in which only one base class and multiple derived classes is
known as hierarchical inheritance.
E.g.
class One {
public void printOne() {
System.out.println("printOne() Method of Class One");
}
}
class Two extends One {
public void printTwo() {
System.out.println("Two() Method of Class Two");
}
}
class Three extends One {
public void printThree() {
System.out.println("printThree() Method of Class Three");
}
public class Main {
public static void main(String args[]) {
Two obj1 = new Two();
Three obj2 = new Three();
obj1.printOne();
obj2.printOne();
}
}

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Note :- Java does not support multiple
inheritances with classes. In Java, we can achieve multiple inheritances only
through Interfaces.
E.g.
import java.util.*;
1. interface Character {
2. void attack();
3. }
4. interface Weapon {
5. void use();
6. }
7. class Warrior implements Character, Weapon {
8. public void attack() {
9. System.out.println("Warrior attacks with a sword.");
10. }
11. public void use() {
12. System.out.println("Warrior uses a sword.");
13. }
14. }
15. class Mage implements Character, Weapon {
16. public void attack() {
17. System.out.println("Mage attacks with a wand.");
18. }
19. public void use() {
20. System.out.println("Mage uses a wand.");
21. }
22. }
23. public class MultipleInheritance {
24. public static void main(String[] args) {
25. Warrior warrior = new Warrior();
26. Mage mage = new Mage();
27. warrior.attack();
28. warrior.use();
29. mage.attack();
30. mage.use(); }
31. }
Java Interface
An Interface in Java programming language is defined as an abstract type used to
specify the behavior of a class. An interface in Java is a blueprint of a behavior. A
Java interface contains static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction.
 By default, variables in an interface are public, static, and final.
 It is used to achieve abstraction and multiple inheritances in Java.
E.g.
import java.io.*;
interface testInterface {
final int a = 10;
void display();
}
class TestClass implements testInterface {
public void display(){
System.out.println("Geek");
}
}
class Geeks
{
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}
Note: In Java, the abstract keyword applies only to classes and methods,
indicating that they cannot be instantiated directly and must be implemented.

Class Interface

In an interface, you must initialize


In class, you can instantiate
variables as they are final but you
variables and create an object.
can’t create an object.

The interface cannot contain


A class can contain concrete (with
concrete (with implementation)
implementation) methods
methods.

The access specifiers used with In Interface only one specifier is


classes are private, protected ,public used- Public.
Java Threads
Multithreading : Multithreading is a technique that allows a program or a
process to execute many tasks concurrently (at the same time and parallel). It
allows a process to run its tasks in parallel mode on a single processor system.
In the multithreading concept, several multiple lightweight processes are run in a
single process/task or program by a single processor. In Java, the Java Virtual
Machine (JVM) allows an application to have multiple threads of execution
running concurrently. It allows a program to be more responsible to the user.

Threads are lightweight subprocesses, representing the smallest unit of


execution with separate paths. The main advantage of multiple threads is
efficiency (allowing multiple things at the same time). For example, in MS Word,
one thread automatically formats the document while another thread is taking
user input.

let us know in detail each and every state:


1. New State: By default, a Thread will be in a new state, in this state,
code has not yet been run and the execution process is not yet initiated.
2. Active State: A Thread that is a new state by default gets transferred to Active
state when it invokes the start() method, his Active state contains two sub-
states : 1. Runnable State 2. Running State
3. Waiting/Blocked State: If a Thread is inactive but on a temporary time,
then either it is a waiting or blocked state, for example, if there are two threads,
T1 and T2 where T1 needs to communicate to the camera and the other thread
T2 already using a camera to scan then T1 waits until T2 Thread completes its
work, at this state T1 is parked in waiting for the state.

4. Timed Waiting State: Sometimes the longer duration of waiting for threads
causes starvation, if we take an example like there are two threads T1, T2 waiting
for CPU and T1 is undergoing a Critical Coding operation and if it does not exist
the CPU until its operation gets executed then T2 will be exposed to longer
waiting with undetermined certainty, In order to avoid this starvation situation, we
had Timed Waiting for the state to avoid that kind of scenario as in Timed
Waiting, each thread has a time period for which sleep() method is invoked and
after the time expires the Threads starts executing its task.

5. Terminated State: A thread will be in Terminated State, due to the


below reasons:
 Termination is achieved by a Thread when it finishes its task Normally.
 Sometimes Threads may be terminated due to unusual events like
segmentation faults, exceptions…etc. and such kind of Termination can
be called Abnormal Termination.
 A terminated Thread means it is dead and no longer available.

Java Packages
Packages in Java are a mechanism that encapsulates a group of classes, sub-
packages, and interfaces.
Packages are used for:
 Prevent naming conflicts by allowing classes with the same name to exist
in different packages,
like college.staff.cse.Employee and college.staff.ee.Employee.
 They make it easier to organize, locate, and use classes, interfaces, and
other components.
 Packages also provide controlled access for Protected members that are
accessible within the same package and by subclasses.
Types of Java Packages
 Built-in Packages
 User-defined Packages
1. Built-in Packages
These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:
 java.lang: Contains language support classes
 java.io: Contains classes for supporting input / output operations.
 java.util: Contains utility classes which implement data structures like
Linked List, Dictionary and support ; for Date / Time operations.
 java.applet: Contains classes for creating Applets.
 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.

2. User-defined Packages
These are the packages that are defined by the user.
1. Create the Package:
2. Use the Class in Program:

Some advantages of the package in java are as follow:


1. Name Collision :- Packaging helps to avoid class name collision. When there is
the use of the same class name, it needs to be present in different directories.
2. Provide Control Access :- The access specifiers have ingress control on
package level and protected. A member declared in the program as protected is
approachable by classes inside the same packages and the subclasses.
3. Reuse of Code :- The most useful advantage of packages is reusability. When
there is development in software, and due to a lack of communication between
programmers, a programmer writes the same codes twice. Saves the instruction
in some other package. Whenever there is a need for that particular instruction,
the developer will easily access it.
4. Information Hiding :- With the help of packages, the class information will
conceal. By specifying the data member as public, protected, and private with the
use of the modifier.
5. Organization of Project :- Packages play a significant role in organizing the
structure of data. That contains several enumerations, interfaces, and classes. A
project has various components, so it would be efficient if one package has the
same enumerations, interfaces, and classes.

You might also like