0% found this document useful (0 votes)
29 views

Unit 1

Uploaded by

barla geetha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Unit 1

Uploaded by

barla geetha
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

PARADIGMS OF PROGRAMMING LANGUAGES

 The term paradigm describes a set of techniques, methods, theories and standards
that together represent a way of thinking for problem solving.
 Language paradigms were associated with classes of languages. First the
paradigms are defined. Thereafter, programming languages according to the
different paradigms are classified.
 The language paradigms are divided into two parts, imperative and declarative
paradigms
 Imperative languages can be further classified into procedural and object
oriented approach.
 Declarative languages can be classified into functional languages and logical
languages.

 Imperative paradigm: The meaning of imperative is “expressing a command or


order”, so the programming languages in this category specify the step-by-step
explanation of command. Imperative programming languages describe the details
of how the results are to be obtained. The programs specify step by step the entire
set of transitions that the program goes through. The program starts from an initial
state, goes through the transitions and reaches a final state. Within this paradigm
we have the procedural approach and Object Oriented approach.

 Procedural paradigm: Procedural languages are statement oriented with


the variables holding values. We have two kinds of statements.
Nonexecutable statements allocate memory, bind symbolic names to
absolute memory locations, and initialize memory. Executable statements
like computation, control flow, and input/output statements. The popular
programming languages in this category are Fortran, Basic, Algol, Pascal,
Cobol, C, etc.

 Object Oriented paradigm: The Object Oriented paradigm is centered on


the concept of the object. Everything is focused on objects. Computation in
this paradigm is viewed as the simulation of real world entities. The popular
programming languages in this paradigm are C++ and Java.

 Declarative paradigm: In this paradigm programs declare or specify what is to be


computed without specifying how it is to be achieved. Declarative programming is
also known as Value-oriented programming. Declarative languages describe the
relationships between variables in terms of functions and inference rules.
Declarative paradigm is further divided into two categories, functional and logical
paradigms.

 Functional paradigm: In this paradigm, a program consists of a collection


of functions. A function just computes and returns a value. A program
consists of calling a function with appropriate arguments, but any function
can make use of other functions also.

 Logic paradigm: In this paradigm programs only explain what is to be


computed not how to compute it. Here program is represented by a set of
relationships, between objects or property of objects known as predicate
which are held to be true, and a set of logic/clauses (i.e. if A is true, then B
is true).

Differences between POP and OOP:-

POP OOP
POP follows Top Down approach. OOP follows Bottom Up approach.
In POP, program is divided into small parts In OOP, program is divided into parts called
called functions. objects.
POP does not have any proper way for OOP provides Data Hiding so provides
hiding data so it is less secure. more security.
Their is no provision of inheritance. Inheritance achieved in three modes public
private and protected.
Operator overloading is not allowed. Operator overloading is allowed.
Example of POP are : C,FORTRAN, Example of OOP are : C++, JAVA,
Pascal. VB.NET, C#.NET.

Introduction to OOPs using java:


JAVA was developed by Sun Microsystems Inc in 1991,later acquired by Oracle
Corporation. It was developed by James Gosling and Patrick Naughton. It is a simple
programming language. Writing, compiling and dxebugging a program is easy in java. It
helps to create modular programs and reusable code.

Java terminology

1. Java Development Kit(JDK).


As the name suggests this is complete java development kit that includes JRE (Java
Runtime Environment), compilers and various tools like JavaDoc, Java debugger etc.In
order to create, compile and run Java program you would need JDK installed on your
computer.

2. Java Runtime Environment(JRE)


JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed
on your system, you can run a java program however you won’t be able to compile it.
JRE includes JVM, browser plugins and applets support. When you only need to run a
java program on your computer, you would only need JRE.

3. bytecode
javac compiler of JDK compiles the java source code into bytecode so that it can be
executed by JVM. The bytecode is saved in a .class file by compiler.

4. Java Virtual Machine (JVM)


Before, we discuss about JVM lets see the phases of program execution. Phases are as
follows:
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler
included in java development kit (JDK). It takes java program as input and generates java
bytecode as output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called
program run phase.

So, now that we understood that the primary function of JVM is to execute the bytecode
produced by compiler. Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating systems. That is why we
call java as platform independent language.

5. API:
An application programming interface (API), in the context of Java, is a collection
of prewritten packages, classes, and interfaces with their respective methods, fields and
constructors. Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and
packages, which are helpful in minimizing the number of lines written within pieces of
code.
After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.

Basic concepts of OOPs

 Class
 Object
 Abstraction
 Encapsulation

 Inheritance
 Polymorphism

1. Class

Collection of objects is called class. It is a logical entity. A class is a group of objects


which have common properties. It is a template or blueprint from which objects are
created. It is a logical entity. It can't be physical.

A class in Java can contain:


 fields
 methods
 constructors
 blocks
 nested class and interface

Syntax to declare a class:

class<class_name>{
field;
method;
}

2. Object

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical. Object is the physical as
well as logical entity whereas class is the logical entity only.

An object has three characteristics:


 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. But, it is used internally by the JVM to
identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

3. Abstraction
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a
process where you show only “relevant” data and “hide” unnecessary details of an object
from the user. For example, when you login to your Amazon account online, you enter
your user_id and password and press login, what happens when you press login, how the
input data sent to amazon server, how it gets verified is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system, steering mechanism,
engine, which are again have their own subsystems. But for humans car is a one single
object, which can be managed by the help of its subsystems, even if their inner details are
unknown.

4. Encapsulation

Encapsulation is:
 Binding the data with the code that manipulates it.
 It keeps the data and the code safe from external interference
Looking at the example of a power steering mechanism of a car. Power steering of a car
is a complex system, which internally have lots of components tightly coupled together,
they work synchronously to turn the car in the desired direction. It even controls the
power delivered by the engine to the steering wheel. But to the external world there is
only one interface is available and rest of the complexity is hidden. Moreover, the
steering unit in itself is complete and independent. It does not affect the functioning of
any other mechanism.
5. Inheritance
 Inheritance is the mechanism by which an object acquires the some/all properties
of another object.
 It supports the concept of hierarchical classification.
For example: Car is a four wheeler vehicle so assume that we have a class
FourWheeler and a sub class of it named Car. Here Car acquires the properties of a class
FourWheeler. Other classifications could be a jeep, tempo, van etc. FourWheeler defines
a class of vehicles that have four wheels, and specific range of engine power, load
carrying capacity etc. Car (termed as a sub-class) acquires these properties from
FourWheeler, and has some specific properties, which are different from other
classifications of FourWheeler, such as luxury, comfort, shape, size, usage etc.
A car can have further classification such as an open car, small car, big car etc, which
will acquire the properties from both Four Wheeler and Car, but will still have some
specific properties. This way the level of hierarchy can be extended to any level.

6. Polymorphism
 Polymorphism means to process objects differently based on their data type.
 In other words it means, one method with multiple implementation, for a certain
class of action. And which implementation to be used is decided at runtime
depending upon the situation (i.e., data type of the object)

Lets us look at same example of a car. A car have a gear transmission system. It has four
front gears and one backward gear. When the engine is accelerated then depending upon
which gear is engaged different amount power and movement is delivered to the car. The
action is same applying gear but based on the type of gear the action behaves differently
or you can say that it shows many forms (polymorphism means many forms)

Main Features of JAVA

1. Java is a platform independent language


Compiler (javac) converts source code (.java file) to the byte code(.class file). As
mentioned above, JVM executes the bytecode produced by compiler. This byte code can
run on any platform such as Windows, Linux, Mac OS etc. Which means a program that
is compiled on windows can run on Linux and vice-versa. Each operating system has
different JVM, however the output they produce after execution of bytecode is same
across all operating systems. That is why we call java as platform independent language.

2. Simple
Java is considered as one of simple language because it does not have complex
features like Operator overloading, Multiple inheritance, pointers and Explicit memory
allocation.
3. Robust Language
Robust means reliable. Java programming language is developed in a way that
puts a lot of importance on early checking for possible errors, that’s why java compiler is
able to detect errors that are not easy to detect in other programming languages. The main
features of java that makes it robust are garbage collection, Exception Handling and
memory allocation.

4. Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in Java.

5. Java is distributed
Using java programming language we can create distributed applications.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating
distributed applications in java. In simple words: The java programs can be distributed on
more than one systems that are connected to each other using internet connection. Objects
on one JVM (java virtual machine) can execute procedures on a remote JVM.

6. Multithreading
Java supports multithreading. Multithreading is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization of CPU.
7. Portable
As discussed above, java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any platform for
execution that makes java code portable.

Applications of OOPs:

 Web Applications such as irctc.co.in etc.


 Desktop Applications such as acrobat reader, media player, antivirus, etc.
 Enterprise Applications such as banking applications.
 Mobile
 Embedded System
 Smart Card
 Robotics
 Games, etc.

Advantages of OOPs:

OOP offers several benefits to both the program developer and the user. The new
technology provides greater programmer productivity, better quality of software and
lesser maintenance cost. The major benefits are:
 Ease in division of job: Since it is possible to map objects of the problem domain
to those objects in the program, the work can be easily partitioned based on
objects.
 Reduce complexity: Software complexity can be easily managed.
 Provide extensibility: Object Oriented systems can be easily upgraded from small
to large system.
 Eliminate redundancy: Through inheritance we can eliminate redundant code
and extend the use of existing classes.
 Saves development time and increases productivity: Instead of writing code
from scratch, solutions can be built by using standard working modules.
 Allows building secure programs: Data hiding principle helps programmer to
build secure programs that cannot be accessed by code in other parts of the
program.
Types of java programming:
There are many types of Java programs which run differently:
 Java Applet - small program written in Java and that is downloaded from a
website and executed within a web browser on a client computer.
 Application - executes on a client computer. If online, it has to be downloaded
before being run.
 JAR file (Java ARchive) - used to package Java files together into a single file
(almost exactly like a .zip file).
 Servlet - runs on a web server and helps to generate web pages.
 Swing application - used to build an application that has a GUI (windows,
buttons, menus, etc.).
 EJB - runs on a web server and is used to develop large, complex websites.

How to Compile and Run your First Java Program

Simple Java Program:


public class FirstJavaProgram {
public static void main(String[] args){
System.out.println("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class
Output: This is my first program in java

How to compile and run the above program


Prerequisite: You need to have java installed on your system.
Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the
above program and paste it in the text editor.
Step 2: Save the file as FirstJavaProgram.java You may be wondering why we have
named the file as FirstJavaProgram, the thing is that we should always name the file same
as the public class name. In our program, the public class name is FirstJavaProgram,
that’s why our file name should be FirstJavaProgram.java.
Step 3: In this step, we will compile the program. For this, open Terminal in Linux
To compile the program, Set path in Linux and type the following command and hit
enter.
javac FirstJavaProgram.java

Step 4: After compilation the .java file gets translated into the .class file(byte code). Now
we can run the program. To run the program, type the following command and hit enter:
java FirstJavaProgram

Explanation to the First Java Program


public class FirstJavaProgram {
This is the first line of our java program. Every java application must have at least one
class definition that consists of class keyword followed by class name. When I say
keyword, it means that it should not be changed, we should use it as it is. However the
class name can be anything.
You need to know now that a java file can have any number of classes but it can have
only one public class and the file name should be same as public class name.
public static void main(String[] args) {
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from
outside the class.
static: We do not need to create object for static methods to run. They can run itself.
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run
your program.
(String[] args): Used for command line arguments that are passed as strings.
System.out.println("This is my first program in java");
This method prints the contents inside the double quotes into the console and inserts a
newline after.

Tokens

Token is the smallest element of a program that is meaningful to the compiler.


There is Five Types of Tokens
 Reserve Word or Keywords
 Identifier
 Literals
 Separators
 Operators

Java Keywords
Keywords are predefined, reserved words used in Java programming that have special
meanings to the compiler.
For example: int score;
Here, int is a keyword. It indicates that the variable score is of integer type.
You cannot use keywords like int, for, class etc as variable name (or identifiers) as they
are part of the Java programming language syntax. Here's the complete list of all
keywords in Java programming.
Java Keywords List
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implement impor
s t
instanceo int interfac long native
f e
new package private protected public
return short static strictfp super
switch synchronize this throw throw
d s
transient try void volatile while

Java identifiers
Identifiers are the name given to variables, classes, methods etc.
Example: int score;
Here, score is a variable (an identifier). You cannot use keywords as variable name. It's
because keywords have predefined meaning.
Rules for Naming an Identifier
 Identifier cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter, $
or _. The first letter of an identifier cannot be a digit.
 It's convention to start an identifier with a letter rather and $ or _.
 Whitespaces are not allowed.
 Similarly, you cannot use symbols such as @, #, and so on.
Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is a Integer literal.
char ch ='A';
Here A is a char literal
Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b =100;
short s =200;
int num =13313131;
long l =928389283L;
Float Literals
Used for data type float and double.
double num1 =22.4;
float num2 =22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
Char and String Literal
Used for char and String type.
char ch ='Z';
String str ="BeginnersBook";

Separators in Java
Separators help define the structure of a program. The separators used in HelloWorld are
parentheses( ), braces,{ }, the period,., and the semicolon,;. The table lists the six Java
separators (nine if you count opening and closing separators as two).

Separator Name Use

. Period It is used to separate the package name from


sub-package name & class name. It is also
used to separate variable or method from its
object or instance.

, Comma It is used to separate the consecutive


parameters in the method definition. It is also
used to separate the consecutive variables of
same type while declaration.

; Semicolon It is used to terminate the statement in Java.

() Parenthesis This holds the list of parameters in method


definition. Also used in control statements &
type casting.

{} Braces This is used to define the block/scope of code,


class, methods.

[] Brackets It is used in array declaration.

Separators in Java

Variable
A Java variable is a piece of memory that can contain a data value. A variable thus has a
data type. Variables are typically used to store information which your Java program
needs to do its job.
In the code example below, the main() method contains the declaration of a single integer
variable named number. The value of the integer variable is first set to 10, and then 20 is
added to the variable afterwards.
public class MyClass {
public static void main(String[] args) {
int number = 10;
number = number + 20;
}
}
Java Variable Types
In Java there are four types of variables:
1. Non-static fields
2. Static fields
3. Local variables
4. Parameters
1. A non-static field is a variable that belongs to an object. Objects keep their internal
state in non-static fields. Non-static fields are also called instance variables,
because they belong to instances (objects) of a class. Non-static fields are covered
in more detail in the text on Java fields.
2. A static field is a variable that belongs to a class. A static field has the same value
for all objects that access it. Static fields are also called class variables. Static
fields are also covered in more detail in the text on Java fields.
3. A local variable is a variable declared inside a method. A local variable is only
accessible inside the method that declared it. Local variables are covered in more
detail in the text on Java methods.
4. A parameter is a variable that is passed to a method when the method is called.
Parameters are also only accessible inside the method that declares them, although
a value is assigned to them when the method is called. Parameters are also covered
in more detail in the text on Java methods.

Java Variable Declaration


Exactly how a variable is declared depends on what type of variable it is (non-static,
static, local, parameter). However, there are certain similarities that
In Java you declare a variable like this:
type name ;
Instead of the word type, you write the data type of the variable. Similarly, instead of the
word name you write the name you want the variable to have.
Here is an example declaring a variable named myVariable of type int.
int myVariable;
Java Variable Assignment
Assigning a value to a variable in Java follows this pattern:
variableName = value ;
Here are three concrete examples which assign values to three different variables with
different data types
myInt = 127;
myFloat = 199.99;
myString = "This is a text";
Java Variable Naming Conventions
There are a few rules and conventions related to the naming of variables.
The rules are:
1. Java variable names are case sensitive. The variable name money is not the same
as Money or MONEY.
2. Java variable names must start with a letter, or the $ or _ character.
3. After the first character in a Java variable name, the name can also contain
numbers (in addition to letters, the $, and the _ character).
4. Variable names cannot be equal to reserved key words in Java. For instance, the
words int or for are reserved words in Java. Therefore you cannot name your
variables int or for.
Here are a few valid Java variable name examples:
myvar
myVar
MYVAR
_myVar
$myVar
myVar1
myVar_1
Scope of a variable

Scope and Lifetime of Variables. The scope of a variable defines the section of the code
in which the variable is visible. As a general rule, variables that are defined within a
block are not accessible outside that block. The lifetime of a variable refers to how
long the variable exists before it is destroyed.

Constants in Java.

A constant is a variable which cannot have its value changed after declaration. It uses
the 'final' keyword.

Type Casting in Java


Type casting is used to convert an object or variable of one type into another.
Syntax
dataType variableName = (dataType) variableToConvert;
Example

double calculatedMark = 87.6;


int finalGrade = (int)calculatedMark; //will return 87

Data Types

Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values.
In java we have two categories of data type:
1) Primitive data types 2) Non-primitive data types – Arrays and Strings are non-
primitive data types.
1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double. Java developers included these data types to maintain the portability of java as
the size of these primitive data types do not change from one operating system to another.
 byte, short, int and long data types are used for storing whole numbers.
 float and double are used for fractional numbers.
 char is used for storing characters(letters).
 boolean data type is used for variables that holds either true or false.

byte:
This can hold whole number between -128 and 127. Mostly used to save memory and
when you are certain that the numbers would be in the limit specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:
classJavaExample{
public static void main(String[] args){
byte num;
num =113;
System.out.println(num);
}
}
Output:
113
Try the same program by assigning value assigning 150 value to variable num, you would
get type mismatch error because the value 150 is out of the range of byte data type. The
range of byte as I mentioned above is -128 to 127.

short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte
short num=45678;

int:
Used when short is not large enough to hold the number, it has a wider range:
-2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
classJavaExample{
publicstaticvoid main(String[] args){
short num;
num =150;
System.out.println(num);
}
}
Output:
150

long:
Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
classJavaExample{
publicstaticvoid main(String[] args){
long num =-12332252626L;
System.out.println(num);
}
}
Output:
-12332252626

double:
Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
classJavaExample{
publicstaticvoid main(String[] args){

double num =-42937737.9d;


System.out.println(num);
}
}
Output:
-4.29377379E7

float:
Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
classJavaExample{
publicstaticvoid main(String[] args){
float num =19.98f;
System.out.println(num);
}
}
Output:
19.98

boolean:
Holds either true of false.
classJavaExample{
publicstaticvoid main(String[] args){

boolean b =false;
System.out.println(b);
}
}
Output:
false

char:
Holds characters.
Size: 2 bytes
classJavaExample{
publicstaticvoid main(String[] args){

char ch ='Z';
System.out.println(ch);
}
}
Output:
Z
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running
the java program. The arguments passed from the console can be received in the java
program and it can be used as an input. So, it provides a convenient way to check the
behavior of the program for the different values.
Example:
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}

compileby>javac CommandLineExample.java
runby>java CommandLineExamplesonoo

Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code for specific
time.
1. Single Line Comment

Example: //This is single line comment

2. Multi Line Comment

Example:

/*

This

is

multi line

comment

*/

Basic Examples:

Java Program to read integer value from the Standard Input

In this program we will see how to read an integer number entered by user. Scanner class
is in java.util package. It is used for capturing the input of the primitive types like int,
double etc. and strings.

Program to read the number entered by user


We have imported the package java.util.Scanner to use the Scanner. In order to read the
input provided by user, we first create the object of Scanner by passing System.in as
parameter. Then we are using nextInt() method of Scanner class to read the integer.

import java.util.Scanner;
publicclassDemo{
publicstaticvoid main(String[] args){
Scanner scan =newScanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
scan.close();
// Displaying the number
System.out.println("The number entered by user: "+num);
}
}
Output:
Enter any number:101
The number entered by user:101
publicclassAddTwoNumbers{
publicstaticvoid main(String[] args){
int num1 =5, num2 =15, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Sum of these numbers:20
Exercise:
1.Write a program to print Sum of two numbers using Scanner
import java.util.Scanner;
public class AddTwoNumbers2{
public static void main(String[] args){
int num1, num2, sum;
Scanner sc =newScanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
EnterFirstNumber:
121
EnterSecondNumber:
19
Sum of these numbers:140
2. Write a Java program to swap two variables.

public class swap {

public static void main(String[] args) {

int a, b, temp;
a = 15;
b = 27;
System.out.println("Before swapping : a, b = "+a+", "+ + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping : a, b = "+a+", "+ + b);
}
}
3. Write a Java program that reads a number and display the square, cube, and fourth
power.
import java.util.Scanner;
public class square {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input the side length value: ");
double val = in.nextDouble();

System.out.printf("Square: %12.2f\n", val * val);


System.out.printf("Cube: %14.2f\n", val * val * val);
System.out.printf("Fourth power: %6.2f\n", Math.pow(val, 4));
}
}
4. Write a Java program that accepts two integers and then prints the sum, the difference,
the product, the average, the distance (the difference between integer), the maximum (the
larger of the two integers), the minimum (smaller of the two integers).
import java.util.Scanner;
public class operations {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input 1st integer: ");
int firstInt = in.nextInt();
System.out.print("Input 2nd integer: ");
int secondInt = in.nextInt();

System.out.printf("Sum of two integers: %d%n", firstInt + secondInt);


System.out.printf("Difference of two integers: %d%n", firstInt - secondInt);
System.out.printf("Product of two integers: %d%n", firstInt * secondInt);
System.out.printf("Average of two integers: %.2f%n", (double) (firstInt + secondInt)
/ 2);
System.out.printf("Distance of two integers: %d%n", Math.abs(firstInt - secondInt));
System.out.printf("Max integer: %d%n", Math.max(firstInt, secondInt));
System.out.printf("Min integer: %d%n", Math.min(firstInt, secondInt));
}
}

You might also like