Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
44 views

Programming Home Work 2

This document provides an overview of object-oriented programming concepts in Java including data types, variables, operators, and type casting. It discusses both primitive and non-primitive data types, describing their characteristics and examples. Primitive data types covered are integer, floating point, boolean, and char types. The document also reviews numeric types, strings, and type casting between primitive types.

Uploaded by

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

Programming Home Work 2

This document provides an overview of object-oriented programming concepts in Java including data types, variables, operators, and type casting. It discusses both primitive and non-primitive data types, describing their characteristics and examples. Primitive data types covered are integer, floating point, boolean, and char types. The document also reviews numeric types, strings, and type casting between primitive types.

Uploaded by

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

LAB MANUAL 2

OBJECT OREINTED PROGRAMMING


LECTURER: SAYED NAJMUDDIN “SADAAT”

1. Introducti on
In this practical you learn basics of java such as Variables, Data Types and other basics activities.
Data types are divided into two groups:
 Primitive data types - includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes
PRIMITIVE DATA TYPES
A primitive data type specifies the size and type of variable values, and it has no additional methods.
There are eight primitive data types in Java:
Data Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values

Non-primitive
NON-PRIMITIVE data types
DATA are called reference types because they refer to objects.
TYPES
The main difference between primitive and non-primitive data types are:
 Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
 Non-primitive types can be used to call methods to perform certain operations, while primitive types
cannot.
 A primitive type has always a value, while non-primitive types can be null.
 A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase letter.
 The size of a primitive type depends on the data type, while non-primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

Primitive
NUMBERSnumber types are divided into two groups:
(PRIMITIVES)
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid
types are byte, short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
Even though there are many numeric types in Java, the most used for numbers are int (for whole numbers)
and double (for floating point numbers).

int myNum = 5; // Integer (whole number)

Page 1 of 4
float myFloatNum = 5.99f; // Floating point number

char myLetter = 'D'; // Character

boolean myBool = true; // Boolean

String myText = "Hello"; // String

Page 2 of 4
INTEGER TYPES

Byte The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other integer types
to save memory when you are certain that the value will be within -128 and 127:
Short
The short data type can store whole numbers from -32768 to 32767:
Int The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our tutorial,
the int data type is the preferred data type when we create variables with a numeric value.
Long The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. This is used
when int is not large enough to store the value. Note that you should end the value with an "L":
FLOATING POINT TYPES
You should use a floating-point type whenever you need a number with a decimal, such as 9.99 or 3.14515.
FLOAT
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end the value
with
an "f":
DOUBLE
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should end the value
with a "d":
Which one to use Float or Double?
The precision of a floating-point value indicates how many digits the value can have after the decimal
point. The precision of float is only six or seven decimal digits, while double variables have a precision of
about 15 digits.
Therefore, it is safer to use double for most calculations.
SCIENTIFIC NUMBERS
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
float f1 = 35e3f; double d1 =
12E4d; System.out.println(f1);
System.out.println(d1); char
myGrade = 'B';
System.out.println(myGrade);

BOOLEANS A boolean data type is declared with the boolean boolean isJavaFun = true; boolean
keyword and can only take the values true or false: isFishTasty = false;
System.out.println(isJavaFun);
Boolean values are mostly used for conditional testing, System.out.println(isFishTasty);
CHARACTE The char data type is used to store a single character. char myGrade = 'B';
RS The character must be surrounded by single quotes, System.out.println(myGrade);
like
'A' or 'c':
Alternatively, you can use ASCII values to display certain characters:

char a = 65, b = 66, c = 67; Some examples >62 greater-than


System.out.println(a); A 65 uppercase A
B 66 uppercase B
System.out.println(b); ? 63 question mark
@ 64 at sign
System.out.println(c); a 97 lowercase a
b 98 lowercase b
STRINGS
The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes:

String message = "This is A string in Page 3 of 4


Java"; System.out.println(message);
The String type is so much used and integrated in Java, that some call it "the special ninth type".
A String in Java is actually a non-primitive data type, because it refers to an object. The String object has methods that are used
to perform certain operations on strings.

Page 4 of 4
JAVA TYPE CASTING
Type casting is when you assign a value of one primitive data type to another
type. In Java, there are two types of casting:
 Widening Casting (automatically) - converting a smaller type to a larger type
size byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size
type double -> float -> long -> int -> char -> short -> byte

public class Main {


WIDENING CASTING public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
Widening casting is done automatically
System.out.println(myInt); // Outputs 9
when passing a smaller size type to a System.out.println(myDouble); // Outputs 9.0
larger size type: }
}
public class Main {
NARROWING CASTING public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to
Narrowing casting must be done int System.out.println(myDouble); // Outputs 9.78
manually by placing the type in System.out.println(myInt); // Outputs 9
parentheses in front of the value: }
}
JAVA OPERATORS
Operators are used to perform operations on variables and
values. Java divides the operators into the following groups:
ARITHMETIC + Addition Adds together two values x+y
OPERATORS - Subtraction Subtracts one value from another x-y
* Multiplication Multiplies two values x*y
Arithmetic operators are
/ DivisionDivides one value by another x/y
used to perform common
% Modulus Returns the division remainder x%y
mathematical operations.
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x
= x=5 x=5 &= x &= 3 x = x & 3
ASSIGNMENT
+= x += 3 x = x + 3 |= x |= 3 x = x | 3
OPERATORS
-= x -= 3 x = x - 3 ^= x ^= 3 x = x ^ 3
Assignment operators are *= x *= 3 x = x * 3 >>= x >>= 3 x = x >> 3
used to assign values to /= x /= 3 x = x / 3 <<= x <<= 3 x = x << 3
variables. %= x %= 3 x = x % 3
COMPARISON == Equal to x == y < Less than x<y
OPERATORS != Not equal x != y >= Greater than or equal to x >= y
Comparison operators > Greater than x > y <= Less than or equal to x <= y
are used to compare two
values:
LOGICAL OPERATORS && Logical and Returns true if both statements are true x < 5 && x < 10
Logical operators are
|| Logical or Returns true if one of the statements is true x < 5 || x < 4
! Logical not Reverse the result, returns false if it is true !(x < 5 && x < 10)
used to determine the
logic between variables
or values:
BITWISE OPERATORS & Bitwise AND Operator 4&3 =>
| Bitwise AND Operator 5|3 =>
^ Bitwise AND Operator 9^3 =>
>> Bitwise AND Operator 12 >> 2 =>
<< Bitwise AND Operator 16 << 3 =>

Page 5 of 4
Java Simple Programs
//Java Program to check Even or Odd Output 1:
number import java.util.Scanner;
class CheckEvenOdd{
public static void main(String args[]) { int Enter an Integer number:
num; 78
Entered number is even
System.out.println("Enter an Integer number:");
Output 2:
//The input provided by user is stored in num
Scanner input = new Scanner(System.in);
num = input.nextInt(); Enter an Integer number:
/* If number is divisible by 2 then it's an even 77
number * else odd number*/ Entered number is odd
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
//Program to check whether the input year is leap or not Here we will write a java program to
import java.util.Scanner; check whether the input year is a leap
public class Demo { year or not. Before we see the program,
public static void main(String[] args) { int lets see how to determine whether a
year; year is a leap year mathematically:
Scanner scan = new To determine whether a year is a leap
Scanner(System.in); year, follow these steps:
System.out.println("Enter any Year:"); 1. If the year is evenly divisible by 4, go to step
year = scan.nextInt(); 2. Otherwise, go to step 5.
scan.close(); 2. If the year is evenly divisible by 100, go
boolean isLeap = false; to step 3. Otherwise, go to step 4.
if(year % 4 == 0) { 3. If the year is evenly divisible by 400, go
if( year % 100 == 0) { to step 4. Otherwise, go to step 5.
if ( year % 400 == 0) 4. The year is a leap year (it has 366 days).
isLeap = true; 5. The year is not a leap year (it has 365 days).
else
isLeap = false; Output:
}
else Enter any Year:
isLeap = true; 2001
}else { 2001 is not a Leap Year.
isLeap = false;
}
if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}

//Program to calculate power of a number using for loop In this program we are calculating the
public class JavaExample { power of a given number using for loop.
public static void main(String[] args) {
//Here number is the base and p is the exponent Here number is the base and p is the power
int number = 2, p = 5; (exponent). So we are calculating the result
long result = 1; of number^p.Program to calculate power of
//Copying the exponent value to the loop counter a number using pow() function In the above
int i = p; two programs, we have seen how to
for (;i != 0; --i) calculate power of a number using loops. In
{ the following program, we are using pow()
result *= number;
Page 6 of 4
} function to calculate power.
//Displaying the output public class JavaExample {
System.out.println(number+"^"+p+" = "+result);
} public static void main(String[] args)
} { int number = 10, p = 3;
double result =
Math.pow(number, p);
System.out.println(number+"^"+p
+" =
"+result);
}
}

Page 7 of 4

You might also like