KEMBAR78
Java Unit-1 One Shot Marathon Notes | PDF
0% found this document useful (0 votes)
366 views80 pages

Java Unit-1 One Shot Marathon Notes

dfsfsd

Uploaded by

d.devilmc05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
366 views80 pages

Java Unit-1 One Shot Marathon Notes

dfsfsd

Uploaded by

d.devilmc05
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 80
AKTU BTech (2nd Year) gS & MCA (2nd Sem) ~@ ee (oY) F AY Tt 4 oe): Sar Vet OL & ar atts] = Vikas Sir Chapter No * Javais ahigh-level] object-oriented programming language that is designed to be platform-independent. * It allows dey code that car(run on any device equipped with theYava Virtual Machine (JVM).| OR « Java is a programming language and a platform. Java is a high level, robust,| object-oriented and secure programming language. eee eee seen ae’. Java Programming by VikasSir History Of Java Programming Language:- * Java was originally designed for (nteractive television] but it was too advanced technology for the(digital cable televisionjindustry at the time. * 1)Qames Gosling,|Mike Sheridan, and Patrick Naughton initiated the Java language project ir June 1991] The small team of sun engineers called Green) Team. * 2)Firstly, it was called /Greentalk"/by James Gosling, and the file extension * 3) After that, it was(called Oak and was developed as a part of the Green project. Java Programming by VikasSir History Of Java Programming Language:- * Oaks a symbolf strengthland chosen as affational tree of many countries like the U.S.A., France, Germany, Romania, etc. + 4) in 1995, Oak was(enamed as "Java']because it was already a trademark by Gak Technolog + 5) JDK 1.0 was released on/January 23, 1996. After the first release of Java, there have been many additional features added to the language. 2.1997: Java Development Kit KK) 1.1 was released, bringing several new features, including[inner classe, JavaBeans) and JDBC (Java Database Connectivity). History Of Java Programming Language:- * 1998: The release of Java 2 (JDK 1.2) marked a significant update, with the introduction of Swing for GUI development, |the Collections framework. * 2004: Java 5{(originally called J2SE 5.0) Introduced major enhancements like nd the enhanced for loop. * 2006: Sun released Java under the GNU General Public License (GPL) making iopen-source software. * 2010:'Qracle Cor; jon acquired/Sun Microsystems, taking over the . ee. development and stewardship of Java. Java Programming by VikasSir History Of Java Programming Language: * 2018: java 10jintroduced local-variable type inference with the var keyword, and Java|11 provided long-term support (LTS)] featuring new enhancements and deprec: 24172024, Java's future lies in its(integration with cutting-edge technologiesllike machine learning, cloud computing, and the Internet of Things (IoT). _machine learning, cloud computing, For instance, Java 8 Future introduces features for asynchronous computations, simplifying the development of multithreaded applications. Java Programming by VikasSir Characteristics Java Programming Language:- Object-Oriented: * Java is based on objects. An object can represent a real-world thing like a car or aconcept{like a bank account] Each object has attributes (properties) and behaviors (methods). PI Independent: * Writ your code once,and it car{run anywhere /Java programs are compiled into bytecode, which can be executed on any device with a Java Virtual Machine (JVM). _Sipopte and Easy to Learn: * Java's syntax is straightforward and similar tolether popular programming] languages like C and Cs+-This makes it easier for new developers to pick up. Java Programming by VikasSir Characteristics Java Programming Language:- Secure: « Javahas buittfin secul rity features that help protect(against malicious code. For example, it runs inside a virtual machi virtual machine, w which adds an extra layer ot rotection. (Robust: l * Java emphasizes reliability. It has strong memory management, Jerror hai @ chances of crashes and bugs. _yibetreated: © Java can perforn} many tasks at the same time|(multithreading). This is useful for creating apptications that need to perform multiple operations simultaneously, like games or web servers. Java Programming by VikasSir JVM( Java virtual machine ):- * AJVM: JVM is an abstract machine. It is a software-based, virtual computer that provides runtime environment in which java bytecode can be executed. Java Programming by VikasSir VM contains the Component: * 1.Classloader: Classloader is aGubsystem of JVM|which is used to load class files. Whenever we run the java program, it is loaded first by(the classloader. 22 Class area: Class area stores, ber-class structures such ds the runtime constant pool, field and method data. * 3.Heap: It is the runtime data area in which(objects are allocated. | « &Stack: Java stack stores frames. it holds localvariables and partial results, and plays a part in method invocation and return. * 5.Program Counter (PC) register : PC register contains the address of the Java virtual machine instructior{ currently being executed. | * 6. Native method stack: It contains all the native methods used in the application. * 7. Execution engine: It contains: i_A virtual processor ao Victual processor _ _llJaterpreter: Read bytecode stream then execute the instructions. Java Programming by VikasSir JVM( Java virtual machine ):- iii. Just-In-Time(JIT) compiler: It is used to (mprove the performance] JIT compiles parts of the byteco: nctionality at the same time, and hence reduces the@mount of * 8.Java Native Interface: Java Native Interface (JNI) is {framework/which provides an interface to communicate with another application written in another language like C, C++, Assembly etc. _*-9.le of JVM: The primary role of the Java Virtual Machine (JVM) in the execution of programs is to act as an intermediary between the compiled Java bytecode and the host operating system and hardware. Java Programming by VikasSir JDK(Java Development Kit) * Java Development kit (JDK): It's a software package you install on your computer to develop Java programs. It includes: © Compiler (javac): Translates your Java code into bytecode that the computer carvund _esava Runtime Environment (JRE): Allows {you to run Java programs.) _oJii6faries: Pre-written code that you can use to build your applications. © Tools: Utilities like debuggers and documentation generators. Java Programming by VikasSir JDK(Java Development Kit) IDK (Java Development Kit) Java Programming by VikasSir Java Source File Structure:- A Java source file has aGpecific structure land follows certain conventions to ensure that the code is organized and easily understandable} able. ge Declaration: The package declaration defines the namespace for the classes in the file. It is the(first line in the source file if present./ Example:- package com.example.myapp; em Statements: Import statements allow jout Java Programming by VikasSir lass Declaration: A Java source file can€ontain multiple classes, but only @ne public class} The name of the public class must match the filename. public class MyClass { MTclass content) } ir io lass pos i neues Constructors ate special methodslthat are called when an object of the class is created. They have the same name as the class and fo return type. 7 pul MyClass(int number, String name) { this.number = number; —— this.name = name; ~~ } jain Method (Optional Entry point of the application. public static void main(String[] args) { <— Cichsy MyClass 6bp-{new/MyClass(10, "Alice"); d obj.displayO> } > Methods: * Functions that define the behavior of the cl public voidGiisplay) | = { = Ais ply C 5 pues Meta i yam : package com.example.myapp; = import java.util.List; ___. import javautiArrayList; | public clas{ MyClass > private int number; private String name; —> Public MyClass(int number, String name) { this.number= number 7 this.name = 2,04 } ) —> public void display) { uv System.out.prirtin("Number: "+ Pat er +", Name: "+ name); —>public static void main(String[] args) { yClass/6bp= new MyClass(10, "Alice"); Access modifiers: * Access modifiers in Java determine the(visibility]and accessibilityof classes, methods, and variables. * They help td control how different parts of your code can interact with each other. * There are four main access modifiers in Java: public, protected, default (no modifier), and private. Prive public: * Visibility: Everywhere. * Usage: Any class, method, or variable declared as public can be accessed from any other class, regardless of which package(t belongs to.! — public class MyClass { public int fayNumber; puiste void myMethod() { // This method can be accessed from anywher} } or i private: * Visibility: Within thel Game class on! y. * Usage: Any class, method, or variable declared as private can only be accessed(within the cl is declared. It is not visible toother classes. > public class MyClass { private int myNumber; rivate void myMethod() { // This method can only be accessed within MyClass } : claps oot f 4 ype, Java Programmingby Vikassir & protected: * Visibility: Within the same package and subclasses (even if they are in different packages). * Usage: Any class, method, or variable declared as protected can be accessed @ithin its own packagejand by Gubclasses in other packages. public class MyClass, protected int fayNumber; protected void myMethod() { // This method can be accessed within the same package and subclasses ———— } } default (no modifier); * Visibility: Within the same package. * Usage: If no the class, method, or variable is accessible only(within its own package.) class @yClassit int myNumber; “uF BN void myMethod() { // This method can be accessed within the same pac! — F Data Types:- * data types specify the different sizes and values[that can be stored ina variable. yo. - oO ae. ez, 0 * There are two main categories of data types in Javaf primitive data types and reference (6r non-primitive)/data types. a" => ol, Primitive Data Types a” * Primitive data types are the most basic data types available within the (ava language/There are eight primitive data typss= ‘JavaProgrammingby Vikassir & Reference Data Types « Reference data types are constructed from/(primitive data|types and refer to objects. These include classes, interfaces, arrays, and enums. Data Types in java, Primitive Data Types es Floating-Point ee ‘Character ae E Boolean boolean G ([- Non-primitive Data Types ee Dictionary All user-defined class ete 8 16 32 long 64 float 32 double 64 char 16 boolean 1 e(inbits) | Range Whyte -128 to 127 ea -32,768 to 32,767 -231 to 231-1 ya ol aa 1.4e-045 to 3.4e+038 4,9e-324 to 1.8e+308 < Oto 65,535 ae true or false OPERATOR IN JAVA :- In Java, operators are/symbols|that perform operations on variables and values. They are categorized based on the type ofjoperation they perfor: > Types Of Operators: SBS : ze +Q>7 * Arithmetic operators fee, BE « Arithmetic operators in Java are used to perform mathematical operations on numeric values, including integers and floating-point numbers. * Arithmetic operators follow the usual rules of mathematics Of Operator: S Common arithmetic operators used in Java: Operator Meaning + Addition > @+, ) subwaction (a -») 9. gg 3 SC) + Multiplication Gb) / Division (a /4) i12 % Modulus, remainder after division’ ( a / 4 + Increment —_ Ste2 2 (L) an Decrement * Relational operators: * Relational operators in Java are used to compare tys-alues and determine the relationship between them. Relational operators used in Java: Operator Meaning == Equal to a@==b 2=-=+>5F/O = Not equal to Foot < Less than 2 Trt > Greater than ries fF < Less than or equal to >= Greater than or equal to * Logical operators: * Logical operators in Java are used to perform|logical operations/on boolean values. * These operators allow you to combine or modify boolean values and make decisions based on the results¢ Logical operators used in Java: Operator Meaning && Logical AND I Logical OR ! Logical NOT ghee =4he 22-5) sae hl 2 = [ y * Assignment operators: ¢ “* ' aes” on BE * Assignment operators in Java are used to assign values to variables. . {tors combine the assignment of a et Le (bitwise operation) @=s ) Gees. pe Wile Operator Assignment operators used in Java: a Meaning ag. fe 4 Assignment G@ = S—_ 2 3 Add And assign Gass gS ots7 Subtract and assign Multiply and assign Divide and assign Modules and assign Bitwise AND and assign Bitwise OR and assign oll eg Java are used to perform operations on individual es (byte, short, int, [ong] * These operators treat the values as(sequences of binary Higits (bits) and manipulate them at the bit level. Operator Meaning 1OF stato e's” & Bitwise AND —— g 22te I Bitwise OR —— ‘<_ " Bitwise XO! - Bitwise NOT. oan i? << Left shine 4 ft @ > Right Shi ol sae Unsigned right shi * Conditional Operator: * The conditional operator in Java, often referred to as the ternary Java operator," is a shorthand way of writing in a single apublie(MainOt x=5; } public static void main(String[] args) 7 “eum { ae 4 System.out.printin(myObj.x); } } // Outputs 5 Types Of Constructors:- (1)Default Constructor: * This constructor does not take(any parameters| It is used to initialize objects with@efault values. ] class MyClass { // default constructor is provided by java } (2)Parameterized Constructor: * This constructor takes parameters and allows you to initialize objects with class @yClasst int value; MyClass(int iis alue = valy // initialization code } } (3)Copy Constructor: * This constructor creates a new object as a copy of an existing object. | It typically takes a reference to an object of the same class. S class MyClass { int value; // Copy constructor “is MyClass(MyClassobj) { value = obj.value; i : 7 ae lyClass objl = new MyClass(10); // Calls the parameterized constructor MyClass obj2 = new MyClass(obj1); // Calls the copy constructor [0 Jp (4)Private constructor: If a constructor is declared as private, then its objects are only accessible from within(the declared class. class private ClassName() { // initialization code 7 Inheritance:- * Inheritance in Java is a fundamental concept that allows one class (called the child or subclass) to inherit features (methods and fields) from another class (called the parent o! p * The child class inherits all thdfields And nfethods 6fthe parent class. * This means the child class can reuse the code of the parent class without _having to rewrite it —— * It promotes code(feusability!and helps in implementing the "is-a" relationship Types Of inheritance in java:- Single Inheritance:- * Single inheritance occurs when a class extends only oneSuperclass{The subclass inherits the properties and behaviors of thesuperclass. | a Single Inheritance class Animal { voideatl K System.out.println("This animal eats food."); y pes Dog jextdhds Animal { void bark() { System.out.printin(The dog barks."); H public class Singleinheritancd { myDe > public static void main(String[] args) { <= 7 og nyDog {newIDogi); 7 myDog.eat(); Trib animal Cals pe myDog.bark(); T— Tre Oey boats yn Multi-level Inheritance:- * Multilevel inheritance in Java is a feature that allows a class to inherit properties and behaviours from another class, which in turn inherits from another class, forming(a "chi f inheritance. Multi-Level Inheritance pn & © 5 System.out.printin("The horse is running";L> Deg. ag ae uenald ; anim public class Multilevel_Inheritance { public static void main(String{] args) { horse /myhorsd = newhorse(); myhorse.eat(); —> © 4 yhorse.bark(); —> myhorse.run(); > H Hierarchical inheritance: * Atype of inheritance in object-oriented programming where multiple derived classes inherit from a single base class. cae @ i B eby> obyc 2W 7" de JL ob: ot i | of al? ovy & ®@ ©) oO Tow class Animal { void eat() { System.out.printin("This animal eats food."); a class(Dogextends{Animall{ void bark() { System.out.printin("The dog barks."); n Za ? class horse extends(Animal{ Z void run() { Di Horse System.out.printin("The horse is running"); ( ° : } public class Hierarchical_Inheritance { public static void main(String[] args) { horse (nyhorsq= new horse(); myhorse.eat(); myhorse.run(); yobj = new Dog(); eee ? myobj.Gark();> n jultiple Inheritance: * Java does not support(multiple inheritancelwith classes to avoid land simplify the design, but it can be achieved through Base2 Basel << =~ NN Derived [|-—? -JavaProgrammingby Vikassir & Hybrid Inheritance: * Acombination of twd or more types of inheritancel It can be achieved using interfaces to avoidthe diamond problem. Hybrid Inheritance Interface In Java: * The interface in Java is a mechanism to achieve(abstraction! There can be only abstract methods in the Java interface, not the method body. * Itis used to achieve(abstraction/and multiple inheritances|in Java.using Interface. + Java Interface also represents the IS-A relationship. Syntax for Java Interfaces: ? interface { // declare constant fields <— // declare methods that/abstract | // by default. } Uses of Interfaces in Java: * It is used to achieve(total abstraction. * java does not support! fnuttipte inheritancesjin the case of class, by using an interface it can(achieve multi ple noastea] _t Interfaces are used toimplement abstraction. 2 od zany clas¢ can extend only 1 class, but can any class implement an infinite number of interfaces. * It is also used to achieve/loose coupling. Implement Multiple Inheritance by Using Interfaces in Java: Interface It void walk(); P interface Swimmable { void swim(); } L 2 clase(Duckimplements Walkable, Swimmable { public void walk() fi System.out.printin("Duck is walking."); } public void swim() { System.out.println("Duck is swimming."); }} class Main { [wate ] public static void main(String[] args) { uiwu \ __Duck duck = new Duck(; duck.walk(); —— Output: [Duck duck.swim(); Duck is walking. y} Duck is swimming. Abstract Classes and Methods: * Data abstraction is the process of hiding certain details and showing only essential information to the user. * Abstraction can be achieved with either abstract classes or interfaces. Abstract class: « (isarestrictedclass that cannot be/used to create objects|(to access it, it must be inherited from another class). Abstract method: * can only be used in ai and es not have a body! The * body is provided by the subclass (inherited from). Advantage Of Abstract class : . eran * Testin; 5 Abstraction * Flexibility ~ * Secure code Gbstract\class Anima ic abstract void animalSound(); } wu class Dog extends Animal { public void animalSound() { 7 System.out printin("The Dog is barking "); => n spolass Main{ public static void main(String[] args) { Dog(iny)= new Dog); y.animalSound();, —> The Dey 18 balks yn Polymorphism:- * The word “poly” means many and “morphs” means forms, So it means many forms. * we can define Java Polymorphism as the ability of a message to be displayed ini more than one form. I Types Of Polymorphism:- * Compile-time Polymorphism((Method Overloading): * Compile-time polymorphism is achieved through method overloading. It occurs when fnultiple methods in the same class have the[same name but different parameters (different number of parameters or different types of parameters). “Java Programmingby Vikassir & Method overloading can be done by changing: = * The number of parameters{in two methods. “add (4, 5) ) acld (a4, c) he data types of the parameters of methods. (oO Essen pes ett ie? medi Inka, jot): PIP, RO * The Order of the parameters of methods. aJd {flout a, {let ) , id(imta, flaath), — 7 C loge , imt bd 7 2a et class Adder{ void add(int a, int b){ System.out.println(“sum =”+(a+b)); q void add(int a, int b,int c){ System.out.println(“sui ies (a+ i } public static void main(String[] args) J sadereenen Adder(); ad,add(5,6); ad.add(5,4,7); n { -JavaProgrammingby Vikassir & * Runtime Polymorphism (Method Overriding): * Runtime polymorphism is achieved through method overriding,|It occurs when a subclass has a method with the same name, retutn oo and Parameters asametiod in its(superclass.) add : Gard> Rules for Java Method Overriding: av J=> pat? add * The method(must have the same name as i in the parent 2 * The method must have the same parameter as i in the parent class. * There must be an |S-A relationship (inheritance). class Vehicle { void move() { System.out.printin(" The vehicle is moving) car extelids Vehicle { void move() { System.out.printin("The car is driving."); public class TestOvel ing { (> public static void main(String{] args) { Vehicle myVehicle = new Vehicle();_ yVehicle.move(); // Output: The vehicle is moving. Car myCar = rigw Car(); yCar.move(); // Output: The caris driving. yn Interface interface support multiple inheritance. ‘erface does'n Contains Data Member. _2 Interface does'n contains Cunstructors. Pe ouuearieas Contains only incomplete member (signature of member). Member of interface can not be Static. “Java Programmingby Vikassir & Abstract class * Abstract class does not support multiple inheritance. _2-Abstract class contains Data Member. _2- Abstract class contains Cunstructors. * An abstract class Contains both _incomplete (abstract) and co! jembe! _2 Only Complete Member/of abstract class can be Static. “Java Programmingby Vikassir & Method Overloading Method Overriding + Multiplemethodsfsamenamein + Multiple methods of same name in single class. (different class. 1 . a of inheritance] as it is in * Inheritance is used, as it is in different single class. yeeeEeEeEG——n— class. * All methods have different signature./ » all methodsihave same signature.|_ * It's acompile time polymorphism. | * It's Arun time polymorphism. _v/No special keyword used. _Alitual & override keywords. Package:- * Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Types of Packages in Java Packages User Defined InBuilt Packages Packages Built-in Packages:- * These packages consist of a large number of classes which are a part of Java API. oe * Some of the commonly used built-in packages are:/>__ java.tang, java.io, java.util, ete oC a“ User-defined package: * These are the packages that are defined by the uset « First we create a directory myPackage (name should be same as the name 7?» of the package). * Then create the MyClass inside the directory with the first statement ———— being the package names. Creating a Package: // Calculator.java package com.example.math; => public class(Calculator { public int add(int a, int b) { return a+b; “Java Programmingby Vikassir & To use this calculator in another class // Mainjava import com.example.math.Calculator; J ee eee public class Main { D2 balk public static void main(String[] args) { => qlee tpetstel Calculator calc = new Calculator(); = Ame 4 int sum = calc.add(5, 3); “System tin("Sum:"+sum); ( 5“ : | } int aml 5 on) “Java Programmingby Vikassir & CLASSPATH IN JAVA * The classpath in Java is an environment variable that tells the Java compiler (javac) and the Java runtime (java) where to find user-defined classes and packages. _ * Itis essential when running Java programs that depend on external Setting the CLASSPATH in Java: 1. Temporary Setting of CLASSPATH FOR WINDOWS set CLASSPATH=path1;path2;path3 — Linux/Mac Terminal: | export CLASSPATH=path1:path2:path3 Rae eeee 2. Permanent Setting of CLASSPATH On Windows: * Right-click on My Computer or This PC and select Properties. _—— eee * Click on Advanced sys ettings. * Under System variables, click New to aa new CLASSPATH or select an existing CLASSPATH variable and click Edit. * Enter the paths to your libraries and classes. Separate each path with a semicolon (‘;’). . EXAMPLE:- 5C:\Program Files\Java\jdk1.8.0_231\lib; (.) refers to the current directory. : my JavaProjects\lib NU Regular Import Static Import « Uesd to importclasses orpackage,

You might also like