0% found this document useful (0 votes)
10 views35 pages

Java Part1

The document outlines the content of a Java course, covering topics such as programming languages, Java's history, advantages, and its development environment (JDK). It details the structure of Java programs, including syntax for variables, data types, operators, and methods. Additionally, it explains key concepts like platform dependency, tokens, and the Java execution process.

Uploaded by

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

Java Part1

The document outlines the content of a Java course, covering topics such as programming languages, Java's history, advantages, and its development environment (JDK). It details the structure of Java programs, including syntax for variables, data types, operators, and methods. Additionally, it explains key concepts like platform dependency, tokens, and the Java execution process.

Uploaded by

vigguviggu33
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Course Content

Part-1
1. Programming Language
2. Paltform
3. Introduction to Java
4. Structure of Java Program
5. Tokens
6. Variables & Datatypes
7. Operators
8. Methods
9. Conditional Statements
10. Looping Statements
11. Dynamic Read

JAVA: It is a high level programming language.


Programming language :Language used to communicate with System(computer) is known as
programming language .
Software : A software is a group programs which is developed to solve a business problem.
Program :Set of instruction given to computer to perform a specific task.
Language :A mode of Communication , to share our ideas ,emotion.
Types of programming Language
Low level language
High level language
Intermediate level language

Low level language:


This are Machine understandable language( it consists of binary code) means set of
instructions given to the computer in the form of 0’s and 1’s
Ex:Binary language( 01110111 )
⚫ It is very difficult for human beings to write the program and to understand the program using
machine level language , but it is easy for computer to understand .
⚫ No need of any translator , because it is easily understandable by machine
Advantage:
1. Program execution is very fast.
2. Machine friendly language.
3. No translator is required.
Disadvantage:
1. Not programmer friendly.
2. Difficult to read and write ,and to modify, debug.
3. Not portable.
High level language:
This are human understandable language, written by using normal English components, like(class , if ,
switch… ) Ex:Java, Python etc.
It is easy for the programmer to write and to understand but it is difficult for the machine so we need
translator.
Translator used to convert high level code into machine level.
Advantage:
1. Programmer friendly
2. Easy to read, write,modify and debug.
3. It is Portable.
Disadvantage:
1. Takes more time to execute when compared with machine language.
2. Translator is required.
Intermediate language
It is a type of language which is not understandable by machine nor by humans.
Ex:Byte Code

File
[Link] file
2. Executable File
Source File:
A file inside which the instruction will be written using high level language, it is the file
created by the programmer and is used for creating an application as well as for generating
executable file
Executable File:
A file which is used for executing the application is know as Executable file
This is a file which is not created by the programmer and it will have instruction written
either in low level language (or) intermediate language.
Platform
Platform is a combination of operating system and processor.
Ex: Windows+i5 intel core

Platform is a place where we can develop a program

Types of programming language based on platform


1. Platform dependent
2. Platform independent

Platform dependent - An application developed in one platform can run only in same platform such
applications are called as platform dependent application.

Linux
Windows Windows
App
input
Mac

Platform independent - An application developed in one platform can run on any platform such
applications are called as platform independent application.

Linux
Windows
App
input
Windows

Mac

History of Java:
⚫ SunMicroSystems a software development company had the vision of developing a programming
language which was completely platform independent.
⚫ In 1990 a team of Researchers led by James Gosling starts research to develop a platform
independent programming language.
⚫ In the year 1995 official version of JAVA was first released to the market .
⚫ First version of JDK was released in year 1996.
⚫ Initially it was named as ‘Oak’,but this name was not so popular .So they renamed it as ‘JAVA’
which basically means coffee bean.
⚫ Current owner of Java:Oracle.
ADVANTAGES OF JAVA :
[Link] is a Simple Programming Language:syntax is easy and we can learn from scratch.
[Link] is a Secured language:because of byte [Link] is difficult to decode the byte code.
[Link] is an Extensible language:we can integrate java program with other programming language like
c,c++,python etc to develop project more effectively.
[Link] is a Platform Independent Language:means you can develop java program in one operating
system and run on any other operating systems like Windows,Linux,Unix,Mac etc.
[Link] is Robust:means strong,it can handle huge applications without crashing it because it can handle
its exception through concept called exceptional handling.
[Link] Supports Oops Principles Such as Encapsulation,Inheritance,Polymorphism,Abstraction.
[Link] has Automatic Garbage Collector which identifies the unused data and automatically removes it
hence memory management is excellent in java.

JDK: Java Development Kit


It is software kit which is provides tools to develop and execute java program.
⚫ Compiler - to check syntax is correct or not in sorce file.
If syntax is wrong it gives error ,programmer has to correct it.
If syntax and code is correct no errors will be given and it will create executable file which
contains byte code(intermediate code).
⚫ JRE- Java Runtime Environment.
It provides the environment to run the java program.
◼ Java Libraries - Contains inbuilt codes.
◼ JVM- Java Virtual Machine
It is important part of JDK and JRE.
It is responsible to develop and execute/run java application.
Complete memory allocation will be done by JVM.
JVM has:
◼ RunTime Data Areas
Contains diferrent memory areas like static area,stack area,heap area and method area
◼ Class Loaders - Loads class into memory
◼ Execution Area

Execution Area has:


⚫ Interpreter: Interpreter will help to convert Byte code into Binary Code.
⚫ JIT compiler:(Just in time): It will helps to increase the performance of conversion and help
interpretor.
⚫ Garbage Collector: removes all the data related to program present in memory after execution of
program to free up the memory space.

Structure of java program:


• Create a file
• Compilation
• Execute:

Step 1: Create a file:


Create a file with file Name along with a extension .java with the help of editors(Notepad,
VScode…etc)
• Inside the file we can have 2 things
o Class
o Interface
o Enum

class:
• It is a keyword in java.
Syntax:
className
{

Step 2: Compilation(Compiler or javac)


After creating source file, give the file for compiler(software) to check the syntax.
• Compiler will check the syntax if there is any mistake then compiler will throw the file to the
developer to debug.
• Else compiler will create a new file called as .class(executable file) file which contains byte
code.
ByteCode:
It is a intermediate language which is not understood by human beings as well systems.

Step 3: Execute
If we want to execute java program we need a software called as JRE(Java Runtime
Environment).

Note: compiler and jre is a software present in JDK(java development kit).

Syntax for Compilation: javac [Link]


Syntax for Execution: java ClassName

main Method

If we want to execute java program then we need main method.


Syntax to create a main method:
public static void main(String[] args){
//Set of Instructions…
}

Printing Statement

If we want to print anything in java then we should make use of printing statements.
Syntax:
[Link](“message”): This print statement will print the data and holds the cursor in same line.
[Link](“message”); This print statement will print the data and shift the cursor to next line.

Tokens
Tokens are nothing but smallest component of any programming language.
Types of tokens:
1. Keywords.
2. Identifiers.
3. Literals

[Link]: keywords are nothing but predefined words which are aware by the compiler.
Ex: class, public, static , void.
Rules:
• Keywords should be specified in lower case.

[Link]:
Identifiers is nothing but a name given to java component.
Ex: class ClassName→ Identifier

With respect to identifiers we have to follow 2 things


1. Rules
2. Convention

[Link]
a. Identifiers cannot start with numbers
b. Only $ and _ are allowed as identifiers.
c. Keywords cannot be used as identifiers.
d. No spaces are allowed.
[Link]:
As a developer we have to follow Naming convention
For ClassName and InterfaceName:
⚫ We should follow UpperCamelCase.
⚫ Every word 1st letter should be specified in upper case is known as UpperCamelCase.

For variableName and methodName:


⚫ We follow lowerCamelCase.
⚫ Start with lower case and then every word 1st letter should be specified in upper case.

Literals:
Literals are nothing but values passed by the programmer in a program is known as literals.

Literals are classified into 4 types:


1. Number Literals – Are represented directly in java it can be Integer and Decimal.
2. Character Literals- are represented within single quotes and should have single character.
3. String literals- are represented within double quotes.
4. Boolean Literals- means true or false.

Comments
1. Additional Information which will not affect the
execution of a program.
// Single Line Comment
/* Multi
Line
Comment */

class Literal
{
public static void main(String [] args)
{
/*
Number Literal
integer literal
*/
[Link](23);
[Link](-4);

//decimal literal
[Link](6.7);

//character literal
[Link]('a');
[Link]('T');
[Link]('1');
[Link]('@');

//String literal
[Link]("Hello World");

//boolean literal
[Link](true);
[Link](false);
}
}

Variables:

Variable is a named block of memory/ container which is used to store the data.

Variable Declaration:
Syntax: datatype variableName/Identifier;
Ex: int a;

Datatype: It specifies which type of container has to be created.

Variable Initialization:
variableName/Identifier = value;
Ex: a = 10;

Variable Declaration and Variable Initialization:


Syntax:
datatype variableName/Identifier = value;
Ex:int a = 10;

Advantages:
• Variable has a name.
1. Using name we can store the data
2. We can access/fetch the data
3. We can re-initialize the data
Variable utilization
Syntax: [Link](variableName/Identifier);

Types of Datatypes:
Primitive datatype: are of 8 types
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter

Non primitive Dataype


-String &
-In java every classname is a Non-primitive datatype.

Operators
Operators are pre-defined Symbols,which is used to perform a specific task on the operands.

Operand: The values which user passes is known as Operand.

Characteristics of Operator :
1. Operator will return data.

Types Of Operators:

[Link] on Operands:- Unary , Binary , Ternary Operator.

i) Unary Operator: An Operator which requires only one operand to perform the task is known as
Unary Operator.
Ex: Logical not , new , Typecast Operator, Increment & Decrement Operator etc……

ii) Binary Operator: An Operator which requires 2 operands to perform the task is known as Binary
Operator.
Ex: Arithmetic Op, Relational Op , Logical Op etc……

iii) Ternary Operator: An Operator which requires 3 Operands to perform the task is known as
Ternary Operator.
Ex: Conditional Operator.

2. Based on Task:-

i) Arithmetic Operator: It is a Binary operator which are used to perform arithmetic operators(+,/,-
,*,%).
-Plus Operator(+):- In java plus operator will have 2 behaviors, One is Concatenation & Another one is
Normal Addition.
-concatenation oprt(+) : Is used to join a String value with any other data.
-Between a string and any other type if you use + oprt it will join the string and given value creating a
new String.
Ex : "hello"+"world“
“hello"+10

-Division Operator: Whenever we are using division operator(/),the compiler will give the Quotient as
Output.
-Modulus Operator: Whenever we are using Modulus operator(%),the compiler will give the Reminder
as Output.

Relational Operator:
-It is used to Compare two values.(==,!=,>,<,>=,<=)
-It is Binary Operator.
-Return Type of relational Operator is Always Boolean.
Note: Except For == And != Operator boolean datatypes cannot be used for other relational operator.

class RelationalOperator
{
public static void main(String [] args)
{
//Assignment operator
int a=10;
int b=20;
char c1='a';//97
char c2='b';//98

//Relational operator
[Link](a==b);//f
[Link](a==a);//t
[Link](c1==c2);//f
[Link](2==4);//f
[Link]("---------------");
[Link](a!=b);//t
[Link](a!=a);//f
[Link](c1!=97);//f
[Link]("---------------");
[Link](a>b);//f
[Link](a>a);//f
[Link](c1>c2);//t
[Link]("-----------------");
[Link](a>=b);//f
[Link](b>=a);//t
[Link](a>=a);//t
[Link]("---------------------");
[Link](b<b);//f
[Link](b<a);//f
[Link](c1<c2);//t
[Link]("-------------------");
[Link](b<=b);//t
[Link](b<=a);//f
[Link](c1<=c2);//t
}
}

Logical Operators: (&& , || , !):


-It is a binary operator.
-The return type of logical operator is always a boolean type.
-Logical Operator are used to merge more than one condition.
-In java we have the following types of logical operators:
i) Logical And(&&)
ii) Logical Or(||)
iii) Logical Not(!)

i)Logical And(&&):
-It is a Binary operator.
-The And Operator are used whenever it is mandatory to satisfy all the conditions to be performed.
-In Logical And Operator if the First Condition is returning us false, we can directly say result will be
false itself.
-If the first condition is false then compiler will never check second condition.

CONDITION1 CONDITION 2 RESULT

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

ii)Logical OR(||):
-It is a Binary operator.
-The OR Operator are used whenever we can perform a task ,even if any one of the condition is
satisfied. It returns true itself.

CONDITION1 CONDITION 2 RESULT

TRUE TRUE TRUE

TRUE FALSE TRUE

FALSE TRUE TRUE

FALSE FALSE FALSE

iii)Logical Not(!):
-It is a Unary operator.
-The return type is boolean.
-It is used to negate the literals passed to it.
-Whenever we are working with Not Operator & if we are passing an expression to it, we must pass that
expression within parenthesis().

Compound Assignment Operator:


-Assignment Op: It is used to update the value to the variable.
-Compound Assignment Operator: (+= , -= , *= , /= , %=)
-It is a Binary Operator.
-A compound Assignment op is a Combination of Arithmetic op Along with Assignment Op.
-We use Compound assignment op whenever we need to update a Variable by Performing Arithmetic
Op in the RHS.

Unary Operator

1. Increment Operator.
- The Increment Operator is Represented by (++) .
- They can be used only along with Variables which are the primitive types…. Except the Boolean.
Types:
A) Pre-increment- It will increase the value by one and then assign the value to expression.
B) Post-increment-It will assign the current value to expression first and then it will increase the value
by one.

[Link] Operator
-Decrement operator is Represented by (--).
-They can be used only along with Variables which are the primitive types…. Except the Boolean.
Types:
C) Pre-decrement- It will decrease the value by one and then assign the value to expression.
D) Post-decrement-It will assign the current value to expression first and then it will decrease the value
by one.

Questions on Increment and Decrement operator:

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i = 11;

i = i++ + ++i;

[Link](i);
}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int a=11, b=22, c;

c = a + b + a++ + b++ + ++a + ++b;

[Link]("a="+a);
[Link]("b="+b);
[Link]("c="+c);
}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=0;

i = i++ - --i + ++i - i--;

[Link](i);

}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=1, j=2, k=3;

int m = i-- - j-- - k--;

[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
[Link]("m="+m);
}
}
public class IncrementDecrementQuiz
{
public static void main(String[] args)
{
int a=1, b=2;

[Link](--b - ++a + ++b - --a);


}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int i=19, j=29, k;

k = i-- - i++ + --j - ++j + --i - j-- + ++i - j++;

[Link]("i="+i);
[Link]("j="+j);
[Link]("k="+k);
}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int m = 0, n = 0;

int p = --m * --n * n-- * m--;

[Link](p);
}
}

public class IncrementDecrementQuiz


{
public static void main(String[] args)
{
int x = 001, y=010, z=100;

int i = --x + y++ - z-- - --z + ++y - --x + y-- - --x;

[Link]("x="+x);
[Link]("y="+y);
[Link]("z="+z);
[Link]("i="+i);
}
}
public class JavaIncrementDecrementQuiz
{
public static void main(String[] args)
{
int ch = 'A';

[Link](ch++);
}
}

public class JavaIncrementDecrementQuiz


{
public static void main(String[] args)
{
double d = 1.5, D = 2.5;

[Link](d++ + ++D);
}
}

iv) Conditional Operator:


-It is a Ternary Operator.
- It is used to make a Decisions in java.

Syntax: Op1 ? Op2 : Op3 ;


Op1: It Should be a Condition Or Boolean Literal
Op2 And Op3: value /variable/ exp.

-In Conditional Operator ,the first operand must be of type boolean i.e we can directly write Boolean
literal or We can have an Expression which returns Boolean.
-The Return Type of Conditional Op is always depends on the datatype of Op2 & Op3.

Class Ternary{
Public static void main(String [] args){
//ternary
[Link](10>20?"Hii":"Hello");
[Link](10<20?10:20);

int num=6;
[Link](num%2==0?"even":"odd");
}
}
Type Casting: The process of Converting one type of data into another type is known as Typecasting
Operator.
In java we have following classification.
i) Primitive Typecasting-------( Widening and Narrowing) .
ii) Non-Primitive Typecasting---( Upcasting and Downcasting).

i) Primitive Type-Casting: The Process of Converting One Primitive type to Another Primitive type is
known as Primitive typecasting.
In java we have 2 types of primitive Typecasting.
[Link]
[Link]

[Link]: The Process of Converting Smaller range datatype into larger range datatype is known as
widening.
-In Widening there is no loss of data.
-Hence the Compiler will do it implicitly(Internally).
-Can be done explicitly also.
-It is Also referred as Auto-widening.

2. Narrowing: The Process of Converting Larger range datatype into smaller range datatype is known
as narrrowing.
-In Narrowing there is a loss of data.
-Hence the Compiler will not do it implicitly, It has to be done Explicitly by the Programmer, Using
TypeCast Operator.

TypeCast Operator:
-It is a Unary Operator.
-It is Used to convert one type of data into another type of data.
-Syntax: (Datatype to be Converted to)Value/exp/variable.

class TypeCast{
public static void main(String [] args){
int a=10;
double b=a;//implicit widening
double b1=(double)a;//explicit widening

[Link](a);//10
[Link](b);//10.0

double c=5.3;
int d=(int)c; //narrowing(exp)
[Link](c);//5.3
[Link](d);//5

char c1='a';//2
double a1=c1; //8
[Link](c1);//a
[Link](a1);//97.0

int a2=112;
char c2=(char)a2;
[Link](a2);//112
[Link](c2);//p
}
}

METHODS / FUNCTIONS
-Method is a set of instructions or block of codes which is used to perform a specific task.
-Method gets executed only when they are called.

Syntax to create a method in java:


[modifiers] Returntype Identifier (formal arguments)
{
// java Stmts;
}

Some Imp Method Terminologies:

[Link] Signature: A Method name followed by formal arguments is known as Method Signature.
[Link] Declaration: The Modifiers & Return type followed by Method Signature is known as
Method Declaration.
[Link] Definition: A Method declaration followed by a method block or body is known as Method
Definition.

Modifier:
-These are the Keywords
-They are responsible to change the behaviour of the members of the class.
Types of Modifiers:
[Link] Modifiers: public , private, protected ,default.
[Link]-Access Modifiers: static, abstract, final …etc……

Return Type: It is a datatype which specifies (tells) what type of data is given back to the caller of the
method, once the execution is completed.
Types:
i) Primitive type ( byte,short,int,long,float,double,char,boolean).
ii) Non Primitive type (Any ClassName,String).
iii) void

Formal Argument: The variable declared /created in the method declaration statement is called as
formal arguments.

Characteristics of Method
[Link] gets executed only when it is called, we can call method with the help of method signature.
Syntax: Methodname();
[Link] can execute any number of times.
[Link] will Increase the code Reuse-ability.
[Link] a method returns something, store it Or Print it.

What Happens when a method is called ?


-Execution of current method is paused.
-Control is transferred from calling method or caller to called method.
-Execution of called method starts from beginning.
-Once the execution is completed, control returns to the caller or calling method.
-Execution of caller resumes.

public class Method {

//create a method to print GoodMorning


public static void example()//called method
{
[Link]("example method started");
[Link]("Good Morning");
[Link]("example method ended");
}
public static void main(String [] args)//calling method
{
[Link]("Main method started");
//call the method
example();//method call statement
example();
[Link]("Main method ended");

}}

Types Of Methods
i) Based on Arguments:
a.) No-Argument Method
b.) Parameterized Method

No-Argument Method:
A method which doesn’t have a formal arguments declared in it is known as No-argument method.
Or
A method declared without formal arguments is known as No-argument method.

Syntax to call No-argument Method:


Methodname();

Parameterized Method:
A method which is having formal arguments is known as Parameterized method.
Syntax to create parameterized Method:
Modifier returntype Methodname (datatype v1, datatype v2..)
{
//statements;
}
Syntax to call parameterized Method:
Methodname (actual arguments);

Actual Arguments: The data / value which is passed in the method call statement is known as actual
arguments.

Note:
⚫ Actual arguments are in method calling statement.
⚫ Formal arguments are in method definition.
⚫ If the return type is void it will not return anything to the caller.
⚫ A method can return the data to the caller ,if the returntype of the method is anything other than
void.

Rules to call a method:


[Link] number of formal arguments & actual arguments should be same.
[Link] type of corresponding actual and formal argument should be same, else compiler tries for
widening , if it is not possible then it throws CTE.

Return Statement:
-It is a keyword.
-Return is a control transfer statement , it stops the execution of current method and transfer the control
back to the caller.

Rules:
⚫ return statement is mandatory if the return type of the method is anything other than void.
⚫ If the return type is void , return statement is optional. ,but we should use return statement without
value.
⚫ return statement in java can return only one value.
⚫ return statement should be the last statement of the block.

//creates methods to perform sub(),mul(),div(),mod()--in all 4 types


public class Method12 {

//without f.a and rt as void

// public static void add()//called method


// {
// [Link]("add started");
// int a=23,b=12;
// [Link](a+b);
// [Link]("add ended");
// }

//without f.a and rt other than void (int)


/*
* return statement is mandatory.
* Syntax: return value/variable/expression;
*
* this statement has to be wriiten in last line of the method
* datatype of value/variable/expression should be same as datatype of return type you have specified
*/
// public static int add1(){
// int a=12,b=16;
// return a+b;//28
// }

//with formal argument and rt as void


/*
* Rules of formal argument & actual arguments
* Number should be same
* Datatype should be same
* Order of datatype should be same
*/

// public static void add2(int a,double b)//a=4,b=5


// {
// [Link](a+b);//4+5
// }

//with f.a and rt as int

public static int add3(int a,int b,int c){


return a+b+c;
}
public static void main(String[] args) //caller method
{
[Link]("Main started");
//add();//method call statement
// [Link](add1());

// add2(4,5);//actual argument---value that is passes in method call statement


// add2(7,8.9);

[Link](add3(10, 20, 15));


[Link]("Main ended");
}
}

1.
package com;
class Demo {
/* Method without Arguments and without return statement */
void display()
{
[Link]("Hello World!");
}
public static void main(String[] args) {
[Link]("start");
Demo d = new Demo();
[Link](); // calling or invoking the method
[Link]("end");
}
}

o/p:
start
Hello World!
end

2.
package com;
class Addition
{
/* Method with Arguments and without return statement */
void add(int a, int b)
{
[Link]("Sum of "+a+" & "+b+" is "+ (a+b) );
/* int sum = a+b;
[Link]("Sum of "+a+" & "+b+" is "+sum);
[Link](a+b); */
}
public static void main(String[] args) {
Addition obj = new Addition();
[Link](10, 20);
[Link](6, 3);
[Link](123, 456);
}
}

o/p:
Sum of 10 & 20 is 30
Sum of 6 & 3 is 9
Sum of 123 & 456 is 579

3.
package com;
class Test
{
/* Method without Arguments and with return statement */
int display()
{
return 10;
}
public static void main(String[] args) {
[Link]("start");
Test t = new Test();
int result = [Link]();
[Link](result);
[Link]([Link]());
[Link]("end");
}
}

o/p:
start
10
10
End

4.
package com;
class Example
{
/* Method with Arguments and with return statement */
int findSquare(int n)
{
return n*n;
}
public static void main(String[] args) {
Example e = new Example();
int res = [Link](5);
[Link](res);
[Link]([Link](4));
}
}

o/p:
25
16
5a.
package com;
class Solution {
/* Method without Arguments and without return statement */
void m1() {
[Link]("Learning Methods");
}
/* Method with Arguments and without return statement */
void m2(String name, int age) {
[Link]("Name: "+name+" Age:"+age);
}
/* Method without Arguments and without return statement */
String m3() {
return "Jspiders";
}
/* Method with Arguments and with return statement */
int m4(int a, int b) {
return a+b;
}
}

5b.
package com;
public class MainClass {
public static void main(String[] args) {
Solution s = new Solution();
s.m1();
[Link]("------------");
s.m2("john", 25);
[Link]("------------");
String company = s.m3();
[Link](company);
[Link](s.m3());
[Link]("------------");
int sum = s.m4(4, 5);
[Link](sum);
[Link](s.m4(12, 78));
}
}

o/p:
Learning Methods
------------
Name: john Age:25
------------
Jspiders
Jspiders
------------
9
90
Decision Statements/Conditional Statements

These are used to Decide whether block of Instructions need to be Executed or not.
In java we have following decision statements:
1.)Simple if
2.)if else
3.) else if ladder
4.) switch

1.)Simple if: whenever we have only one condition then we will use simple if statement.
Syntax:
if(condition/boolean)
{
// java stmts;
}

-if is a Keyword.
-In the Simple if statement the control will checks for the condition, if the condition is true , it will enter
into if block and execute all the statements and then continue with remaining execution.
-If the condition is false then control will not enter into if block , it will skip if block and then it will
continue with the remaining execution.

[Link] else : Whenever we have 2 options we will use (if else statement).
Syntax:
if(condition/boolean)
{
// java stmts;
}
else
{
// java stmts;
}

[Link] if ladder: whenever we have more than 2 option and we need to execute any one of it.. then we
use else if ladder statement.
Syntax:
if(condition/boolean)
{
// java stmts;
}
else if(condition/boolean)
{
// java stmts;
}
.
.
[ else
{
// java stmts;
}]

Note: It is not mandatory to have else block inside else if ladder.


Inside else if ladder we can execute only one block even if multiple blocks conditions are true , First
true block will get executed.
4)switch:
Syntax:
switch(value/exp)
{
case value/exp:
{
// java stmts;
}
case value/exp:
{
// java stmts;
}
default:
{
// java stmts;
}
}

Note: For switch we can pass value or expression of datatypes -byte,short,char,int,String.


-The following datatypes cannot be passed (long ,float,double,boolean).
-Variables are allowed for switch but not for cases, but values allowed
-Inside switch we can have any number of cases.
-The switch statement uses the predefined equality operator to compare the values of switch with the
value present in each case.
-If anyone of the case is validated to true then the stmt of that case will executed and also rest of the
cases will also be executed without even comparing the values of cases along with default statements
also.
-The default statement gets executed only when none of the case are validated to true.

Drawback of switch:
Switch statement not just execute the validated case , it also executes unwanted cases too.
Note: In order to resolve this drawback we must use break keyword.

Break:
-It is a keyword.
-It is a control transfer statement.
-It stops the execution of program and transfer the control outside the block.
-It can be used only inside switch or loop statements.

Break inside Switch:


-Whenever a break statement is executed , the execution of switch statement will be stopped and the
control comes outside the switch statement.

1.
class SimpleIfDemo
{
public static void main(String[] args)
{
[Link]("start");
int n = 5;
if(n<=10) // if(5<=10) -> if(true)
{
[Link](n+" is lesser than or equal to 10");
}
[Link]("end");
}
}
o/p:
start
5 is lesser than or equal to 10
end

2.
class IfElseDemo
{
public static void main(String[] args)
{
int a = 50;
int b = 20;
if(a<=b)
{
[Link](a+" is lesser than or equal to "+b);
}
else
{
[Link](a+" is greater than "+b);
}
[Link]("--------------------------");
if(true)
{
[Link]("Hai Dinga");
}
else
{
[Link]("Bye Dinga");
}
[Link]("--------------------------");
if(false)
{
[Link]("Hai Dinga");
}
else
{
[Link]("Bye Dinga");
}
}
}
o/p:
50 is greater than 20
--------------------------
Hai Dinga
--------------------------
Bye Dinga

3.
class IfElseIfDemo
{
public static void main(String[] args)
{
int a = 10;
int b = 10;
if(a<b) // if(10<10) -> if(false)
{
[Link](a+" is lesser than "+b);
}
else if(a>b) // if(10>10) -> if(false)
{
[Link](a+" is greater than "+b);
}
else
{
[Link](a+" is equal to "+b);
}
}}
o/p:
10 is equal to 10

4.
class MarksValidation
{
public static void main(String[] args)
{
int marks = -7;
if(marks>=81 && marks<=100)
{
[Link]("Distinction");
}
else if(marks>=35 && marks<=80)
{
[Link]("First Class");
}
else if(marks>=0 && marks<=34)
{
[Link]("Fail, Study Well!! :(");
}
else
{
[Link]("Invalid Marks");
}
}
}
o/p:
Invalid Marks

3.
class AssignmentPrograms
{
public static void main(String[] args)
{
int num = -10;
if(num>0)
{
[Link](num+" is a Positive Number");
}
else
{
[Link](num+" is a Negative Number");
}
[Link]("-------------");
int n = 215;
if(n%2 == 0) // if(215%2 == 0) -> 1 == 0
{
[Link](n+" is a Even Number");
}
else
{
[Link](n+" is a Odd Number");
}
[Link]("-------------");
int a = 20;
int b = 20;
[Link]("a:"+a+" b:"+b);
if(a>b)
{
[Link]("a is Largest");
}
else if(a<b) // b>a
{
[Link]("b is Largest");
}
else
{
[Link]("a and b are both equal");
}
}
}
o/p:
-10 is a Negative Number
-------------
215 is a Odd Number
-------------
a:20 b:20
a and b are both equal

1.
class SwitchDemo
{
public static void main(String[] args)
{
int choice = 3;
switch(choice)
{
case 1: [Link]("In Case-1");
break;
case 2: [Link]("In Case-2");
break;
case 3: [Link]("In Case-3");
break;
default : [Link]("Invalid");
}
}
}
o/p:
In Case-3

2.
class GradeValidation
{
public static void main(String[] args)
{
char grade = 'C';
switch(grade)
{
case 'A': [Link]("Excellent -> Distinction");
break;
case 'B': [Link]("Good -> First Class");
break;
case 'C': [Link]("Bad -> Fail :(");
break;
default: [Link]("Invalid Grade");
}
}
}
o/p:
Bad -> Fail :(

Dynamic Read
Java application fetching the data from end user when the application is under execution is known as
Dynamic read.
How to take input from User? We must follow 3 steps:
1. Import Scanner class :must be written above class.
Syntax: import [Link];
2. Create Object of Scanner class.
Syntax: Scanner s=new Scanner([Link]);
3. Request the data from user by calling respective methods of Scanner class.
Ex:To accept integer data we have to [Link]() method of Scanner class.

Datatype Method of Scanner class


byte nextByte();
short nextShort();
int nextInt();
long nextLong();
float nextFloat();
double nextDouble();
char next().charAt(0);
String next();
boolean nextBoolean();

import [Link];//step 1
public class DynamicRead {
public static void main(String[] args) {
//step 2
Scanner s=new Scanner([Link]);

[Link]("Enter a int value");


//step 3
int a=[Link]();

[Link]("Enter b int value");


int b= [Link]();

[Link]("a value is:"+a);


[Link]("b value is:"+b);
[Link]("Addition of a and b is:"+(a+b));
[Link]("----------------------------");

[Link]("Enter byte value");


byte c=[Link]();
[Link]("c value is:"+c);
}
}

4. Nested If
- Nested If is a decision-making statement wherein one if condition is present inside another if condition.

1.
class NestedIf
{
public static void main(String[] args)
{
int a = 70;
if(a<=10) // false outer if
{
[Link]("Inside Outer If");
if(a==5) // inner if
{
[Link]("a is equal to 5");
}
else // inner else
{
[Link]("a is not equal to 5");
}
}
else // outer else
{
[Link]("a greater than 10");
}
}
}
o/p:
a greater than 10

2.
class LoginValidation
{
public static void main(String[] args)
{
String id = "adminxyz";
int password = 123;
if(id == "admin")
{
[Link]("User Id is Valid");
if(password == 123)
{
[Link]("Password is Valid");
[Link]("Login Successful :)");
}
else
{
[Link]("Password is Invalid");
[Link]("Login Unsuccessful :(");
}
}
else
{
[Link]("User Id is Invalid");
[Link]("Login Unsuccessful :(");
}
}
}
o/p:
User Id is Invalid
Login Unsuccessful :(
3.
class LargestOfThreeNumbers
{
public static void main(String[] args)
{
int a = 20;
int b = 150;
int c = 10;
[Link]("a:"+a+" b:"+b+" c:"+c);
if(a>b)
{
if(a>c) {
[Link]("a is Largest");
}
else {
[Link]("c is Largest");
}
}
else if(b>c)
{
[Link]("b is Largest");
}
else
{
[Link]("c is Largest");
}
[Link]("-------------------");
if(a>b && a>c)
{
[Link]("a is Largest");
}
else if(b>a && b>c)
{
[Link]("b is Largest");
}
else
{
[Link]("c is Largest");
}
}
}

o/p:
a:20 b:150 c:10
b is Largest
-------------------
b is Largest

5.
class MatrimonyPortal
{
public static void main(String[] args)
{
char gender = 'M';
int age = 19;
if(gender == 'M')
{
[Link]("Gender is Male");
if(age>=21)
{
[Link]("Yes, You can get Married");
}
else
{
[Link]("Have Patience :)");
}
}
else if(gender == 'F')
{
[Link]("Gender is Female");
if(age>=18)
{
[Link]("Yes, You can get Married");
}
else
{
[Link]("Have Patience :)");
}
}
else
{
[Link]("Invalid"); }
}
}
}
o/p
Gender is Male
Have Patience :)

Looping Statements
It is used to execute an Instruction or set of Instructions Multiple times.
Or
Looping Statement will help programmer to execute the statements again & again.

Types Of Looping Statements


[Link] loop
[Link]-while loop
[Link] loop

Note: Every loop statement we design must and should have three important segments.
i) Initialization
ii) Condition
iii) Updation
[Link] loop: It is a keyword used as loop statement.
Syntax: while(condition)
{
// java stmts;
}
- we go for while loop whenever we need to execute a statement/ group of statement repeatedly based
on a condition.
-we go for while loop whenever we don’t know number of iterations.

Arrays
Array is continuous block of memory which is logically broken into sub blocks and used to store
multiple values.

Characteristic of an Array:
1. Array is a container to store a group of Data/Elements.
2. Array is of Fixed Size.
3. Array can store only Homogeneous Data.
4. Array is of Indexed Based and index position starts from 0.

Array reference variable: A variable which is created to store array reference/address of an array is
called as array reference variable.

How to create an array:

Array declaration - datatype [] ref-variable;


Ex: int [] a;
Array creation - ref-variable=new datatype[size];
Ex: a=new int [4];

Both Array declaration and Array creation together:


Syntax: datatype [] ref-variable=new datatype[size];
Ex: double [] b=new double[5];

Store value in array:


Syntax: ref-variable[index]=value;
Ex: int [] a =new int [3];
a[0]=10;
a[1]=20;
a[2]=30;

Access value from array:


Syntax : [Link](ref-variable[index]);
Ex:
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
index 0 1 2 3 4 5 6 7 8

Array Length = 9

ArrayIndexOutOfBoundsException: Whenever we try to access index position out of limit of array


created we get ArrayIndexOutOfBoundsException.
Note: index=size-1;

Array Literal : datatype [] ref-variable={value1,value2,…..};


Ex: int [] c={1,2,3,4,5};

Length variable: used to get the size of given array.


Syntax: [Link];
Ex: int [] a =new int [3];
[Link]([Link]);//output=3

package com;
public class Demo {
public static void main(String[] args) {
/* Array Declaration */
int[] a;
/* Array Creation */
a = new int[3];
/* Printing Array Elements */
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link]("-------");
/* Array Initialization */
a[0] = 10;
a[1] = 20;
a[2] = 40;
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
[Link]("==============");
// Array Declaration and Creation
double[] x = new double[4];
[Link](x[0]);
[Link](x[1]);
[Link](x[2]);
[Link](x[3]);
[Link]("-------");
x[0] = 1.2;
x[1] = 3.4;
x[2] = 5.6;
x[3] = 7.8;
[Link](x[0]);
[Link](x[1]);
[Link](x[2]);
[Link](x[3]);
[Link]("Length: "+[Link]);
}

You might also like