Department of Information Technology: JAVA Assignment-1 (BTIT-502) B.Tech 3rd Year - V Semester

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

“DEPARTMENT OF INFORMATION TECHNOLOGY”

Department of Information Technology

JAVA Assignment-1
( BTIT-502)
B.Tech 3rd Year – V Semester
(Branch: IT)

Submitted To: Submitted By:


Ms.Sharanjeet Kaur
Anurag
Assistant Professor
1703233
I.T Department
5th / A1

Chandigarh Engineering College


Anurag 1
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Landran, Mohali-140307
Programming in java (BTIT-502)
Assignment –I
Questions:
Explain in brief (Question 1-4)

Explain in detail (Question 5-9)

1. Write the structure of a typical Java program.

2. What is the difference between a class and an object?

3. What is CLASSPATH?

4. What are Byte Codes?

5. Discuss the salient features of Java programming language. How Java is different from C

and C++?

6. What are the various operators available in Java? Discuss each with an example

7. What are Jagged arrays? Explain with examples.

8. Why Java is called platform independent?

9. Write various steps to develop compile and run Java program. Explain with example.

Answers:-
1. Write the structure of a typical Java program.

Answer:- Structure of a Java program

A typical Structure of a Java program would contain the following elements:


 Package declaration
 Import statements
 Comments

Anurag 2
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

 Class definition
 Class variables, Local variables
 Methods/Routines/Behaviors
The below picture would show the above mentioned elements that make out the structure of
Java program.

Structure of a Java program


Package Declaration :
Classes in java could be placed in different directories/packages based on the module they are
used in or the functionality it provides. For all classes that belong to a single parent source
directory, path from source directory is considered as package declaration.
Import Statements :
There would be classes written in other folders/packages of your working java project and
also there are many classes written by individuals, companies, institutions, enthusiasts etc.,
which could be useful in our program. To use them in a class, we would need to import the class
that we intend to use. Many classes could be imported in a single program and hence multiple
import statements could be written.
Class Name :
A name should be given to class in java file. This name is used while creating an object of the
class, in other classes/programs.
Variables :
Anurag 3
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Variables are the means of storing the values of parameters that are required during execution of
the program. Variables declared with modifiers have different scopes, which define the life of a
variable. We shall see in detail about the modifiers like global, local, static and private at
Variables in Java.
Main method :
Execution of a java application starts from “main” method. In other words, its an entry point for
the class or program that starts in Java Run-time.
Method/Routine/Behavior :
This is a room for a set of instructions which form a purposeful functionality or a routine that
would be required to run multiple times during the execution of the program.

2. What is the difference between a class and an object?

Answer:- What is Class?

A class is an entity that determines how an object will behave and what the object will contain.
In other words, it is a blueprint or a set of instruction to build a specific type of object.

Syntax

class <class_name>
{
field;
method;
}

What is an Object?

An object is nothing but a self-contained component which consists of methods and properties to
make a particular type of data useful. Object determines the behavior of the class. When you
send a message to an object, you are asking the object to invoke or execute one of its methods.

From a programming point of view, an object can be a data structure, a variable or a function. It
has a memory location allocated. The object is designed as class hierarchies.

Syntax

ClassName ReferenceVariable = new ClassName();

Anurag 4
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

No. Object Class

1) Object is an instance of a class. Class is a blueprint or


template from which objects are
created.
2) Object is a real world entity such as Class is a group of similar objects.
pen, laptop, mobile, bed, keyboard,
mouse, chair etc.
3) Object is a physical entity. Class is a logical entity.

4) Object is created through new Class is declared using class


keyword mainly e.g. keyworde.g.
Student s1=new Student(); class Student{}
5) Object is created many times as per Class is declared once.
requirement.
6) Object allocates memory when it is Class doesn't allocated memory
created. when it is created.

7) There are many ways to create There is only one way to define
object in java such as new keyword, class in java using class keyword.
newInstance() method, clone() method,
factory method and deserialization.

some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

3 .What is CLASSPATH?
Answer:-Java classpath is where Java looks for Java files. But it seems that you have a problem
with windows path variable, because javac itself is not found.

At the bottom of your picture is path variable. You should add the directory path that you
mentioned to that variable. Also check if javac.exe is actually in that directory.The javac.exe file
is in the /bin subdirectory.
Anurag 5
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

4. What are Byte Codes?

Anurag 6
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Answer:-Java byte code is the result of the compilation of a Java program, an intermediate
representation of that program which is machine independent.

The Java byte code gets processed by the Java virtual machine (JVM) instead of the processor. It
is the job of the JVM to make the necessary resource calls to the processor in order to run the
byte code.

5.Discuss the salient features of Java programming language. How Java is different from C
and C++?
Answer:-Java is a programming language that produces software for multiple platforms. When
a programmer writes a Java application, the compiled code (known as bytecode) runs on most
operating systems (OS), including Windows, Linux and Mac OS. Java derives much of its
syntax from the C and C++ programming languages.
Features of Java

The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
java buzzwords.

A list of most important features of Java language is given below.

Anurag 7
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:

Anurag 8
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).

Secured
Anurag 9
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which


is used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
right to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and
64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

High-performance

Anurag 10
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and
EJB are used for creating distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet

Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It shares a common memory
area. Threads are important for multi-media, Web applications, etc.

Dynamic

Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++.Java supports
dynamic compilation and automatic memory management (garbage collection).

Anurag 11
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

6.What are the various operators available in Java? Discuss each with an example

Answer:-

An operator, in Java, is a special symbols performing specific operations on one, two or three operands and

then returning a result.

Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Ternary Operators

Anurag 12
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

1.Arithmetic Operators: They are used to perform simple arithmetic operations on primitive
data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction

Example:-

import java.util.Scanner;
public class Arithmeticopr
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter first number :");
int num1 = in.nextInt();
System.out.println("Enter second number :");
int num2 = in.nextInt();
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
int divide = num1 / num2;
int modulo = num1 % num2;
System.out.println("Sum : " + sum);
System.out.println("Difference : " + difference);
System.out.println("Product : " + product);
System.out.println("Divide : " + divide);
System.out.println("Modulo : " + modulo);
System.out.println("\n\nAnurag\n\n1703233\n");
}
}

Anurag 13
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Relational Operators : These operators are used to check for relations like equality, greater than,
less than. They return boolean result after the comparison and are extensively used in looping
statements as well as conditional if else statements. General format is,
variable relation_operator value
Some of the relational operators are-
 ==, Equal to : returns true of left hand side is equal to right hand side.
 !=, Not Equal to : returns true of left hand side is not equal to right hand side.
 <, less than : returns true of left hand side is less than right hand side.
 <=, less than or equal to : returns true of left hand side is less than or equal to right hand
side.
 >, Greater than : returns true of left hand side is greater than right hand side.
 >=, Greater than or equal to: returns true of left hand side is greater than or equal to
right hand side.
Example:

import java.util.Scanner;
public class RelationalOperators {
private static Scanner sc;
public static void main(String[] args) {
int a, b;
sc = new Scanner(System.in);
System.out.println(" Please Enter two integer Value: ");
a = sc.nextInt();
b = sc.nextInt();
System.out.println(" Result of a > b is = " + (a > b));
System.out.println(" Result of a >= b is = " + (a >= b));
System.out.println(" Result of a < b is = " + (a < b));
System.out.println(" Result of a <= b is = " + (a <= b));
System.out.println(" Result of a == b is = " + (a == b));
System.out.println(" Result of a != b is = " + (a != b));
System.out.println(" \n\nAnurag\n1703233\n");
}
}

Anurag 14
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Logical Operators : These operators are used to perform “logical AND” and “logical OR”
operation, i.e. the function similar to AND gate and OR gate in digital electronics. One thing to
keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a
short-circuiting effect. Used extensively to test for several conditions for making a decision.
Conditional operators are-
 &&, Logical AND : returns true when both conditions are true.
 ||, Logical OR : returns true if at least one condition is true.

Example:
import java.util.*;
import java.lang.*;
class LogicalOperator
{
public static void main(String args[])
{
int x,y,z;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the Value of x : ");
x=scan.nextInt();
System.out.print("Enter the Value of y : ");
y=scan.nextInt();
System.out.print("Enter the Value of z : ");
z=scan.nextInt();
System.out.println("x>y and x>z : "+((x>y) &&(x>z)));
System.out.println(" x>y or y>z : "+ (x>y||y>z));
System.out.println("x not equal to z : "+(x!=z));
System.out.println("\n\nAnurag\n1703233\n");
}
}

Anurag 15
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Bitwise Operators : These operators are used to perform manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when performing update
and query operations of Binary indexed tree.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit by bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
compliment representation of the input value, i.e. with all bits inversed.

Example:-
import java.util.Scanner;
public class BitwiseOperator
{
public static void main(String[] args)
{
int m, n, x, a;
Scanner s = new Scanner(System.in);
System.out.print("Enter First number:");
m = s.nextInt();
System.out.print("Enter Second number:");
n = s.nextInt();
while(true)
{
System.out.println("");
System.out.println("Press 1 for Right Shift by 2:");
System.out.println("Press 2 for Left Shift by 2:");
System.out.println("Press 3 for Bitwise AND:");
System.out.println("Press 4 for Bitwise OR by 2:");
System.out.println("Press 5 for Bitwise Exclusive OR:");
System.out.println("Press 6 for Bitwise NOT:");
System.out.println("Press 7 to Exit:");
System.out.println("");
System.out.print("Option:");
x = s.nextInt();
switch(x)
{
case 1:
a = m << 2;
System.out.println("Result after left shift by 2:"+a);
break;
case 2:
a = n >> 2;
Anurag 16
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

System.out.println("Result after right shift by 2:"+a);


break;
case 3:
a = m & n;
System.out.println("Result after bitwise AND:"+a);
break;
case 4:
a = m | n;
System.out.println("Result after bitwise OR:"+a);
break;
case 5:
a = m ^ n;
System.out.println("Result after bitwise Exclusive OR:"+a);
break;
case 6:
a = ~ m;
System.out.println("Result after bitwise NOT:"+a);
break;
case 7:
System.exit(0);
}
System.out.println("\n\nAnurag\n1703233\n");
}
}
}
Output:-

Anurag 17
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Anurag 18
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

Ternary operator : Ternary operator is a shorthand version of if-else statement. It has three
operands and hence the name ternary. General format is-
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the ‘:’.
Example:-
import java.util.Scanner;
public class TernaryOperator {
private static Scanner sc;
public static void main(String[] args) {
int marks;
sc = new Scanner(System.in);
System.out.println(" Please Enter Your Marks: ");
marks = sc.nextInt();
String Message = (marks >= 70)? " You are eligible for Placement " :
" You are Not eligible for Placement ";
System.out.println(Message);
System.out.println("\n\nAnurag\n1703233\n");
}
}

Anurag 19
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

7.What are Jagged arrays? Explain with examples.

Answer:-Jagged array is array of arrays such that member arrays can be of different sizes, i.e.,
we can create a 2-D arrays but with variable number of columns in each row. These type of
arrays are also known as Jagged arrays.
Example:
class Main
{
public static void main(String[] args)
{
int arr[][] = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
System.out.println("Contents of 2D Jagged Array");
for (int i=0; i<arr.length; i++)
{
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Contents of 2D Jagged Array


012
34

8.Why Java is called platform independent?

Answer:-A programming language or technology is said to be platform independent if and


only if which can run on all available operating systems with respect to its development and
compilation. (Platform represents Operating System).

Java is a platform independent programming language, Because when you install jdk software
on your system then automatically JVM are installed on your system. For every operating
system separate JVM is available which is capable to read the .class file or byte code. When
we compile your Java code then .class file is generated by javac compiler these codes are
Anurag 20
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

readable by JVM and every operating system have its own JVM so JVM is platform
dependent but due to JVM java language is become platform independent.

Note: Java is platform independent but jvm is platform dependent.

9.Write various steps to develop compile and run Java program. Explain with example.

Answer:-Compile and Run Java Program

In the Java programming language, all source code is first written in plain text files and save with

the .java extension. After compilation, .class files are generated by javac compiler. A .class file

does not contain code that is native to your processor; it instead contains bytecodes (it is machine

language of the Java Virtual Machine1 (JVM)).

Anurag 21
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

The java launcher tool then runs your application with an instance of the Java Virtual Machine
(JVM).

Steps For compile Java Program

 First Save Java program with same as class name with .java extension.
Example: Sum.java
 Compile: javac Filename.java
Example, javac Sum.java

Note: Here javac is tools or application programs or exe files which is used for Compile the
Java program.

Steps For Run Java Program

 For run java program use java tool.


 Run by: java Filename
Example: java sum

Note: Here java is tools or application programs or exe files which is used for run the Java
program.

Steps For compiling and executing the java program

The following sequence of steps represented in the diagram use compiling the java program
and executing the java programs.

Anurag 22
1703233
“DEPARTMENT OF INFORMATION TECHNOLOGY”

In the above diagram javac and java are called tools or application programs or exe files
developed by sun micro system and supply as a part of jdk 1.5/1.6/1.7 in bin folder (starting
directory of java is called java home directory).

Anurag 23
1703233

You might also like