0% found this document useful (0 votes)
2 views70 pages

Java Fundamentals

This document provides an overview of Java fundamentals, including its evolution, features, and applications. It discusses key concepts such as object-oriented programming, Java's architecture, and the Java Virtual Machine (JVM). Additionally, it outlines the structure of Java programs, data types, variables, and the differences between Java and other programming languages like C and C++.

Uploaded by

Mmahek Dudhediya
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)
2 views70 pages

Java Fundamentals

This document provides an overview of Java fundamentals, including its evolution, features, and applications. It discusses key concepts such as object-oriented programming, Java's architecture, and the Java Virtual Machine (JVM). Additionally, it outlines the structure of Java programs, data types, variables, and the differences between Java and other programming languages like C and C++.

Uploaded by

Mmahek Dudhediya
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

Unit V

Java Fundamentals
Contents
❖ Review of Object oriented concepts
❖ Evolution of Java
❖ Comparison of Java with other programming languages Java features, Java and World Wide Web, Java
Run Time Environment. JVM architecture.
❖ Overview of Java Language
❖ Simple Java Program
❖ Java Program Structure.
❖ Installing and Configuring Java.
❖ Java Tokens, Java Statements, Constants, variables, data types.
❖ Declaration of variables, Giving values to variables, Scope of variables
❖ Arrays
❖ Symbolic constants
❖ Typecasting, Getting values of variables, Standard default values
❖ Operators, Expressions, Type conversion in expressions, Operator precedence and associatively
❖ Mathematical functions
❖ Control statements- Decision making & looping.
Department of E & TC
Objectives
Discuss the concept of classes, objects implementation using Java.

Outcome
Apply fundamental Java programming constructs to effectively find
solutions for given computational problems.

Department of E & TC
Java Evolution
The Creation of Java
• Java was conceived by James Gosling, Patrick Naughton, Chris Warth,
Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991.
• It took 18 months to develop the first working version. This language was
initially called “Oak” but it existed so was renamed “Java” in 1995.
• Java Slogan: Java is Everywhere

Department of E & TC
History of Java
• James Gosling initiated the Java language project in June 1991 for use in one of
his many set -top box projects. The language, initially called Oak after an oak tree
that stood outside Gosling's office, also went by the name Green and ended up later
being renamed as Java, from a list of random words.
• Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run- times on popular
platforms.
• On 13 November 2006, Sun released much of Java as free and open
source software under the terms of the GNU General Public License (GPL).
• On 8 May 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
• The primary motivation was the need for a platform-independent (that is,
architecture neutral) language that could be used to create software to be
embedded in various consumer electronic devices, such as microwave ovens and
remote controls.

Department of E & TC
Job Opportunities
There are various sector where you can go.

• Java web developer

• Java web master

• Web software development

• Android developer.

• Automation tester with selenium

Department of E & TC
Java Applications

• Mobile Applications.

• Desktop GUI Applications.

• Web-based Applications.

• Gaming Applications.

• Big Data technologies.

• Business Applications.

• App designs

• Web servers.

Department of E & TC
Overview of Java Language
Features of Java Language: Java is,
• Object Oriented: In Java, everything is
an Object. Java can be easily extended since it
is based on the Object model.
• Platform independent: Unlike many other programming
languages including C and C++, when Java
is compiled, it is not compiled
into platform specific machine, rather into platform independent
byte code. This byte code is distributed over the web and interpreted by
Java virtual Machine (JVM) on whichever platform it is being run.

Simple: Java is designed to be easy to learn. If you understand the basic


concept of OOP, Java would be easy to master.
• Secure: With Java's secure feature, it enables to develop virus-free,
tamper-free systems. Authentication techniques are based on public-key
encryption.
• Architectural-neutral: Java compiler generates an architecture-neutral
object file format, which makes the compiled code to be executable on
many processors, with the presence of Java runtime system.
Department of E & TC cont………..
Overview of Java Language
Features of Java Language: Java is,
• Portable: Being architectural-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary which is a POSIX subset.

• Robust: Java makes an effort to eliminate error prone situations by emphasizing


mainly on compile time error checking and runtime checking.

• Multithreaded: With Java's multithreaded feature, it is possible to write


programs that can do many tasks simultaneously. This design feature allows
developers to construct smoothly running interactive applications.

• Interpreted: Java byte code is translated on the fly to native machine


instructions and is not stored anywhere. The development process is more rapid
and analytical since the linking is an incremental and lightweight process.
• High Performance: With the use of Just-In-Time compilers, Java enables high
performance.

• Distributed: Java is designed for the distributed environment of the internet.

• Dynamic: Java is considered to be more dynamic than C or C++ since it is


designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
Department of E & TC
Step by step Execution of Java Program:

• Whenever, a program is written in JAVA, the javac compiles it.


• The result of the JAVA compiler is the .class file or the bytecode and not the machine
native code (unlike C compiler).
• The bytecode generated is a non-executable code and needs an interpreter to execute on a
machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM.
• And finally program runs to give the desired output.

Compiled by
Java Source Interpreter
JavaC
code (JDK)
compiler

Department of E & TC
JVM architecture
❖ Java Virtual Machine (JVM) is a engine that provides runtime environment to drive
the Java Code or applications.
❖ It converts Java bytecode into machines language.
❖ JVM is a part of Java Run Environment (JRE). In other programming languages, the
compiler produces machine code for a particular system.
❖ However, Java compiler produces code for a Virtual Machine known as Java Virtual
Machine.

Load
Link -- Verify,
Prepare
Resolve
Initialise

Department of E & TC
Department of E & TC
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major functions viz. Loading,
Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures and the code for methods.
3) Heap
All the objects when created are stored in the heap. Example arrays. This memory is common and shared
across multiple threads.
4) Java Stacks
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack,
created simultaneously as the thread is created. A new frame is created whenever a method is invoked, and it
is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing. In Java,
each thread has its separate PC register.
6) Native Method Stacks
Native method stacks hold the instruction of native code depends on the native library. It is written in
another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution engine never
carries any information about the tested product.
8) Native Method interface
The Native Method Interface is a programming framework. It allows Java code which is running in a JVM
to call by libraries and native applications.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.
Department of E & TC
JAVA VS C
• Java does not include the C unique statement keywords sizeof and
typedef.
• Java does not contain the data types struct and union.

• Java does not define the type modifiers keywords auto, extern, register,
signed, and unsigned.
• Java does not support an explicit pointer type.

• Java does not have a preprocessor and therefore and therefore we cannot use
#define, #include, and #ifdef statements.

• Java requires that the function with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
• Java adds new operators such as instanceof and >>> (right shift operator).
• Java adds labeled break and continue statements.
• Java adds many features required for object oriented programming.
Department of E & TC
JAVA VS C++:
• Java does not support operator overloading.
• Java does not have template classes as in c++.

• Java does not support multiple inheritance of classes. This is accomplished


using a new feature called “interface”.

• Java does not support global variables. Every variable and method is declared
within the class and forms part of that class.
• Java does not use pointers.
• Java has replaced the destructor function with a finalize ()
function.
• There is no header file in java.

Department of E & TC
Java Vs C Vs C++ in terms of execution
• In case of C or C++ (language that are not platform independent), the compiler
generates an .exe file which is OS dependent.
• When we try to run this .exe file on another OS it does not run, since it is OS
dependent and hence is not compatible with the other OS.
• In Java, the main point here is that the JVM depends on the operating system – so if
you are running Mac OS X you will have a different JVM than if you are running
Windows or some other operating system.

Department of E & TC
Overview of Java Language
• JAVA Program Structure:

Department of E & TC
JAVA TOKENS:

• Java is basically collection of classes. A class is defined by a set of


declaration statements and methods containing executable statement.

• Java language includes five types of tokens. They are:


1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators

Department of E & TC
1. Java Keywords
The following list shows the reserved words in Java. These reserved words may not
be used as constant or variable or any other identifier names.

Department of E & TC 10
2. Identifiers
• Identifiers are programmer defined tokens.

• They are used in class name, methods, variables,


objects, labels, packages and interfaces.

• Java identifiers follow following rules:

❖ They can have alphabets, digits, and the underscore and dollar sign characters.

❖ They must not begin with digit.

❖ Uppercase and lowercase letters are distinct.

❖ They can be of any length.

Department of E & TC
3. Literals:
• Literals in java are a sequence of characters (digits, letters, and other characters) that
represents constant values stored in variables.

For example :

int rollno = 101;

• Java language specifies five major types of literals. They are:


❖ Integer literals.
❖ Floating point literals.
❖ Character literals.
❖ String literals.
❖ Boolean literals.

Department of E & TC
4. Operators:
• An operator is a symbol that takes one or more arguments and operates on them
to produce a result.
• Operators
❖ Arithmetic (+, -,*, /).
❖ Relational (<, <=, >, >=, ==, !=).
❖ Logical (&&, ||, !).
❖ Assignment (=).
❖ Increment and decrement (++, --).
❖ Conditional (?:).
❖ Bitwise (&, |, ^, ~, <<, >>, >>>).
❖ Special (instanceof, dot )

Department of E & TC
5. Separators:
• Separators are symbols used to indicate where groups of code are divided and

arranged.

• They basically define the shape and function of our code. (), {}, [], ;, . , , etc are

the separators in java .

Department of E & TC
Symbol Name Usage

Used to enclose parameters in method definition and


invocation; also used for defining precedence in
() Parentheses
expressions, containing expressions for flow control, and
surrounding cast types.

Used to contain values of automatically initialized arrays


{} Braces and to define a block of code for classes, methods, and
local scopes.

Used to declare array types and for dereferencing array


[] Brackets
values.
; Semicolon Used to separate statements.

Used to separate consecutive identifiers in a variable


, Comma declaration; also used to chain statements together inside
a for statement.

Used to separate package names from sub-packages and


. Period classes; also used to separate a variable or method from a
reference variable.
Constants, Variables and Data Types
1. Constant:
Constants in java refer to fixed values that do not change during the execution
of a program. Java supports several types of constants.

• Example:
Integer constant (Decimal, Octal, Hexa):
123 -321 654321
Real Constant: 0.0083 -0.75 735.36
Character Constant: ‘5’ ‘x’ ‘;’ 0
String Constant: “Hello “1997” “5+3”
Java”
Department of E & TC
Type of
Data Type Description Example
Constant

Whole numbers
Integer int int a = 10;
(no decimal)

Numbers with float x = 3.14f;


Real float, double
decimal points double y = 25.67;

Single character
Character char char ch = 'A';
(in single quotes)

Group of
String String String name ="Diagram";
characters (text)

True or False
Boolean boolean boolean flag = true;
values
2. Variables:
• The variable is the basic unit of storage in a Java program.
• A variable is defined by the combination of an identifier, a type, and an optional
initializer.
• In addition, all variables have a scope, which defines their visibility, and a lifetime.
These elements are examined next.
• Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:
type identifier[ =value][,identifier[=value] ...] ;
• Here are several examples of variable declarations of various types.
Note that some include an initialization.
✔ int a, b, c; // declares three ints, a, b, and c.
✔ int d = 3, e, f = 5; // declares three more ints, initializing d and f.
✔ byte z = 22; // initializes z.
✔ double pi = 3.14159; // declares an approximation of pi.
✔ char x = 'x'; // the variable x has the value 'x'

Department of E & TC
Scope Of variables:
• Java variables are actually classified into three kinds:
✔ Instance variables.
✔ Class variables, and
✔ Local variables.

• Instance and class variables are declared inside a class. Instance variables are created
when the objects are instantiated and therefore they are associated with the objects.
They take different values for each class creates. Only one memory location is created
for each class variables.

• Variables declared and used inside methods are called local variables. They are
called so because they are not available for use outside the method definition. Local
variables can also be declared inside the program blocks that are defined between an
opening braces { and closing brace }. These variables are visible to program only from
the beginning of its program block to the end of program block. When program control
leaves a block, all the variables in the block will cease to exist. The area of program
where the variable is accessible (i.e. usable) is called its scope.
Department of E & TC cont……. 19
• We can have program blocks within other program blocks (called nesting) as
shown in figure. Each block contains its own set of local variable declarations. We
cannot, however declare a variable to have the same name as one in outer block. In
figure the variable x declared in block1 is available in all three blocks. However,
the variable n declared in block 2 is available only in block 2, because it goes out
of the scope at the end of block 2. Similarly, m is accessible only in block 3.

• Note that we cannot declare the variable x again in block2 and block3 (This is
perfectly legal in C and C++).
Department of E & TC
Type Casting:
• We often encounter situations where there is a need to store a value of one type into
a variable of another type. In such situations, we must cast the value to be stored by
proceeding it with the type name in parentheses. The syntax is:

type variable1 =(type)variable2 ;


The process of converting one data type to another is called
casting. Example:
int m =50;
byte n =(byte)m;
long count=(long)m;
Casting is often necessary when a method returns a type different than the one we require.

Department of E & TC
Casts that results in no loss of information

Department of E & TC
Data Types
• Every variable of java has a data type.
• Data type specifies the size and type of values that can
be stored.
• Specify the type of data and the length of the data item
in bytes.

Department of E & TC
Data Types

Department of E & TC
Operators and Expressions:

• Java provides a rich set of operators to manipulate variables. We can divide


all the Java operators into the following groups:

– Arithmetic Operators
– Relational Operators
– Bitwise Operators
– Logical Operators
– Assignment Operators
– Misc Operators
– Special operators

Department of E & TC
The Arithmetic Operators:
• Arithmetic operators are used in mathematical
expressions in the same way that they are
used in algebra. The following table lists the
arithmetic operators:
• Assume integer variable A holds 10 and variable B holds 20, then

Department of E & TC
The Relational Operators:
• There are following relational operators supported by Java language:
• Assume variable A holds 10 and variable B holds 20, then:

Department of E & TC
The Bitwise Operators:
• Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte. Bitwise operator works on bits and performs bit-
by-bit operation. Assume if a = 60; and b = 13; now in binary format
• they will be as follows:
a = 0011 1100
b = 0000 1101
-------------------------- a&b
= 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Department of E & TC
The Bitwise
Operators:

Department of E & TC
The Logical Operators:
• The following table lists the logical operators:
• Assume Boolean variables A holds true and variable B holds false, then:

Department of E & TC 30
The Assignment Operators:
There are following assignment operators supported by Java language.

Department of E & TC
31
Misc Operators
• There are few other operators supported by Java Language.
• Conditional Operator (?:)
• Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide which value should be assigned to the variable. The operator is written as:
variable x =(expression)? value if true: value if false
• Following is the example:
public class Test{
public static void main(String args[])
{
int a , b;
a =10;
b =(a ==1)?20:30;
[Link]("Value of b is : "+ b );
b =(a ==10)?20:30;
[Link]("Value of b is : "+ b );
}
}
• This would produce the following result:
Value of b is:30
Value of b is:20
Department of E & TC
Special operators

instanceof:

This operator allows us to determine whether the object belongs to a particular

class or not.

Ex: person instanceof student

this statement returns true if person belongs to student else returns false.

dot (member operator):

This operator is used to access the member of a package or a class.

Department of E & TC
Operator precedence and associatively
This is very important when there is an expression involving more than one operator.

Rank Operators
1 . , () , []
2 - , ++ , -- , ! , ~
3 *,/,%
4 +,-
5 << , >> , >>>
6 < , <= , > , >= , instanceof
7 == , !=
8 &
9 ^
10 `
11 &&
12 `
13 ?: (ternary operator)
14 =
Department of E & TC
Java Decision Making
• There are two types of decision making statements in Java.
They are:
✔ if statements
✔ switch statements
The if Statement:
• An if statement consists of a Boolean expression followed by
one or more
statements.
• Syntax:
The syntax of an if
statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}

Department of E & TC 34
• Example:
public class Test{
public static void main(String
args[]){ int x =10;
if( x <20){
[Link]("This is if statement");
}
}
}

This would produce the following result:


This is if statement
The if...else Statement:
• An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.
• Syntax:
The syntax of an if...else is:
if(Boolean_expression){
//Executes when the Boolean expression is true
}
else{
//Executes when the Boolean expression is false
}

• This would produce the following result: This is else statement


Department of E & TC 35
• Example:
public class Test{
public static void
main(String args[])
{
int x =30;
if(x <20)
{
[Link]("This is if statement");
}else
{
[Link]("This is else statement");

}
}

This would produce the following result:


This is if statement
The switch Statement:

• A switch statement allows a variable to be tested for equality


against a list of values.

• Each value is called a case, and the variable being switched


on is checked for each case.

Department of E & TC
• Example:
• public class Test {
public static void main(String[] args) {
int day = 3;
switch(day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
default:
[Link]("Invalid day");
}
}
}
Loop Statements :
1. while ( <condition>)
{
------------------- //loop body
}
2. for( <initialization>; <condition testing>; <increment/decrement> )
{
------------------- //loop body
}
3. do
{
------------------- //loop body
} while ( <condition>);

Department of E & TC
public static void main(String argc[])
Public:
This is an access modifier. It has to be public so that java runtime can execute this method. Remember that if you
make any method non-public then it’s not allowed to be executed by any program, there are some access
restrictions applied
Static:
In any Java program, the main() method is the starting point from where compiler starts program execution. So,
the compiler needs to call the main() method.
If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
Static method of a class can be called by using the class name only without creating an object of a class.
The main() method in Java must be declared public, static and void. If any of these are missing, the Java
program will compile but a runtime error will be thrown.
Void:
Main() method does not return any thing thus it is void.
String argc[]:
This is a command line arguments (Input). These are passed to the program during runtime. These arguments
are passed as arguments to main(String args[]).
This means that arguments are stored in array args[] and are of String datatype.
final keyword in java
final keyword is applicable only to a variable, a method or a class

Final Variable To create constant variables


Final Method To prevent method overriding.
Final Class To Prevent inheritance
When a variable is declared with final keyword, its value can’t be modified, essentially, a
constant. This also means that you must initialize a final variable.
Initializing a final variable :
We must initialize a final variable, otherwise compiler will throw compile-time error. A final
variable can only be initialized once.
There are three ways to initialise but the most widely used way is when the final variable is
declared.
When to use a final variable :
The only difference between a normal variable and a final variable is that we can re-assign value
to a normal variable but we cannot change the value of a final variable once assigned. Hence
final variables must be used only for the values that we want to remain constant throughout the
execution of program.
Ex: final int STRENGTH = 100
final float PI = 3.14f
final char DATA = ‘c’
Department of E & TC
Arrays in Java:
❖ Java array is an object which contains elements of a similar data type.

❖ In Java, array is an object of a dynamically generated class.

❖ Declaring an array
Arrays are dynamically allocated.
Arrays are treated as objects and thus can find their length using member length.

❖ Declaration of an array
int [ ]a;
int a[ ];

❖ Allocation of memory or instantiation.


new operator is compulsory used to allocate memory.
Syntax: arrayname = new type[size];
Ex: int [ ] a;
a = new int[4];
int a[ ] ;
a = new int[2];
Department of E & TC
Arrays in Java:
❖ Initialisation

int a[ ] = {10,20,30,40};
string s[ ] = {“abc”,”pqr” };

❖ Printing the array:

for(i=0;i<[Link];i++)
{
[Link](a[i])
}

Department of E & TC
For-each Loop for Java Array
❖ We can also print the Java array using for-each loop.
❖ The Java for-each loop prints the array elements one by one.
❖ It holds an array element in a variable, then executes the body of the loop.
❖ The syntax of the for-each loop is given below:
for(data_type variable : array)
{
//body of the loop
}
Example:
class Testarray
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
[Link](i);
}
}

Department of E & TC
Programs:
❖ Write a program to find factorial of a number.
package factorial;
public class Factorial {
public static void main(String[] args) {
int i, fact =1, n = 4;
for(i=1;i<=4;i++)
{
fact = fact*i;
}
[Link]("Factorial is: "+fact);
}}
❖ Write a program to print elements in an array.
package array;
public class Array_print {
public static void main(String[] args)
{
int a[] = {10,12,13,14};
int i;
[Link]("The elements in array are:");
for(i=0;i<[Link];i++)
{
[Link]("\t"+a[i]);
}
}} Department of E & TC
Mathematical functions in java
Java supports many mathematical functions through class math.
This math class is defined in package called [Link]
Syntax:
Math.function_name()
Example:
[Link](x,y);
This method finds the max out of x and y.

List of functions:

❖ max(x,y)
❖ min(x,y)
❖ sqrt(x)
❖ abs(x) absolute (positive) value of x. Thus x should be negative.
❖ random() This method returns randomly numbers between 0 and 1
❖ sin(x)
❖ cos(x)
❖ tan(x)
❖ pow(x,y) returns x^y
❖ exp(x) returns e^x
Department of E & TC
Reading Input from User
❖ Java Scanner class allows the user to take input from user.
❖ It belongs to [Link] package.
❖ It is used to read the input of primitive types like int, double, long, short, float, and byte. It
is the easiest way to read input in Java program.
❖ To use Scanner class we have to create an object of that class and import the class in our
program.
❖ Syntax:
import [Link];
Scanner object_name=new Scanner([Link]);
❖ Example:
Scanner obj1 = new Scanner([Link])
This will create a object of class scanner. There are different methods (Functions in this class
which are now accessed using the object. JDK
Example: Package1 package2

[Link](“Enter value”); Package


int n = [Link]();
classes classes

Department of E & TC
Methods of Java Scanner Class
Java Scanner class provides the following methods to read different primitives types:
Method Description
int nextInt() It is used to scan the input as an integer.

float nextFloat() It is used to scan the input as a float.

double nextDouble() It is used to scan the input as a double.

byte nextByte() It is used to scan the input as a byte.

String nextLine() Advances this scanner past the current line.

boolean nextBoolean() It is used to scan the input into a Boolean value.

long nextLong() It is used to scan the input as a long.

short nextShort() It is used to scan the input as a Short.

BigInteger nextBigInteger() It is used to scan the input as a BigInteger.

BigDecimal nextBigDecimal() It is used to scan the input as a BigDecimal.

Department of E & TC
Programs
Write a program to add two numbers
package add_user;
import [Link];

public class Add_user {

public static void main(String[] args) {


Scanner obj1= new Scanner([Link]);
[Link]("Enter a: ");
double a= [Link]();
[Link]("Enter b: ");
double b = [Link]();
double c = a+b;
[Link]("Addition result is: "+c);
}

Department of E & TC
Programs
Write a program to print name, age and salary of an employee.
package person;
import [Link];
public class Person {

public static void main(String[] args) {


int age;
String name;
double salary;
Scanner obj1 = new Scanner([Link]);
[Link]("Enter name: ");
name = [Link]();
[Link]("Enter age: ");
age = [Link]();
[Link]("Enter salary: ");
salary = [Link]();
[Link]("Name is :"+name+"Age is:"+age+"Salary is:"+salary);

} Department of E & TC
Programs
Write a program to print day in a week.
package dayinaweek;
import [Link];
public class Day {

public static void main(String[] args) {


Scanner s = new Scanner([Link]);
int n;
[Link]("Enter the day number:");
n = [Link]();
switch(n)
{
case 1:
[Link]("Its Monday");
break;
case 2:
[Link]("Its Tuesday");
break;
case 3:
[Link]("Its Wednesday");
break;
case 4:
[Link]("Its Thrusday");
break;
case 5:
[Link]("Its Friday");
break;
case 6:
[Link]("Its Staurday");
break;
case 7:
[Link]("Its Sunday");
break;
} Department of E & TC
}}
Reading array from user
Program to find sum and average of 5 elements in an array.
package array_sum;
import [Link];
public class Array_sum {

public static void main(String[] args)


{
int i,sum =1;
Scanner s = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]();
int a[] = new int[n];
[Link]("Enter the elements: ");
for(i=0;i<n;i++)
{
a[i] = [Link]();
}
[Link]("elements are: ");
for(i=0;i<n;i++)
{
[Link]("\t"+a[i]);
}
[Link]("\n");
for(i=0;i<n;i++)
{
sum = sum+a[i];
}
double avg =sum/n;
[Link]("Sum is: "+ sum+"\n");
[Link]("Average is: "+ avg);
}
}
Department of E & TC
Passing Arrays to methods
You can pass arrays to a method just like normal variables. When we pass an array to a method as an
argument, actually the address of the array in the memory is passed (reference). Therefore, any changes
to this array in the method will affect the array.
// Print the elements in array
public static void dataArray(int[] list, int n)
{
import [Link];
Scanner s = new Scanner([Link]);
public class PassArray
[Link]("Enter " + n + " integers");
{
for (int i = 0; i < n; i++)
public static void main(String[] args)
{
{
list[i] = [Link]();
final int SIZE = 4;
}
int[] array = new int[SIZE];
}
dataArray(array, SIZE);
[Link]("Numbers are :");
public static void printArray(int[] list, int n)
printArray(array, SIZE);
{
}
for (int i = 0; i < n; i++)
{
[Link](list[i] + " ");
}
}
}
Department of E & TC
Program to find sum and average of 5 elements in an array using
function.
import [Link]; public static void calculate(int a[],int n)
{
public class Array_function { int sum =1;
for(int i=0;i<n;i++)
public static void main(String[] args) { {
sum = sum+a[i];
Scanner s = new Scanner([Link]); }
[Link]("Enter the number of elements: "); double avg =sum/n;
int n = [Link](); [Link]("Sum is: "+ sum+"\n");
int a[] = new int[n]; [Link]("Average is: "+ avg);
[Link]("Enter the elements in array: "+"\n"); }
getarray(a,n);
}
[Link](" elements in array are : "+"\n");
printarray(a,n);
[Link](" Sum and average is: "+"\n");
calculate(a,n);
}
public static void getarray(int a[],int n)
{
Scanner s = new Scanner([Link]);
for(int i=0;i<n;i++)
{
a[i] = [Link]();
}
}
public static void printarray(int a[],int n)
{
for(int i=0;i<n;i++)
{
[Link](" \n"+a[i]); Department of E & TC
}}
Thank you

Department of E & TC

You might also like