Introduction To Java

 Why Programming Language Introduced ?

Ans : 1) interface between human and machine.

          2) works on 0 and 1, false and true, on and off. 

          3) a - 97-122,      A-65-90,  1-1,   2-10


 Why Java ?

Ans : 1) used for mobile app, web app, games, enterprise

          2) having JVM tech. other lang like kotlin, scala, groovy also works on JVM. 

               so if you work on this tech then you can say that you work on java.

          3) Secure.

          4) you if know java you can learn other lang quickly. 

           5) used for testing, to develope android app.

          

What is java ?

Ans : 1) Java is object oriented programming language. developed by sun Microsystem of USA in                   1991.

           2) James Gosling inventor of java.

Features of Java ?

Ans :  1) Simple

           2) platform-independent - write once run anywhere. due to JVM.

                assembly lang are platform-dependent. it is low level lang.

           3) Secure - No Pointer concept.

           4) Object-oriented - written in terms of classes and objects. 

         5) Portable

         6) robust - capable of handling exception handling.

         7) interpreted - other lang. use either the compiler or an interpreter, but Java uses both a compiler and an interpreter. Java programs are compiled to generate bytecode files then JVM interprets the bytecode file during execution.
Interpretation mean code is executed line by line.

         8) multithreaded - Thread is a lightweight and independent subprocess of a running program (i.e, process) that shares resources. And when multiple threads run simultaneously is called multithreading. In many applications, you have seen multiple tasks running simultaneously, for example, Google Docs where while typing text, the spell check and autocorrect tasks are running. 

How java works ?

Ans : 

          1) Java compiles source code into bytecode(. class file)  and then bytecode is interpreted into machine code.

JVM : JVM (Java Virtual Machine). It is called a virtual machine because it doesn't physically exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can also run those programs which are written in other languages and compiled to Java bytecode.

JRE : JRE is Java Runtime Environment. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.


JDK : JDK is Java Development Kit. The Java Development Kit (JDK) is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools.


Java Program Structure :
package com.emp;   //package name
public class Demo {
      public Static void main[Strings [] args]
           sysout(" hello ");
  } 
 }
// class name - MyEmp, OurProject.
// method name - myScanner, myMarks 

Editions of Java Platforms

They are as follows:


1. Java SE (Standard Edition): 

- This edition is used to develop client-side app, desktop app , communication, and user interface.

- It Use to create StandAlone Application . “Standalone” just stands for “independent from anything else”. .“Java Standalone Application” does not require the Internet. It runs on a local machine.

Ex : Calculator , Notepad .(those application which are not need server or internet to play ). 


2. Java EE (Enterprise Edition): 

- This edition is used to develop server-side applications such as Java servlets, JavaServer Pages (JSP), and JavaServer Faces (JSF).

- It is use to create Enterprises Application or Distrubuted Application  .

Enterprise software, or enterprise application software, is computer software used by organizations rather than individual users.

- used to develop web-based, messaging, distributed, and enterprise applications.

Ex : Instagram , gmail .


3. Java ME (Micro Edition): 

- This edition is used to develop applications for mobile devices, such as cell phones. It is also used to develop Personnel Digital Assistants, Setup Box, and printers applications.

- It use to create Mobile Base Application .

- Mobile Base Application means if we design  & execute any Application using on the basis of mobile hardware then application is known as mobile base Application .

- we can both standalone & Enterprise application in Micro Edition.


Most Common question :

Comparison IndexC++Java
Platform-independentC++ is platform-dependent.Java is platform-independent.
Mainly used forC++ is mainly used for system programming. embbeded programmingJava is mainly used for application programming. It is widely used in Windows-based, web-based, enterprise, and mobile applications.

eg. fitness tracker, medical deviceseg. insta, facebook, flipcart


Multiple inheritanceC++ supports multiple inheritance.Java doesn't support multiple inheritance through class. It can be achieved by using interfaces in java.


PointersC++ supports pointersyou can't write the pointer program in java. 
Compiler and InterpreterC++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependenJava uses both compiler and interpreter. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform-independent.
Call by Value and Call by referenceC++ supports both call by value and call by reference.Java supports call by value only.
Structure and UnionC++ supports structures and unions.Java doesn't support structures and unions.

HardwareC++ is nearer to hardware.Java is not so interactive with hardware.
Object-orientedC++ is an object-oriented language. However, in the C language, a single root hierarchy is not possible.Java is also an object-oriented language. However, everything (except fundamental types) is an object in Java. It is a single root hierarchy as everything gets derived from java.lang.Object.


Memory Allocation :

1) when you initialised values to variable it allocates some memory.
if you declare byte - 1byte = 8bits
                       short - 2byte = 16bits
                         int -   4byte = 32bits
                       long -  8byte = 64bits

For Example :
range is from -ve to +ve that no.

The short data type in Java has a range of -32,768 to 32,767. Therefore, if you try to assign the value 32800 to a short variable, it will result in a compilation error because it exceeds the allowed range for the short data type.

you don't have to memorise the range use instead :




Installation of eclipse with JDK 
https://youtu.be/xXrPA_ONxK4?si=j2Tse_rpdUtN7djI

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 ClassesInterfaces, and Arrays.





    A. Examples of primitive data types :
    int myNum = 5;               
    float myFloatNum = 5.99f;    
    char myLetter = 'D';         
    boolean myBool = true;       
    String myText = "Hello";   
    Difference between char and String:
    char stores single character like a, b, c and String stores sequence of characters like "hello", "Good Morning".

    B. Examples of non-primitive types :

    1. Arrays: A collection of elements, all of the same type, stored in contiguous memory locations.

    example : int[] numbers = {1, 2, 3, 4, 5};

    2. Classes and Objects: Classes are blueprints for creating objects. Objects are instances of classes.

    Example :

    class Car {

        String color;

        String model;

        int year;

        

        Car(String c, String m, int y) {

            color = c;

            model = m;

            year = y;

        }

    }


    Car myCar = new Car("red", "Toyota", 2021);

    3. Interfaces: Abstract types that allow classes to implement them, enforcing certain methods to be present.
    interface Animal {
        void makeSound();
    }

    class Dog implements Animal {
        public void makeSound() {
            System.out.println("Woof");
        }
    }

    Operators in Java

    Operators are used to perform operations on variables and values.

    • Arithmetic operators
    • Assignment operators
    • Comparison operators
    • Logical operators
    • Bitwise operators

    1. Arithmetic operators
public class ArithmeticOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        System.out.println("Addition: " + (a + b));       // 15
        System.out.println("Subtraction: " + (a - b));    // 5
        System.out.println("Multiplication: " + (a * b)); // 50
        System.out.println("Division: " + (a / b));       // 2
        System.out.println("Modulus: " + (a % b));        // 0
    }
}

       2. Assignment operators

public class AssignmentOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        a += b; 
        System.out.println("a += b: " + a); 
//

        a -= b; 
        System.out.println("a -= b: " + a); 

        a *= b; 
        System.out.println("a *= b: " + a); 

        a /= b; 
        System.out.println("a /= b: " + a); 

        a %= b; 
        System.out.println("a %= b: " + a); 
    }
}


3. Comparison operators

public class ComparisonOperators {
    public static void main(String[] args) {
        int a = 10;
        int b = 5;

        System.out.println("a == b: " + (a == b)); // false
        System.out.println("a != b: " + (a != b)); // true
        System.out.println("a > b: " + (a > b));   // true
        System.out.println("a < b: " + (a < b));   // false
        System.out.println("a >= b: " + (a >= b)); // true
        System.out.println("a <= b: " + (a <= b)); // false
    }
}

4. Logical operators
public class LogicalOperators {
    public static void main(String[] args) {
        boolean x = true;
        boolean y = false;

        System.out.println("x && y: " + (x && y)); // false
        System.out.println("x || y: " + (x || y)); // true
        System.out.println("!x: " + (!x));         // false
    }
}

 5. Bitwise Operator

public class BitwiseOperators {
    public static void main(String[] args) {
        int a = 10; // 1010 in binary
        int b = 5;  // 0101 in binary

        System.out.println("a & b: " + (a & b));  // 0  (0000 in binary)
        System.out.println("a | b: " + (a | b));  // 15 (1111 in binary)
        System.out.println("a ^ b: " + (a ^ b));  // 15 (1111 in binary)
        System.out.println("~a: " + (~a));        // -11 (inverting all bits of 1010)
        System.out.println("a << 1: " + (a << 1)); // 20 (shifting bits left by 1 position)
        System.out.println("a >> 1: " + (a >> 1)); // 5  (shifting bits right by 1 position)
    }
}



Decision making Statements :
1. if
if (condition) { // code to be executed if condition is true

int number = 10;
if (number > 5) {
    System.out.println("Number is greater than 5");
}


2. else-if

The if-else statement provides an alternative block of code to execute if the condition is false.

Syntax:


if (condition) { // code to be executed if condition is true } else { // code to be executed if condition is false }

Example:


int num = -5; if (num > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is non-positive."); }
3. is-else-is ladder

The if-else-if ladder allows you to check multiple conditions and execute a block of code as soon as one of the conditions is true.

Sequentially evaluates conditions and executes the block of the first true condition. The rest are skipped

Syntax:

if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if all conditions are false }

Example:


int num = 0; if (num > 0) { System.out.println("Number is positive."); } else if (num < 0) { System.out.println("Number is negative."); } else { System.out.println("Number is zero."); }
4. Switch statement

The switch statement evaluates an expression and executes code blocks based on matching cases.

Evaluates the expression once and jumps directly to the matching case, executing its block and then exiting.

Syntax:


switch (expression) { case value1: // code to be executed if expression equals value1 break; case value2: // code to be executed if expression equals value2 break; default: // code to be executed if expression doesn't match any case }

Example 1:



import java.util.Scanner; public class Day1{ public static void main (String[] args){ System.out.println("Enter Day"); Scanner sc = new Scanner (System.in); int number = sc.nextInt(); String dayname = " "; switch(number){ case 1: dayname = "Monday"; break; case 2: dayname = "Tuesday"; break; default: dayname = "Wednesday"; } System.out.println("dayname " +dayname); } }

Example 2:

import java.util.Scanner; public class Maths{ public static void main (String[] args){ System.out.println("Enter case"); Scanner sc = new Scanner(System.in); int a=10; int b=20; int Calculate = 0; int number = sc.nextInt(); switch(number){ case 1: Calculate=a+b; break; case 2: Calculate=a-b; break; default: System.out.println("Done"); }System.out.println("Calculate"+Calculate); } }



Syntax for diff datatypes :
int number = sc.nextInt();
char word = sc.next().charAt(0);
String words = sc.nextLine();
double number = sc.nextDouble();
boolean value = sc.nextBoolean();
5. Ternary operator  

The ternary operator (? :) provides a concise way to evaluate a condition and assign a value based on the result.

Syntax:


variable = (condition) ? expression1 : expression2;
  • If condition is true, variable is assigned expression1.
  • If condition is false, variable is assigned expression2.

Example:


int num = 10; String result = (num > 0) ? "Positive" : "Non-positive"; System.out.println("Number is: " + result);


Example 2 :

public class TernaryOperationExample { public static void main(String[] args) { int num = 10; int a = 5; int b = 3; // Using ternary operator to decide whether to add or subtract int result = (num > 0) ? (a + b) : (a - b); System.out.println("Result is: " + result); } }

Example 3 :

public class AssignGrades {
    public static void main(String[] args) {
        int score = 85;
        String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : (score >= 70) ? "C" : (score >= 60) ? "D" : "F";

        System.out.println("The grade is: " + grade);
    }
}


Loops :
1. for loop

The for loop is used when the number of iterations is known or determined.

for (initialization; condition; update) {
    // code to be executed
}
  • Initialization: Initializes the loop control variable.
  • Condition: Evaluates whether to continue the loop or exit.
  • Update: Updates the loop control variable after each iteration.

for (int i = 0; i < 5; i++) {
    System.out.println(i); // prints numbers 0 to 4
}

2. while loop

The while loop is used when the number of iterations is not known beforehand, and the loop continues as long as the specified condition is true.

1.table of number

2. sum of even numbers from 1 to 10.

3. number divide by 3.

4. square, cube.

5. power.


Syntax:


while (condition) { // code to be executed }

Example:


int i = 0; while (i < 5) { System.out.println(i); // prints numbers 0 to 4 i++; 
}
3. do-while loop

The do-while loop is similar to the while loop, but it guarantees at least one execution of the loop body because it checks the condition after executing the loop body.

Syntax:


do { // code to be executed } while (condition);

Example:


int i = 0; do { System.out.println(i); // prints numbers 0 to 4 i++; } while (i < 5);

Loop control Statements:
1. break statement

In addition to the basic loop structures, Java also provides loop control statements to alter the normal flow of loops:

  • break statement: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.


    for (int i = 0; i < 10; i++) { if (i == 5) { break; // exits the loop when i is 5 } System.out.println(i); }
2. continue statement

Skips the current iteration of the loop and continues with the next iteration.


for (int i = 0; i < 5; i++) { if (i % 2 == 0) { continue; // skips even numbers } System.out.println(i); // prints odd numbers (1, 3) }
3. return statement

return statement: Exits from the current method and optionally returns a value.


public int sum(int a, int b) { return a + b; // returns the sum of a and b } public class DoWhileExample10 { public static void main(String[] args) { int number = 12345; int reversed = 0; do { int digit = number % 10; reversed = reversed * 10 + digit; number /= 10; } while (number != 0); System.out.println("Reversed number: " + reversed); } } Arrays:

An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

declaration of array :
String [] cars; initialization of array :
String[] cars = {"creta", "verna", "BMW"}; initialization of integer array :
int[] numbers = {1,5,33,68,2}; To change the specific cars[0] = "Tata Safari"

1. Declaring an Array

In Java, you can declare an array by specifying the type of elements it will hold, followed by square brackets [].


int[] numbers;

2. Initializing an Array

You can initialize an array by specifying the size (number of elements) it will hold.


numbers = new int[5];

Or you can declare and initialize it at the same time.


int[] numbers = new int[5];

3. Assigning Values to an Array

You can assign values to the array elements using the index.


numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;

4. Declaring, Initializing, and Assigning Values in One Step

You can also declare, initialize, and assign values to an array in one step.


int[] numbers = {10, 20, 30, 40, 50};

5. Accessing Array Elements

You can access array elements using their index.


System.out.println(numbers[0]); // Outputs 10 System.out.println(numbers[1]); // Outputs 20 System.out.println(numbers[2]); // Outputs 30 System.out.println(numbers[3]); // Outputs 40 System.out.println(numbers[4]); // Outputs 50

6. Looping Through an Array

You can use a for loop to iterate through the elements of an array.


for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }

7. Using Enhanced For Loop

Java provides an enhanced for loop (also known as a "for-each" loop) to iterate through arrays.


for (int num : numbers) { System.out.println(num); }

Complete Example

Here is a complete example that demonstrates all the basic operations on an array:


public class ArrayExample { public static void main(String[] args) { // Declare and initialize an array int[] numbers = new int[5]; // Assign values to the array numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; // Access and print array elements System.out.println("Array elements:"); for (int i = 0; i < numbers.length; i++) { System.out.println("Element at index " + i + ": " + numbers[i]); } // Using enhanced for loop to print array elements System.out.println("\nUsing enhanced for loop:"); for (int num : numbers) { System.out.println(num); } } }

Output


Array elements: Element at index 0: 10 Element at index 1: 20 Element at index 2: 30 Element at index 3: 40 Element at index 4: 50 Using enhanced for loop: 10 20 30 40 50

Advantages of Array :
  • Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
  • Random access: We can get any data located at an index position.
Disadvantages of Array :
  • Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.

Methods :

method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:

Syntax :
accessModifier returnType methodName(parameterList) { // Method body }

Example :

public class HelloWorld { // Method definition public void printHello() { System.out.println("Hello, World!"); } public static void main(String[] args) { HelloWorld hw = new HelloWorld(); // Method call hw.printHello(); } }
abstract Class

Interface :
Defi : Interface is just like a class which contain only abstract methods. 1. achieve interface java provides a keyword called implements.
2. interface methods are public and abstract by default.
3. interface variables are by default public + static + final.
Exception :
unexpected, unwanted,abnormal situation that occured at runtime called exception.
Exception Handling :
Techniquenic to handle exception:
try, catch, throw, throws, finally

    Comments

    Popular posts from this blog

    ReactJS

    ReactJs Interview Questions