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

Java Tutorial 2

The document discusses the different data types available in Java, including primitive and non-primitive types. It provides details on each primitive type such as boolean, byte, short, int, long, float, double, and char. It also discusses non-primitive types including strings, classes, interfaces, and arrays.

Uploaded by

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

Java Tutorial 2

The document discusses the different data types available in Java, including primitive and non-primitive types. It provides details on each primitive type such as boolean, byte, short, int, long, float, double, and char. It also discusses non-primitive types including strings, classes, interfaces, and arrays.

Uploaded by

pkcking2
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

JAVA TUTORIAL 2ND

Q.1 Which are the data types available in java? Explain

Ans-Data types in Java are of different sizes and values that can be stored in the
variable that is made as per convenience and circumstances to cover up all test cases.
Java has two categories in which data types are segregated

Primitive data structure Non-primitive data structure

It is a kind of data structure that stores the It is a type of data structure that can store the
data of only one type. data of more than one type.

Examples : integer, character, float. Examples : Array, Linked list, stack.

It contain some value, i.e., it cannot be It consists of a NULL value.


NULL.

The size depends on the type of the data In case of non-primitive data structure, size is not
structure. fixed.

It starts with a lowercase character. It starts with an uppercase character.

It can be used to call the methods. It cannot be used to call the methods.

Primitive Data Types in Java


Primitive data are only single values and have no special capabilities. There are 8
primitive data types.
JAVA TUTORIAL 2ND
such as boolean, char, int, short, byte, long, float, and double

1. Boolean Data Type

Boolean data type represents either true or false which is intended to represent the
two truth values of Boolean algebra, but the size of the boolean data type is virtual
machine-dependent. Values of type boolean are not converted implicitly or
explicitly (with casts) to any other type. But the programmer can easily write
conversion code.

2. Byte Data Type

The byte data type is an 8-bit signed two’s complement integer. The byte data type is
useful for saving memory in large arrays.

3. Short Data Type


The short data type is a 16-bit signed two’s complement integer. Similar to byte, use
a short to save memory in large arrays, in situations where the memory savings
actually matters.

4. Integer Data Type


It is a 32-bit signed two’s complement integer.
JAVA TUTORIAL 2ND
5. Long Data Type
The range of a long is quite large. The long data type is a 64-bit two’s complement
integer and is useful for those occasions where an int type is not large enough to
hold the desired value. The size of the Long Datatype is 8 bytes (64 bits).
6. Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point
numbers. The size of the float data type is 4 bytes (32 bits).
7. Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice. The size of the double
data type is 8 bytes or 64 bits.
8. Char Data Type
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).

Non-Primitive Data Type or Reference Data Types


The Non Primintive data types will contain a memory address of variable values
because the this types won’t store the variable value directly in memory. They are
strings, objects, arrays, etc.

1. Strings
Strings are defined as an array of characters. The difference between a character
array and a string in Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character array is a collection of separate
char-type entities. Unlike C/C++, Java strings are not terminated with a null
character.

2. Class
A class is a user-defined blueprint from which objects are created. It represents the
set of properties or methods that are common to all objects of one type. In general,
class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access.
2. Class name: The name should begin with an initial letter
3. Superclass(if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass) one
parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
5. Body: The class body is surrounded by braces, { }.
JAVA TUTORIAL 2ND
3. Interface
Like a class, an interface can have methods and variables, but the methods declared
in an interface are by default abstract
 Interfaces specify what a class must. It is the blueprint of the class.
 An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move().
So it specifies a set of methods that the class has to implement.
 If a class implements an interface and does not provide method bodies for
all functions specified in the interface, then the class must be declared
abstract.
 A Java library example is Comparator Interface. If a class implements this
interface, then it can be used to sort a collection.
4. Array
An Array is a group of like-typed variables that are referred to by a common name.
Arrays in Java work differently than they do in C/C++. The following are some
important points about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Since arrays are objects in Java, we can find their length using member
length. This is different from C/C++ where we find length using size.
 A Java array variable can also be declared like other variables with [] after
the data type.
 The variables in the array are ordered and each has an index beginning
with 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
 The size of an array must be specified by an int value and not long or
short.
 The direct superclass of an array type is Object.
 Every array type implements the
interfaces Cloneable and java.io.Serializable .

Q.2 Write the usage of import statement

The import statement can be used to import an entire package or sometimes import certain
classes and interfaces inside the package. The import statement is written before the class
definition and after the package statement(if there is any). Also, the import statement is
optional.
A program that demonstrates this in Java is given as follows:

Example
Live Demo

import java.util.LinkedList;
JAVA TUTORIAL 2ND
public class Demo {
public static void main(String[] args) {
LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Cherry");
l.add("Orange");
l.add("Pear");
System.out.println("The LinkedList is: " + l);
}
}

Output
The LinkedList is: [Apple, Mango, Cherry, Orange, Pear]

Q.3 Define java tokens.

The Java compiler breaks the line of code into text (words) is called Java tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Special Symbols
5. Operators
1. Keyword: Keywords are pre-defined or reserved words in a
programming language. Each keyword is meant to perform a
specific function in a program. Since keywords are referred names
for a compiler, they can’t be used as variable names because by
doing so, we are trying to assign a new meaning to the keyword
which is not allowed. Java language supports following keywords:

2 Identifiers: Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user-defined names consisting of an arbitrarily long
sequence of letters and digits with either a letter or the underscore(_) as a first
character. Identifier names must differ in spelling and case from any keywords. You
cannot use keywords as identifiers; they are reserved for special use. Once declared,
you can use the identifier in later program statements to refer to the associated value.
A special kind of identifier, called a statement label, can be used in goto statements.
Examples of valid identifiers :
JAVA TUTORIAL 2ND
3 Constants/Literals: Constants are also like normal variables. But, the only
difference is, their values can not be modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals.
Constants may belong to any of the data type.

4 Special Symbols: The following special symbols are used in Java having some
special meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =
 Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
 Parentheses(): These special symbols are used to indicate function calls
and function parameters.
 Braces{}: These opening and ending curly braces marks the start and end
of a block of code containing more than one executable statement.
 comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
 semi colon : It is an operator that essentially invokes something called an
initialization list.
 asterick (*): It is used to create pointer variable.
 assignment operator: It is used to assign values.

5Operators: 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. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
10. Precedence and Associativity

Q.4 What are string functions in java

A number of methods provided in Java to perform operations in


Strings are called String functions. The methods are compare(),
concat(), equals(), split(), length(), replace(), compareTo() and so on.
Strings in Java are constant, and it is created either using a literal or
using a keyword. String literal is used to make Java memory efficient,
JAVA TUTORIAL 2ND
and the keyword creates Java string in normal memory. The string
represents an array of character values, and the class is implemented
by three interfaces such as Serializable, Comparable, and
CharSequence interfaces. It represents the sequence of characters in a
serialized or comparable manner.

Java String compareTo()


Compares two strings in the dictionary order
Java String equals()
Compares two strings
Java String concat()
Concatenates two strings and returns it
Java String split()
Splits the string at the specified string (regex)
Java String compareTo()
Compares two strings in the dictionary order
Java String split()
Splits the string at the specified string (regex)
Java String compareTo()
Compares two strings in the dictionary order

5 Discuss various loop statements and branching statements available in Java? Show their syntax.

Looping is a feature which facilitates the execution of a set of instructions repeatedly


while some condition evaluates to true. Java provides three ways for executing the
loops.

There Are 3 Types Of Loops In Java-:


1-While Loop
2-For Loop
3-Do While

1 For Loops In Java-:

A for loop is a single-line command that will be executed repeatedly


These Loops Is A Concise Way Of Writing The Loop Structure. For Loop Starts With
The For Keyword And Then We Have To Enter The Initialization, Condition, And Then
JAVA TUTORIAL 2ND
Increment And Decrement It. For Example, Let Print Table Of 2 With The Help Of For
Loop.

2 While Loops In Java:-\

While loops can be single-lined or contain multiple commands for a


single condition.
While Loop Executes The Codes Repeatedly Based On The Boolean Condition We Give. In
The While Loop, We Increment The Or Decrement Code After Writing The Whole Code.

3 Do-While Loops In Java


Do While Loop Executes The Code Block Once And Then Checks If The Given Condition
True. So, The Do While Loop Will Execute The Code Block At Least One Time.

BRANCHING STATEMENT

Break And Continue Statements Are Known As Branching Statements Or Jump Statements.
These Statements Can Be Used Inside Any Loop(For,Do-While, While).
These Statements Are Used To Skip Some Statements Or Immediately Terminate The Loop
When The Condition Is Satisfied.

Break-
Break Statement Terminates From The Loop Immediately. When The Compiler Detects
The Break Statement It Stops The Iteration Of The Loop There And Returns To The First
Statement After The Loop.
Syntax:-
Suppose We Have Numbers From 1-20 And We Want To Print The First 10 Numbers. So, We Can Do
This By Using Break Statement.

Continue Statement
Continue Statement Is Used To Skip The Iteration Of The Loop.

For Example, If We Want To Print Numbers From 1-20 But We Don’t Want To Print A
Particular Number Say 11. This Can Be Done Either By Looping Twice Or By Using The
Continue Statement.

The return Statement


JAVA TUTORIAL 2ND
The return statement is also a branching statement, which allows us to explicitly
return value from a method.

6 Discuss various operators and expression available in java ‘

Operator in Java is a symbol that is used to perform operations

o Arithmetic Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.

1 Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

2 Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.

3Relational Operators in Java are used to comparing two variables for equality, non-equality,
greater than, less than, etc. Java relational operator always returns a boolean value - true or
false.
4A bitwise operator in Java is a symbol/notation that performs a specified operation on standalone
bits, taken one at a time. It is used to manipulate individual bits of a binary number and can be used
with a variety of integer types – char, int, long, short, byte.

5 Logical operators can be defined as a type of operators that help us to combine multiple conditional
statements. There are three types of logical operators in Java: AND, OR and NOT operators.

 AND operator returns true when both conditions under evaluation are true, otherwise it returns
false. Tt=t
 OR operator returns true if any one of the given conditions is true. OR operator returns false if and
only if both conditions under evaluation are false. Tf=t ff=f
 NOT operator accepts a single value as an input and returns the inverse of the same. This is a unary
operator unlike the AND and OR operators.

*******************Q.7 What is the difference between a class and an object?

Class Object

Class is the blueprint of an object. It is


Object is an instance of class.
used to declare and create objects.

No memory is allocated when a class Memory is allocated as soon as an


JAVA TUTORIAL 2ND
is declared. object is created.

Object is a real-world entity such as


A class is a group of similar objects.
book, car, etc.

Class is a logical entity. Object is a physical entity.

Object can be created many times as


Class can only be declared once.
per requirement.

Objects of the class car can be BMW,


Example of class can be car.
Mercedes, jaguar, etc.

Q.8 How do you swap two numbers without using a third variable in Java?
X= 25 (First number), Y= 23 (second number)
Swapping Logic:
X = X + Y = 25 +23 = 48
Y = X - Y = 48 - 23 = 25
X = X -Y = 48 - 25 = 23
and the numbers are swapped as X =23 and Y =25.

Algorithm
o STEP 1: START
o STEP 2: ENTER x, y
o STEP 3: PRINT x, y
o STEP 4: x = x + y
o STEP 5: y= x - y
o STEP 6: x =x - y
o STEP 7: PRINT x, y
o STEP 8: END

You might also like