Java Notes PW

What is Programming?

Programming is simply creating a set of instructions for a computer to perform a specific task. Programming can be done using a variety of computer programming languages eg. Java, C++, C and the list is endless! The best part is, out of these very many options, you can go ahead with the language of your choice to implement the concepts in the form of a logical code.

Category of Programming Languages

Programming languages that have been developed so far can majorly be categorized into machine language, assembly language, and high-level language.

Machine Level Language:

A the name suggests, it is a low-level-language made up of binary numbers or bits that a machine/computer can understand. It is a sequence of 0s and 1s. It is also known as machine code or object code. any program that we write finally transforms into a sequence of s and 1s for the computer to understand.

Assembly Language:

Assembly language is intended to communicate directly with a computer's hardware. Unlike the usual machine language, which consists of binary characters, assembly language is expressed in a more human-readable form. In the future many of you are going to learn and program microprocessors in your higher studies or jobs; that would require an expertise in assembly language.

High-level Language:

It refers to the programming languages that allow the use of symbolic operators (to signify operations, eg. +,-,*,/ etc.) and symbolic names(to represent data and data structures, eg. variable names). They are also structured with syntax and semantics to describe the computing algorithm/program. This often requires the use of a compiler or an interpreter which helps in the translation from high-level human-understandable code into low-level machine code because the computer only works on the binary data. We will be learning and focussing on this category of language in our course. Before we move ahead, are you still confused about the differences between compiling and interpreting? Let us discuss this.

Compilation Vs Interpretation:

Compilation is the process to convert a high-level programming language into machine language (all at once) that the computer can understand. The software which performs this conversion is called a compiler.

 Interpretation is performed by an Interpreter which directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code. This conversion of code happens line by line. Examples of interpreted languages are Perl, Python and Matlab.

Type of Programming Paradigms:

 ⮚ Procedural

 ⮚ Functional

 ⮚ Object Oriented

 Procedural:

Consider a scenario where a program has to collect some data from users (read), perform some calculations (calculate), and then display the result(print) when requested; a simple example of this scenario is any online transaction that you/your parents do. In procedural approach, we can write 3 different procedures/functions for each of the operations of reading, calculating and printing (which could interact amongst each other as well). Hence, in the procedural approach:

 The entire program code is organized as a set of procedures/functions or discrete blocks of codes that are executed in an order.

These procedures are also known as subroutines or functions and contain a series of steps that will be carried out when the procedure is called/used. 

 Some of the programming languages that enable us to use procedural approach : BASIC, FORTRAN, ALGOL, C, COBOL, and Pascal.

Functional:

Let's assume a scenario where we have to perform lots of different operations on the same set of data. This can be in the domains such as the web, statistics, financial analysis, and machine learning. Here, the functional programming paradigm helps a lot.

The program code is organized in pure functions(which always yield the same value for the same set of inputs without any deviation) with each function set up to perform a clearly defined task.

The data/variables are passed in the function as parameters (for the functions to interact with other functions or programs).

Languages that support this approach are: Javascript, Python, etc. 

Object Oriented:

 The program data is organized in classes and objects rather than functions and logic.

 A class is a blueprint for creating objects and an object is referred to as an instance of a class that has unique attributes and behavior.

A good example of this could be you, yes you! You can be a ‘student’ or a ‘working professional’. In this scenario,under the class of ‘Person’, we can have a ‘Student’ or ‘Working professional’ class and you can be an instance of any of these based on whether you fall in the ‘student’ category or ‘working professional’ category. Hence, you are an object

Languages that support object-oriented approach include: Java, C++, C#, Python, R, PHP, Visual Basic. 

 The programming language that we are going to learn here is extremely simple yet very powerful! Any guesses ?! Yes, it's Java (we are already in the course, no marks for guessing!) Lets now, hit the bulls eye !! Let's get started.

Introduction to Java

Java is a general-purpose programming language created for developers (to write once and run anywhere) by James Gosling at Sun Microsystems later acquired by Oracle Corporation. The compiled Java code can run on all platforms that support Java. Java applications are compiled to byte code that can successfully run on any Java Virtual Machine (JVM). Syntax of Java is similar to C/C++. Java works on class-based and object-oriented approach of programming. It is one of the most widely used programming languages for creating desktop and mobile applications as well as big data processing and embedded systems. 

Features of Java Programming

1.  An Object-Oriented Language: Java is an object-oriented language because it is based on the concept of objects and classes (We will explore more about it once we start to code). Here, a complex problem is divided into smaller sets by using concepts of OOP. This makes Java code more understandable (closer to real-life implementation) and reusable. It also improves design and makes the code easier to maintain.

 2. Java is platform independent: The Java code written on one platform can run successfully on other platforms without any modifications. It is not compiled into platform-specific machine code but into platform-independent byte code.

3. Simple and Secure: Java is designed to be easy to learn. If you understand the basic concepts of OOP, Java would be easy to master. It is one of the simplest languages as it does not have complex concepts like pointers, operator overloading, multiple inheritance, and explicit memory allocation (as we see in C++).

4. Large Standard Library: One of the reasons java is so famous is the availability of a huge standard library. To help software program builders like you (in future!), the Java environment carries and supports loads of classes and methods put into numerous packages.

Why is Java better than other programming languages?

Java has added advantages over other languages and environments that make it very appropriate for almost all programming errands. A few of them are :

1. Java syntax is simple to understand and easy to memorize since it is intuitive. 

2. Java has been designed to be simpler to type,compile, debug, and learn than other programming languages. 

3. Java is secure, convenient, viable and comes with superior high-level concurrency devices. Because of this, java is regularly the default choice for scientific applications, including natural language processing.

4. One of the coolest things about Java is its futuristic approach. When the whole world today is still stuck in Java 8 or Java 11, Oracle has already launched Java 18. The whole development community associated with java is very progressive which has kept it up to date since its inception. 

Architecture

Before moving ahead with programming, we need to understand the architecture of Java with its components.

Java Architecture comprises of three major components viz. JVM, JRE, and JDK. Let us discuss each of these in brief. 

JVM:- Java Virtual Machine or JVM, loads, verifies and executes Java bytecode (object code which is further converted into machine code). It is known as the interpreter or the core of Java programming language because it executes Java programming.The JVM manages system memory and provides a portable execution environment for Java-based applications. JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent). 

 Examples: Hotspot,Eclipse OpenJ9

JRE:-  The JRE is the underlying technology that communicates between the Java program and the operating system. It acts as a translator and facilitator, providing all the resources so that once you write Java software, it runs on any operating system without further modifications. A software program needs a runtime environment that provides access to memory and other system resources such as program files and dependencies. In the past, most software used the operating system directly as its runtime environment. However, this meant that developers had to write different code for each operating system that they wanted their applications to run on. The Java Runtime Environment (JRE) technology was created as a solution to this problem. 

JDK:-  The JDK is a collection of ‘software tools’ that you can use for developing Java applications. You can set up the JDK in your development environment by downloading and installing it. Select the JDK software version that matches the Java version you want to use. Still confused ! Let us look at the precise differences between the three. This


 Installation Guide For Windows 
 Content
🔘 Downloading and Installing JDK 

🔘 Downloading and Installing IntelliJ Idea IDE

1. Click the link to download JDK or you may also go to link this website and download the latest version of java

Installation Guide Java For Windows

Steps for installing IntelliJ ldea

1. Click on the link it will redirect you to the jetbrain website. Download the latest version of IntelliJ idea from Community section.

Steps for installing IntelliJ ldea

2. Keep pressing ‘next’ without changing any of the default settings and you will land on this screen.


3. Check the options as shown in the image and proceed with ‘Next’ button.

4. To complete the installation, reboot/restart your system.

When you open IntelliJ from the icon, this screen will appear

Installation Completed


JDK: - JDK stands for java development kit, it internally contains JRE & JVM where JRE stands for Java runtime environment and JVM stands for java virtual machine. JDK provides all the tools to work with java language.

JRE: - JRE stands for java runtime environment, it provides an environment to execute the java program. It internally contains JVM which is responsible to execute a Java Program.

JVM: - JVM Stands for java virtual machine, it is the software in the form of interpreter written in ‘C’ language through which we can execute our java program.

What is JAVA? With Syntax & Example.

Java is a class based high-level object-oriented programming languages developed by “James goslig” and his friends in the year 1991.

                                                                The first version of java (JDK 1.0) was released on the year 23rd jan, 1996 by sun microsystem.

Syntax: -

                Class class-name

                {

                                public static void main(String arg[])

                                {

                                                System.out.print(“     “);

                                }

                }

Rule: -

1.       Save -> class_name.java

2.       Compilation -> javac class_name.java

3.       Execution -> java class_name

Example: -

                Class A

{

                public static void main(String[]a)

                {

                                System.out.print(“welcome java”);

                }

}

 

Java History

·         java is a totally computer-based programming language developed by sun microsystem (james gosling, mike Sheridan & patrich Naughton).

·         In the year 1991 James Gosling & his friend Start a project.

Team -> Green team

·         James Gosling -> greentalk

Extension -> .gt

·         Greentalk -> oak

·         Oak -> Java (1995)

·         Java -> Setbox, television, remote etc….

·         Java -> internet programming

·         Version -> JDK alpha & Beta, 1995 (By Sun Microsystem).

·         Latest Version -> JDK 15 (2020, Oracle)

·         Sun Microsystem -> Oracle corporation, 2010

JAVA: -

        Core JAVA

        Advance JAVA

        Android JAVA

Features of Java

1.       Object oriented

2.       Platform independent

3.       Simple language

4.       Secure

5.       Portable

6.       Compiled & interpreted

7.       Robust

8.       Distributed

9.       Multi-threaded

10.   Performance

11.   Dynamic

class A

{

                public static void main(String args[])

                {

                               

                }

}

 

class A

{

                public static void main(String[] args)

                {

                                System.out.println(“Hello World”);

                }

}

________________________________________________________

Class A

                void show()

                {

                                System.out.println(“hello india”);

{

                public static void main(String []args)

                {

                                A ref=new A();

                                ref.show();

                                System.out.println(“Welcome java”);

                }

}             

___________________________________________________

Class A

                static void show()

                {

                                System.out.println(“hello india”);

{

                public static void main(String []args)

                {

                                 A.show();

                                System.out.println(“Welcome java”);

                }

}

What is comment? Full explanation.

Comment are the statements that are totally ignored by the compiler & interpreter.

Why We use comment: -

1.       The comments can be used to provide explanation about the program.

2.       Comments makes program move understandable and redable to the other programmer.

Type of comment: -

1.       Single line comment   à // statements

2.       Multiline comment à /* statements */

3.       Documentation à /** statements */

/*Java Variable*/

Class test

{

            int a=10;               // instance variable

            static int b=20;  //static variable

            public static void main(String[] args)

                {

                                Int c=30;               //local variable

                                Final int D=40;   //final variable

                                Test t=new Test();           //object variable

                                System.out.println(t.a);

                                System.out.println(b);

                                System.out.println(c);

                                Systme.out.println(D);

                }

}

Data type: -

Datatype specify the different sizes & values that can be stored in the variable.

 

 

 

Datatype

Primary(primitive)

User-defined(non-primitive)

Numeric

Non-numeric

integric

Decimal

Byte (1) byte

Short (2)

Int (4)

Long (8)

 

Float (4)

Double (8)

Char (2)

Boolean (1 bit)

class

interface

arrays

String


 


What is variable? Discuss with Types.

Variable Is the name of memory location. in other word we can say it is user defined name which is given by user. Variable can store any types of values.

Type of Variable: -

1.       Local

2.       Static

3.       Instance

Local Variable: - A variable which is declared inside the body of the method or method parameter called local variable.

Instance Variable: - A variable which is declared inside the class but outside of all the methods called instance variable.

Static Variable: - A variable which is declared with the help of static keyword called static variable.

Example: -

            class A

            {

                        static int b=20;//static

                        int c=30;//instance

                                public static void main(string[]args)

                                {

                                                int a=10;/local

                                                A ref=new A();

                                                System.out.println(a);

                                                System.out.println(A.b);

                                                System.out.println(ref.c);

                                }

                }

class try

{

                static int a=10;

                void fun()

                {

                                int b=10;

                                System.out.println(a+”  “+b);

                                ++a;       ++b;

                }

                public static void main(String[] args)

                {

                                A r=new A();

                                r.fun();

                                r.fun();

                }

}

Add two number without user input

class add

{

                public static void main(String [] args)

                {

                                int num1=30,num2=40;

                                int sum=num1+num2;

                                System.out.println(sum);

                }

}

What is typecasting? With type.

Converting one datatype to another datatype is called typecasting.

Type: -

1.       Implicit

2.       Explicit

Implicit: -

It is automatically performed by the compiler.

// Implicit Typecasting.......

 

class implicit

{

                public static void main(String [] args)

                {

                                int a=10;               //4 bytes

                                double b=a;        //8 bytes

                                System.out.println(b);

                }

}

Explicit Typecasting: -

By default, the compiler, doesn’t allow the explicit typecasting.

// Explicit Typecasting.......

 

class explicit

{

                public static void main(String [] args)

                {

                                double a=10.5;

                                int b=(int)a;

                                System.out.println(b);

                }

}

Input (Scanner class): -    

Scanner is a pre-defined class in java which is available in java.util package. It is used to get user input.

Rule 1: -

                If we use Scanner class, must have to create object of Scanner class.

                Syntax: -

                                Scanner object_name=new Scanner(System.in);

Rule 2: -

Scanner class methods: -

1.       nextLine();  //String

2.       nextInt();                    //integer

3.       nextFloat();                //floating

4.       nextBoolean();          //true or false

5.       nextDouble();            //double

Rule 3: -

import Scanner class package of the top line of program: -

                Syntax: - import java.util Scanner;

Rule 4: -

                Wrong input (Input mismatch Exception)

Output: - (System.out.print())

It is an output statement in java through which we can print the variables, expressions and many more contents.

System: - 1. Pre-defined class.

InputOutput Program: -

import java.util.Scanner;

class inputOutput

{

                public static void main(String [] args)

                {

                                int a;

                                System.out.println("Enter value of a");

                                Scanner obj=new Scanner(System.in);

                                a=obj.nextInt();

                                System.out.println("Value of a is "+a);

                }

}

import java.util.Scanner;

class userInput

{

                public static void main(String[]args)

                {

                                int a,b;

                                Scanner obj=new Scanner(System.in);

                                System.out.print("Enter value of a ");

                                a=obj.nextInt();

                                System.out.print("Enter value of b ");

                                b=obj.nextInt();

                                System.out.print("sum of two number is "+(a+b));

                }

}

What is Token? Full explanation.

Token is the smallest elements of a program that is identified by a compiler.

                                                                                                                                                Every java statements and expression are created using tokens.

Token: -

1.       Keywords            ex: - int, static, void

2.       Identifiers           ex: - variable, method, class_name

3.       Operator             ex: - +, -, *, /, %, &&, ||, ++, --

4.       Separator            ex: -  ;   ,   .   :   ()

5.       Literal                   

What is keyword? Full explanation.

Keyword’s are the reserved word whose meaning is already defined in the compiler called keywords.

Java Keyword’s: -

abstract

continue

for

new

switch

assert***

default

goto*

package

synchronized

boolean

do

if

private

this

break

double

implements

protected

throw

byte

else

import

public

throws

case

enum****

instanceof

return

transient

catch

extends

int

short

try

char

final

interface

static

void

class

finally

long

strictfp**

volatile

const*

float

native

super

while

 

*

 

not used

**

 

added in 1.2

***

 

added in 1.4

****

 

added in 5.0

Note: -

1.       True, false and null just like keywords, but they are actually literals.

2.       You can’t use any of the following as identifiers in your programs.

What is identifier? Full explanation.

In java, an identifier is the name of a variable, method, class, package or interface that is used for the purpose of identification.

Rule of identifier: -

1.       Keyword can’t be used as a identifier.

2.       Identifier are case-sensitive.

3.       We can’t use whitespace in between identifier.

4.       Identifier always start with letters, $ or _ (underscore).

What is operators? With types.

Operator is a symbol that Is used to perform operations according to user requirement. (variable & values)

Types: -

1.       Arithmetic (+, - ,*, /, %)

2.       Relational (<, >, <=, >=, !=, ==)

3.       Logical (&&, ||, !)

4.      

Unary

Increment & decrement (++, --)

5.       Assignment

a.       Simple (=)

b.       Compound (+=, -=, *= etc)

6.       Ternary (? :)

7.       Bitwise(AND, OR, XOR, COMPLEMENT)

// Arithmetic Operator Example......

import java.util.Scanner;

class arithmetic

{

                public static void main(String [] args)

                {

                                int a,b;

                                Scanner obj=new Scanner(System.in);

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

                                a=obj.nextInt();

                                b=obj.nextInt();

                                System.out.println("Addition "+(a+b));

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

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

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

                                System.out.println("Modulo "+(a%b));

                }

}

// Relational Operator Example.........

import java.util.Scanner;

class relational

{

                public static void main(String [] args)

                {

                                int a,b;

                                Scanner obj=new Scanner(System.in);

                                System.out.println("Enter two number: ");

                                a=obj.nextInt();

                                b=obj.nextInt();

                                System.out.println("false/true (a<b)  "+(a<b));

                                System.out.println("false/true (a>b)  "+(a>b));

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

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

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

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

                }

}

//Logical Operator Example............

class logical

{

                public static void main(String []args)

                {

                                System.out.println("Logical AND");                         

                                System.out.println((10>5)&&(2>1));                        //true

                                System.out.println((10>5)&&(2<1));                        //false

                                System.out.println((10<5)&&(2<1));                        //false

                               

                               

                                System.out.println("Logical OR");

                                System.out.println(10>5||(2>1));                             //true

                                System.out.println(10>5||(2<1));                             //true

                                System.out.println(10<5||(2<1));                             //false

 

                                System.out.println("Logical NOT");

                                System.out.println(!(10>5));                       //false

                                System.out.println(!(10<5));                       //true

                }

}

//Increment/Decrement Operator Example................

class incrdecr

{

                public static void main(String []args)

                {

                                int a=10;

                                System.out.println(a);

                                System.out.println("PrePost increment...");

                                System.out.println(a++);

                                System.out.println(++a);

                                System.out.println("PrePost decrement...");

                                System.out.println(a--);

                                System.out.println(--a);

                }

}

// Assignment Operator Example.......

class assignment

{

                public static void main(String [] arts)

                {

                                int a=10;

                                System.out.println(a);

                               

                                a+=10;// a=a+10;

                                System.out.println(a);

 

                                a-=10;// a=a-10;

                                System.out.println(a);

                }

}

// Ternary Operator Example.....

class Ternary

{             

                public static void main(String []args)

                {

                                int a=10,b=20,max;

                                max=(a>b)?a:b;

                                System.out.print(max);

                }

}

// Bitwise Operator Example......

class bitwise

{

                public static void main(String [] args)

                {

                                int a=5,b=7;

                                System.out.println("AND "+(a&b));

                                System.out.println("OR "+(a|b));

                                System.out.println("XOR "+(a^b));

                                System.out.println("Complement "+(~a));

                }

}

Decision Making: -

1.       If statement

a.       Simple if

b.       If-else

c.       If else ladder

d.       Nested if-else

2.       Switch Statement

Simple if statement: -

è It is used when we want to test a condition.

Syntax: - if(condition)

                {

                }

Example: -

// Simple If Statement

import java.util.Scanner;

class simpleIf

{

                public static void main(String []a)

                {

                                int age;

                                Scanner r=new Scanner(System.in);

                                System.out.println("Enter your age: ");

                                age=r.nextInt();

                                if(age>=18)

                                {

                                                System.out.println("Eligible for vote");

                                }

                                                System.out.print("thank u");

                }

}

If-else statement: -

It is used to execute two statements either if statement or else statement for a single condition.

Syntax: -

                If(condition)

                {

                }

                Else

                {

                }

Example: -

//if-else statement............

import java.util.Scanner;

class ifElse

{

                public static void main(String a[])

                {

                                int num;

                                Scanner r=new Scanner(System.in);

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

                                num=r.nextInt();

                                if(num>0)

                                {

                                                System.out.println("+ve number");

                                }

                                else

                                {

                                                System.out.print("-ve number");

                                }

                }

};

else-if ladder statement: -

It is used when we have only one if block, multiple else-if blocks and at last one else block.

Syntax: -

If(condition)

{

}

Else if(condition)

{

}

Else if(condition)

{

}

Else

{

}

Example: -

//else-if ladder statement

import java.util.Scanner;

class elseIf

{

                public static void main(String[] args)

                {

                                int marks;

                                Scanner obj=new Scanner(System.in);

                                System.out.print("Enter your marks: ");

                                marks=obj.nextInt();

                                if(marks>80)

                                {

                                                System.out.print("Topper");

                                }

                                else if(marks<80 && marks>60)

                                {

                                                System.out.print("first");

                                }

                                else

                                {

                                                System.out.print("second");

                                }

                }

};

Nested if else statement: -

Whenever we define if else block, inside this if else block we define another if else block is called nested if else statement.

Syntax: -

If(condition)

{

                If(condition)

                {

                }

                Else

                {

                }

Else

{

                If(condition)

                {

                }

                Else

                {

                }

}             

Example: -

//Nested if else statement…….

import java.util.Scanner;

class nestedIf

{

                public static void main(String[]args)

                {

                                int a,b,c;

                                Scanner r=new Scanner(System.in);

                                System.out.println("Enter three number: ");

                                a=r.nextInt();

                                b=r.nextInt();

                                c=r.nextInt();

                                if(a>b)

                                {

                                                if(a>c)

                                                {

                                                                System.out.print("greatest number is "+a);

                                                }

                                                else

                                                {

                                                                System.out.print("greatest number is "+c);

                                                }

                                }

                                else

                                {

                                                if(b>c)

                                                {

                                                                System.out.print("greatest number is "+b);

                                                }

                                                else

                                                {

                                                                System.out.print("greatest number is "+c);

                                                }

                                }

                }

}

Switch statement: -

Switch is a multiple-choice decision-making selection statement, it used when we want to select only one case out of multiple cases. 

Syntax: -

                Switch(expression)

                {

                                Case 1:

                                Statement1;

                                Break;

                                Case 2:

                                Statement 2;

                                Break;

                                Case n:

                                Statement 3;

                                Break;

                                Default:

                                Statement;

                }

Example: -

import java.util.Scanner;

class Swithc

{

                public static void main(String[]args)

                {

                                int a=10,b=20,ch;

                                Scanner r=new Scanner(System.in);

                                System.out.println("Enter your choice: ");

                                ch=r.nextInt();

                                switch(ch)

                                {

                                                case 1:

                                                                System.out.println("Sum is "+(a+b));

                                                                break;

                                                case 2:

                                                                System.out.println("Subtract is "+(a-b));

                                                                break;

                                                case 3:

                                                                System.out.println("Sum is "+(a*b));

                                                                break;

                                                case 4:

                                                                System.out.println("Sum is "+(a/b));

                                                                break;

                                                default:

                                                                System.out.println("invalid choice.....!");

                                }

                }

}

Looping Statement: -

è Whenever we have to repeat certain statement several times is called loop.

Advantage: -

1.       Fast execution

2.       Reusability

3.       Decrease line of code

4.       Memory space less

Type: -

There are four type of loop

1.       While loop

2.       Do-while loop

3.       For loop

4.       For each loop                                   

 

1.     While loop: -

è While loop is a pre-test loop, it is used when we don’t know the no of iteration in advance.

è It is also known as entry control loop.                    

Syntax: -

While(condition)

{

                Statement;

}

Example: -

class loop

{

                public static void main(String[]args)

                {

                                int n=1;

                                while(n<=10)

                                {

                                                System.out.println("Hello mr. Hemant Kumar");

                                                ++n;

                                }

                }

}

2.     Do-while loop: -

è Do-while loop is a post-test loop, it is used when we want to execute loop body atleast once even condition is false.

è It is also known as exit control loop.

Syntax: -

Do

{

                Statement;

}

While(condition);

Example: -

/* do while loop statement */

class dowhile

{

                public static void main(String[]arts)

                {

                                int n=1;

                                do

                                {

                                                System.out.println(n+" ");

                                                ++n;

                                }

                                while(n<=10);

                }

}

3.     For loop: -

è For loop is the most commonly used loop, it is used when we want to perform initialization, condition and increment/decrement operation in single line.

Syntax: -

for(initialization;condition;increment/decrement)

{

                Statement;

}

Example: -

// for loop example......

class for1

{

                public static void main(String[]args)

                {

                                for(int i=1;i<=10;i++)

                                {

                                                System.out.println(i);

                                }

                }

}

For each loop: -

For each loop mainly used to fetch the values from a collection like array.

Syntax: -

                for(data_type var1 : var2)

                {

                                Statement;

                }

Example: -

// for each loop example......

class forEach

{

                public static void main(String[]args)

                {

                                int a[]={10,20,30,40,50,60,70,80,90,100};

                                for(int b : a)

                                {

                                                System.out.println(b);

                                }

                }

}

Nested for loop: -                                                                                   

è A for loop which contain inside another for loop is called nested for loop.

Syntax: -

For(initialization; condition;updation)

{

                For(initialization; condition; updation)

                {

               

                }

}

Example: -

// nested for loop example.......

class nested_for

{

                public static void main(String[]args)

                {

                                int i,j;

                                for(i=1;i<=5;i++)

                                {

                                                for(j=1;j<=5;j++)

                                                {

                                                                System.out.print("* ");

                                                }

                                                System.out.println();

                                }

                }

Java MCQ’S

1.     Who is the Developer of java?

a)       Dennis Ritchie

b)      James Gosling

c)       Bjarne Stroustrup

d)      Charles Babbage     

2.     What was java name Before?

a)      Java

b)      Javax

c)       Classes and java

d)      Oak

3.     In which year java was Developed?

a)      1991

b)      1972

c)       1979

d)      1995

4.     What is the extension of java?

a)      .gt

b)      .oak

c)       .java

d)      .exe

5.     Java was Developed by_________________?

a)      Sun MicroSystems

b)      Oracle

c)       Microsoft

d)      ANSI

6.     Which of the following are flavours of java?

a)      J2SE

b)      J2EE

c)       J2ME

d)      All of above

7.     Whose product is java right now?

a)      Sun MicroSystems

b)      Microsoft

c)       ANSI

d)      Oracle

8.     What is the first version of java?

a)      JDK alpha & Beta

b)      JDK 1.0

c)       JDK 15

d)      All of above

9.     What is the compilation process of java program?

a)      Java class_name.java

b)      Javac class_name.java

c)       Javac class_name

d)      Class_name.java

10.What is the Execution process of java program?

a)      Java class_name

b)      Javac class_name

c)       Class_name.java

d)      Class_name java

11.In java, JDK stands for_____________?

a)      Java Design Kit

b)      Java Developer Kit

c)       Java Development Kit

d)      None of these

12.In java, JRE stands for_______________?

a)      Java Running Environment

b)      Java Runtime Environment

c)       Java Runtime Execution

d)      None of these

13.In java, JVM stands for_______________?

a)      Java Virtual Machine

b)      Java Verification Machine

c)       Java virtual Moment

d)      None of these

14.Which of the following is features of java?

a)      Platform independent

b)      Simple & secure

c)       Dynamic

d)      All of above

15.In java, system class is defined in __________?

a)      Java.Util package

b)      Java.lang package

c)       Java.io package

d)      None

16.In java, Scanner class is defined in ___________?

a)      Java.util package

b)      Java.lang package

c)       Java.io package

d)      All of above

17.In java, Scanner class is used to take input at___________?

a)      Compile-time

b)      Run-time

c)       Both a & b

d)      None

18.Which Stream is used for output?

a)      System.out

b)      System.in

c)       Scanner

d)      none

19.Which Scanner class method is used to read integer value?

a)      nextInt()

b)      next()

c)       readInt()

d)      nextInteger()

20.which Scanner class method is used to read String value?

a)      nextLine()

b)      next()

c)       readString()

d)      Both a & b

21.How many types of datatype in java?

a)      One

b)      Two

c)       Three

d)      None

22.How many primitive datatypes in java?

a)      4

b)      6

c)       7

d)      8

23.What is the size of char datatype?

a)      1 byte

b)      2 bytes

c)       4 bytes

d)      None

24.What is the default value of Boolean datatype?

a)      True

b)      False

c)       True/false

d)      None

25.Which of the following is smallest integer datatype?

a)      Short

b)      Int

c)       Long

d)      Byte

26.Which of the following datatypes comes under floating datatypes?

a)      Long

b)      Double

c)       Float

d)      Both b & c

27.What is the range of byte datatype is?

a)      -128 to 128

b)      -127 to 128

c)       -128 to 127

d)      -127 to 127

28.How many loops are their in java?

a)      Two

b)      Three

c)       Four

d)      None

29.Which loop always execute atleast once, even condition is false?

a)      While loop

b)      Do while loop

c)       For loop

d)      For-each loop

30.Do while loop is also known as ________loop?

a)      Entry control

b)      Exit control

c)       Both a & b

d)      None

31.Which of the following loops are entry-controlled loop?

a)      While

b)      Do while

c)       For loop

d)      Both a & c

32. What is the purpose for using loop?

a)      For repetition

b)      Check condition

c)       Finding errors

d)      None

33. Which loop is best suitable for arrays in java?

a)      For loop

b)      For-each loop

c)       While loop

d)      Do while loop

34. Which of following is not a part of binary operator?

a)      Assignment operator

b)      Arithmetic operator

c)       Relational operator

d)      Logical operator

35. Which of following is not a arithmetic operator?

a)      +

b)      *

c)       %

d)      &

36. How many types of logical operators?

a)      Two

b)      Three

c)       Four

d)      None

37.Relational operator is used for?

a)      Comparison

b)      Assignment

c)       Finding errors

d)      All of above

38. Which of the following is bitwise AND operator?

a)      &&

b)      ||

c)       !

d)      &

39. Which operator is used for alternate of if-else statement?

a)      Arithmetic operator

b)      Bitwise operator

c)       Ternary operator

d)      Incr/Decr oprator

40. What is the default value of static variable?

a)      0

b)      1

c)       Garbage

d)      None

41. A variable which is declared inside the method called___________?

a)      Instance variable

b)      Local variable

c)       Static variable

d)      None

42. Which of these selection statements test only for equality?

a)      If

b)      Switch

c)       If &switch

d)      None

43. If statement execute of skip statement depending on the__________expression?

a)      Boolean

b)      Double

c)       Integeric

d)      None

Programming Questions

//odd even program

import java.util.Scanner;

class oddEven

{

                public static void main(String[]args)

                {

                                int n;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                if(n%2==0)

                                {

                                                System.out.print("number is even ");

                                }

                                else

                                {

                                                System.out.print("number is odd ");

                                }

                }

}

// to print first N natural numbers program

import java.util.Scanner;

class natural

{

                public static void main(String[]args)

                {

                                int n;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                for(int i=1;i<=n;i++)

                                {

                                                System.out.print(i+ " ");

                                }

                }

}

// Sum of first N natural numbers program

import java.util.Scanner;

class naturalSum

{

                public static void main(String[]args)

                {

                                int n,sum=0;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                for(int i=1;i<=n;i++)

                                {

                                                sum=sum+i;

                                }

                                System.out.println("Sum is " +sum);

                }

}

//print all odd numbers between 1 to N

import java.util.Scanner;

class odd

{

                public static void main(String []args)

                {

                                int n;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                for(int i=1;i<=n;i+=2)

                                {

                                                System.out.print(i+" ");

                                }

                }

};

//print all odd numbers between 2 to N

import java.util.Scanner;

class even

{

                public static void main(String []args)

                {

                                int n;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                for(int i=2;i<=n;i+=2)

                                {

                                                System.out.print(i+" ");

                                }

                }

};            

//calculate sum of odd or even numbers

import java.util.Scanner;

class sumOddEven

{

                public static void main(String[]args)

                {

                                int n,sumEven=0,sumOdd=0;

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

                                Scanner r=new Scanner(System.in);

                                n=r.nextInt();

                                for(int i=1;i<=n;i++)

                                {

                                                if(i%2==0)

                                                {

                                                                sumEven=sumEven+i;

                                                }

                                                else

                                                {

                                                                sumOdd=sumOdd+i;

                                                }

                                };

                                System.out.println("Sum of Even is "+sumEven);

                                System.out.println("Sum of Odd is "+sumOdd);

                }

}

//take character input from user

import java.util.Scanner;

class charprint

{

                public static void main(String[]args)

                {

                                char ch;

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

                                Scanner r=new Scanner(System.in);

                                ch=r.next().charAt(0);

                                System.out.print(ch);

                }

}

//check character is vowel or consonant

import java.util.Scanner;

class vowel

{

                public static void main(String[]args)

                {

                                char ch;

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

                                Scanner r=new Scanner(System.in);

                                ch=r.next().charAt(0);

                                if(ch=='a'||ch=='A'||ch=='e'||ch=='E'||ch=='i'||ch=='I'||ch=='o'||ch=='O'||ch=='u'||ch=='U')

                                {

                                                System.out.print("Vowel");

                                }

                                else

                                {

                                                System.out.print("consonent");

                                }

                }

}

//print ASCII value of character.

import java.util.Scanner;

class ascii

{

                public static void main(String []args)

                {

                                char ch;

                                Scanner r=new Scanner(System.in);

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

                                ch=r.next().charAt(0);

                                int a=ch;

                                System.out.print("ASCII value is "+a);

                }

}

//print A to Z alphabets

import java.util.Scanner;

class alpha

{

                public static void main(String[]args)

                {

                                for(char i='A';i<='Z';i++)

                                {

                                               

                                                //char ch=i;

                                                System.out.print(i+" ");

                                }

                }

}

//find greatest number between two numbers.

import java.util.Scanner;

class big

{

                public static void main(String [] args )

                {

                                int num1,num2;

                                System.out.print("Enter two numbers: ");

                                Scanner h=new Scanner(System.in);

                                num1=h.nextInt();

                                num2=h.nextInt();

                                if(num1>num2)

                                {

                                                System.out.print(num1+" is greatest number");

                                }

                                else

                                {

                                                System.out.print(num2+" is greatest number");

                                }

                }

}

//calculate power of a number.

import java.util.Scanner;

class power

{

                public static void main(String []args)

                {

                                Scanner r=new Scanner(System.in);

                                int p,b,result=1;

                                System.out.print("Enter value of base: ");

                                b=r.nextInt();

                                System.out.print("Enter value of power: ");                         

                                p=r.nextInt();

                                for(int i=1;i<=p;i++)

                                {

                                               

                                                result=result*b;

                                }

                                System.out.print("result="+result);

                }

}

// Find greatest number among three numbers.

import java.util.Scanner;

class greatest

{

                public static void main(String[]args)

                {

                                int a,b,c;

                                Scanner r=new Scanner(System.in);

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

                                a=r.nextInt();

                                System.out.println("Enter second number: ");

                                b=r.nextInt();

                                System.out.println("Enter third number: ");

                                c=r.nextInt();

                                if(a>b)

                                {

                                                if(a>c)

                                                {

                                                                System.out.print("greatest number is "+a);

                                                }

                                }

                                else

                                {

                                                if(b>c)

                                                {

                                                                System.out.print("greatest number is "+b);

                                                }

                                                else

                                                {

                                                                System.out.print("greatest number is "+c);

                                                }

                                }

                }

}

//calculate average marks of five subjects.

import java.util.Scanner;

class average

{

                public static void main(String []args)

                {

                                int math,hindi,eng,sci,sst,average;

                                Scanner r=new Scanner(System.in);

                                System.out.print("Enter five subject marks: ");

                                math=r.nextInt();

                                hindi=r.nextInt();

                                eng=r.nextInt();

                                sci=r.nextInt();

                                sst=r.nextInt();

                               

                                average=(math+hindi+eng+sci+sst)/5;

                                System.out.print("average="+average);

                }

}

// find factorial of a number.

import java.util.Scanner;

class fact

{

                public static void main(String []args)

                {

                                int fact=1,num;

                                Scanner r=new Scanner(System.in);

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

                                num=r.nextInt();

                                for(int i=1;i<=num;i++)

                                {

                                                fact=fact*i;

                                }

                                System.out.print("Result="+fact);

                }

}

//count number of digits.

import java.util.Scanner;

class digit

{

                public static void main(String []args)

                {

                                int num,count=0;

                                Scanner r=new Scanner(System.in);

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

                                num=r.nextInt();

                                while(num!=0)

                                {

                                                num=num/10;

                                                count++;

                                }

                                System.out.print("total number of digits is "+count);

                }

}

// print multiplication table.

import java.util.Scanner;

class table

{

                public static void main(String[]args)

                {

                                int n;

                                Scanner r=new Scanner(System.in);

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

                                n=r.nextInt();

                                for(int i=1;i<=10;i++)

                                {

                                                System.out.println(n+"*"+i+"="+n*i);

                                }

                }

}

//tax calculation program.

import java.util.Scanner;

class tax

{

                public static void main(String []args)

                {

                                int salary;

                                Scanner r=new Scanner(System.in);

                                System.out.print("Enter Salary: ");

                                salary=r.nextInt();

                                if(salary<=10000)

                                {

                                                System.out.print("salary="+salary+" No tax");

                                }

                                else if(salary>=10000&&salary<=100000)

                                {

                                                double tax;

                                                tax=salary*0.10;

                                                System.out.print("salary="+tax+" with tax");

                                }

                                else

                                {

                                                double tax;

                                                tax=salary*0.20;

                                                System.out.print("salary="+tax+" with tax");

                                }             

                }

}

// swap of two number.

import java.util.Scanner;

class swap

{

                public static void main(String[]args)

                {

                                int a,b,c;

                                Scanner r=new Scanner(System.in);

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

                                a=r.nextInt();

                                System.out.print("enter second number: ");

                                b=r.nextInt();

                                c=a;

                                a=b;

                                b=c;

                                System.out.print("a="+a+" b="+b);

                }

}

// swap of two numbers without using third variable.

import java.util.Scanner;

class swapwithout

{

                public static void main(String[]args)

                {

                                int a,b,c;

                                Scanner r=new Scanner(System.in);

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

                                a=r.nextInt();

                                System.out.print("enter second number: ");

                                b=r.nextInt();

                                a=a+b;

                                b=a-b;

                                a=a-b;

                                System.out.print("a="+a+" b="+b);

                }

}                                             

// check number is positive or negative......

import java.util.Scanner;

class pos_neg

{

                public static void main(String[]args)

                {

                                int a;

                                Scanner r=new Scanner(System.in);

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

                                a=r.nextInt();

                                if(a>0)

                                {

                                                System.out.print("positive number "+a);

                                }

                                else if(a==0)

                                {

                                                System.out.print("niether negative or positive number "+a);       

                                }

                                else

                                {

                                                System.out.print("negative number "+a);

                                }

                }

}             

// check number is divisible by 5 or Not.....

import java.util.Scanner;

class divi

{

                public static void main(String[]args)

                {

                                int n;

                                Scanner r=new Scanner(System.in);

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

                                n=r.nextInt();

                                if(n%5==0)

                                {

                                                System.out.print("Number is divisible by 5");

                                }

                                else

                                {

                                                System.out.print("Number is not divisible by 5");

                                }

                }

}             

// find factor of a number....

import java.util.Scanner;

class factor

{

                public static void main(String[]args)

                {

                                int n;

                                Scanner r=new Scanner(System.in);

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

                                n=r.nextInt();

                                for(int i=1;i<=n;i++)

                                {

                                                if(n%i==0)

                                                {

                                                                System.out.print(i+" ");

                                                }

                                }

                }

}

// Reverse a Number

import java.util.Scanner;

class reverse

{

                public static void main(String[]args)

                {

                                int n,m,rev=0;

                                Scanner r=new Scanner(System.in);

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

                                n=r.nextInt();

                                while(n!=0)

                                {

                                                m=n%10;

                                                rev=rev*10+m;

                                                n=n/10;

                                }

                                System.out.print("Reverse number is "+rev);

                }

}

// Reverse a Number

import java.util.Scanner;

class sumof

{

                public static void main(String[]args)

                {

                                int n,m,sum=0;

                                Scanner r=new Scanner(System.in);

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

                                n=r.nextInt();

                                while(n!=0)

                                {

                                                m=n%10;

                                                sum=sum+m;

                                                n=n/10;

                                }

                                System.out.print("Sum of digits is "+sum);

                }

}

MCQ

1.     What does the expression double n=10/0; return?

a)     0

b)    Infinity

c)     Invalid Expression

d)    Exception

2.     What is the reason of portability & security of java?

a)     Bytecode

b)    Applet

c)     Exception Handling

d)    Dynamic

3.     Which package contains the System class?

 

 

 

 


e)       

 

What is OOP? Full explanation.

OOP stands for object-oriented programming language, the main purpose of oop is to deal with real world entity using programming language.

OOPS Features:

Class

Object

Inheritance

Polymorphism

Encapsulation

Abstraction

What is class?

Class ids a collection of objects and it doesn’t take any space on memory, class is also called as blueprint/logical entity.

Type of class

Pre-define

User-defined

Object:

Object is an instance of class that executes the class. Once the object is created, it takes up space like other variable in memory.

What is inheritance? Full explanation.

When we construct a new class from existing class in such a way that the new class access all the features & properties of existing class called inheritance.

Note: - in, java extends keyword is used to perform inheritance.

It provides code reusability

Polymorphism

Poly + Morphism

Poly means many and morphism means form

Polymorphism is the Greek word whose meaning is “same object having different behaviour”.

What is encapsulation? full explanation.

Encapsulation is a mechanism through which we can wrapping the data members and member methods of class in a single unit called encapsulation.

Note: -

Declare the class variables as a private.

Declare the class methods as a public.

Data Abstraction

Abstraction is a process of hiding the implementation details from the user, only the highlighted set of services provided to the user.

Advantage:

Security

Enhancement

Abstraction:

Abstract class

Interface

Data Hiding

Outside users can’t access our internal data directly or our internal data should not go out directly, this oops feature is nothing but data hiding.

After Validation and Authentication-----outside user can access internal data!

working in progress.........