0% found this document useful (0 votes)
8 views18 pages

Java Data Types Explained

Uploaded by

learnwithsalar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views18 pages

Java Data Types Explained

Uploaded by

learnwithsalar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Learn Basic Programs

By Salar Mastoi

[Type the abstract of the document here. The abstract is typically a short summary of the contents of the document. T
IN JAVA, DATA TYPES SPECIFY THE SIZE AND TYPE OF VALUES THAT CAN
BE STORED IN VARIABLES. JAVA HAS TWO CATEGORIES OF DATA TYPES:
PRIMITIVE DATA TYPES AND REFERENCE DATA TYPES.

1. PRIMITIVE DATA TYPES:


- NUMERIC TYPES:
- `BYTE`: 8-BIT SIGNED INTEGER. RANGE: -128 TO 127.
- `SHORT`: 16-BIT SIGNED INTEGER. RANGE: -32,768 TO 32,767.
- `INT`: 32-BIT SIGNED INTEGER. RANGE: -2^31 TO 2^31 - 1.
- `LONG`: 64-BIT SIGNED INTEGER. RANGE: -2^63 TO 2^63 - 1.
- `FLOAT`: 32-BIT FLOATING-POINT. EXAMPLE: 3.14F.
- `DOUBLE`: 64-BIT FLOATING-POINT. EXAMPLE: 3.14.
- **BOOLEAN TYPE**:
- `BOOLEAN`: REPRESENTS TRUE OR FALSE.
- **CHARACTER TYPE**:
- `CHAR`: 16-BIT UNICODE CHARACTER. EXAMPLE: 'A', '\U0041'.
2. **REFERENCE DATA TYPES**:
- **CLASSES**: USER-DEFINED DATA TYPES.
- **INTERFACES**: LIKE CLASSES BUT WITH ONLY METHOD
DECLARATIONS .

- **ARRAYS**: COLLECTIONS OF ELEMENTS OF THE SAME TYPE.


HERE'S AN EXAMPLE DEMONSTRATING THE DECLARATION
AND USAGE OF DIFFERENT DATA TYPES:

PUBLIC CLASS DATATYPESEXAMPLE {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
// PRIMITIVE DATA TYPES
BYTE B = 10;
SHORT S = 100;
INT I = 1000;
LONG L = 100000L; // NOTE: L OR L SUFFIX TO
INDICATE LONG

FLOAT F = 3.14F; // NOTE: F OR F SUFFIX TO


INDICATE FLOAT

DOUBLE D = 3.14159;
BOOLEAN BOOL = TRUE;
CHAR C = 'A';
// REFERENCE DATA TYPES
STRING STR = "HELLO, WORLD!";
INT[] ARR = {1, 2, 3, 4, 5};
PUBLIC CLASS FIRST {
PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
[Link]("HELLO, WORLD!");
}
}

PUBLIC CLASS SECOND {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
[Link]("BS DATA SCIENCE!");
}
}

PUBLIC CLASS THIRD {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
[Link]("SALAR HERE PROGRAMMER!");
}
}
IMPORT [Link];

PUBLIC CLASS ADDITION {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
SCANNER SCANNER = NEW SCANNER([Link]);

[Link]("ENTER FIRST NUMBER: ");


INT NUM1 = [Link]();

[Link]("ENTER SECOND NUMBER: ");


INT NUM2 = [Link]();

INT SUM = NUM1 + NUM2;

[Link]("SUM: " + SUM);

[Link]();

}
}
IMPORT [Link] ;

PUBLIC CLASS NUMBERCHECK {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {

SCANNER SCANNER = NEW SCANNER([Link]);

[Link]("ENTER A NUMBER: ");

INT NUM = [Link]();

IF (NUM % 2 == 0) {

[Link](NUM + " IS EVEN.");

} ELSE {

[Link](NUM + " IS ODD.");

IF (NUM > 0) {

[Link](NUM + " IS POSITIVE.");

} ELSE IF (NUM < 0) {

[Link](NUM + " IS NEGATIVE.");

} ELSE {

[Link](NUM + " IS NEITHER POSITIVE NOR NEGATIVE.");

SCANNER .CLOSE();

IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS GRADESYSTEM {


PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);

S [Link]("ENTER MARKS OBTAINED (OUT OF 100): ");

INT MARKS = [Link]();

CHAR GRADE = CALCULATE GRADE(MARKS);

S [Link]("GRADE: " + GRADE);

SCANNER .CLOSE ();

PUBLIC STATIC CHAR CALCULATE GRADE ( INT MARKS ) {

CHAR GRADE ;

IF (MARKS >= 90) {

GRADE = 'A';

} ELSE IF (MARKS >= 80) {

GRADE = 'B';

} ELSE IF (MARKS >= 70) {

GRADE = 'C';

} ELSE IF (MARKS >= 60) {

GRADE = 'D';

} ELSE IF (MARKS >= 50) {

GRADE = 'E';

} ELSE {

GRADE = 'F';

RETURN GRADE ;

IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS CALCULATOR {


PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);

S [Link]("ENTER FIRST NUMBER: ");

DOUBLE NUM 1 = [Link]();

S [Link]("ENTER SECOND NUMBER: ");

DOUBLE NUM 2 = [Link]();

S [Link]("ENTER OPERATOR (+, -, *, /): ");

CHAR OPERATOR = [Link]().CHARAT(0);

DOUBLE RESULT ;

SWITCH (OPERATOR ) {

CASE '+':

RESULT = NUM1 + NUM2;

BREAK ;

CASE '-':

RESULT = NUM1 - NUM2;

BREAK ;

CASE '*':

RESULT = NUM1 * NUM2;

BREAK ;

CASE '/':

IF (NUM 2 != 0) {

RESULT = NUM1 / NUM2;


} ELSE {

S [Link]("ERROR: DIVISION BY ZERO!");

RETURN ;

BREAK ;

DEFAULT :

S [Link]("ERROR: INVALID OPERATOR !");

RETURN ;

S [Link]("RESULT: " + RESULT);

SCANNER .CLOSE ();

FOR LOOP PROGRAM - PRINT NUMBERS FROM 1 TO 10:

PUBLIC CLASS F ORLOOP EXAMPLE {

PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

FOR (INT I = 1; I <= 10; I++) {

S [Link](I + " ");

WHILE LOOP PROGRAM - PRINT NUMBERS FROM 1 TO 100:

PUBLIC CLASS WHILELOOPEXAMPLE {


PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

INT I = 1;

WHILE (I <= 100) {

S [Link](I + " ");

I++;

FOR LOOP PROGRAM - PRINT MULTIPLICATION TABLE:

IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS MULTIPLICATION TABLE {

PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);

S [Link]("ENTER A NUMBER: ");

INT NUM = [Link]();

S [Link]("MULTIPLICATION TABLE OF " + NUM + ":");

FOR (INT I = 1; I <= 10; I++) {

S [Link](NUM + " X " + I + " = " + ( NUM * I));

SCANNER .CLOSE ();

IMPORT [Link];

PUBLIC CLASS MULTIPLICATIONTABLE {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
SCANNER SCANNER = NEW SCANNER([Link]);
[Link]("ENTER A NUMBER: ");
INT NUM = [Link]();

[Link]("MULTIPLICATION TABLE OF " + NUM


+ ":");

INT I = 1;
WHILE (I <= 10) {
[Link](NUM + " X " + I + " = " + (NUM *
I));

I++;

[Link]();

}
}

IMPORT [Link];

PUBLIC CLASS RANGEPRINTER {


PUBLIC STATIC VOID MAIN(STRING[] ARGS) {
SCANNER SCANNER = NEW SCANNER([Link]);
S [Link]("ENTER THE STARTING
NUMBER: ");

INT START = [Link]();


[Link]("ENTER THE ENDING NUMBER: ");
INT END = [Link]();
[Link]("NUMBERS WITHIN THE RANGE
" + START + " TO " + END + ":");
FOR (INT I = START; I <= END; I++) {
[Link](I + " ");
}

[Link]();

}
}
IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS DAYSMONTHSSEASONS {

PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);


S [Link]("ENTER A MONTH NUMBER (1-12): ");

INT MONTH = [Link]();

S TRING SEASON;

INT DAYS ;

SWITCH (MONTH ) {

CASE 1: CASE 3: CASE 5: CASE 7: CASE 8: CASE 10: CASE 12:

SEASON = "W INTER";

DAYS = 31;

BREAK ;

CASE 4: CASE 6: CASE 9: CASE 11:

SEASON = "SUMMER ";

DAYS = 30;

BREAK ;

CASE 2:

SEASON = "SPRING";

DAYS = 28; // A SSUMING NON-LEAP YEAR FOR SIMPLICITY

BREAK ;

DEFAULT :

S [Link]("INVALID MONTH NUMBER!");

SCANNER .CLOSE ();

RETURN ;

S [Link]("NUMBER OF DAYS IN MONTH " + MONTH + ": " + DAYS);

S [Link]("SEASON: " + SEASON);

SCANNER .CLOSE ();


}

IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS DAYOFWEEK {

PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);

S [Link]("ENTER A NUMBER CHECK DAY OF THE WEEK (1-7): ");

INT DAY NUMBER = [Link]();

S TRING DAY;

SWITCH (DAY NUMBER ) {

CASE 1:

DAY = "M ONDAY";

BREAK ;

CASE 2:

DAY = "TUESDAY";

BREAK ;

CASE 3:

DAY = "W EDNESDAY";

BREAK ;

CASE 4:

DAY = "THURSDAY";

BREAK ;

CASE 5:

DAY = "FRIDAY";

BREAK ;

CASE 6:
DAY = "SATURDAY";

BREAK ;

CASE 7:

DAY = "SUNDAY";

BREAK ;

DEFAULT :

DAY = "INVALID DAY NUMBER";

S [Link]("ACCORDING YOUR NUMBER " + DAYNUMBER + " IS: " + DAY);

SCANNER .CLOSE ();

IMPORT JAVA .UTIL .S CANNER ;

PUBLIC CLASS MONTHOFYEAR {

PUBLIC STATIC VOID MAIN (S TRING [] ARGS ) {

S CANNER SCANNER = NEW SCANNER([Link]);

S [Link]("ENTER A NUMBER THE MONTH OF THE YEAR (1-12): ");

INT MONTH NUMBER = [Link]();

S TRING GREGORIANMONTH;

S TRING ISLAMICMONTH;

SWITCH (MONTH NUMBER ) {

CASE 1:

GREGORIAN MONTH = "JANUARY";

ISLAMIC MONTH = "M UHARRAM";


BREAK ;

CASE 2:

GREGORIAN MONTH = "FEBRUARY";

ISLAMIC MONTH = "SAFAR";

BREAK ;

CASE 3:

GREGORIAN MONTH = "M ARCH";

ISLAMIC MONTH = "RABI' AL-AWWAL";

BREAK ;

CASE 4:

GREGORIAN MONTH = "A PRIL";

ISLAMIC MONTH = "RABI' AL-THANI";

BREAK ;

CASE 5:

GREGORIAN MONTH = "M AY";

ISLAMIC MONTH = "JUMADA AL-AWWAL";

BREAK ;

CASE 6:

GREGORIAN MONTH = "JUNE";

ISLAMIC MONTH = "JUMADA AL-THANI";

BREAK ;

CASE 7:

GREGORIAN MONTH = "JULY";

ISLAMIC MONTH = "RAJAB";

BREAK ;

CASE 8:

GREGORIAN MONTH = "A UGUST";


ISLAMIC MONTH = "SHA'BAN";

BREAK ;

CASE 9:

GREGORIAN MONTH = "SEPTEMBER";

ISLAMIC MONTH = "RAMADAN";

BREAK ;

CASE 10:

GREGORIAN MONTH = "OCTOBER";

ISLAMIC MONTH = "SHAWWAL";

BREAK ;

CASE 11:

GREGORIAN MONTH = "NOVEMBER";

ISLAMIC MONTH = "DHU AL-QI'DAH";

BREAK ;

CASE 12:

GREGORIAN MONTH = "DECEMBER";

ISLAMIC MONTH = "DHU AL-HIJJAH";

BREAK ;

DEFAULT :

GREGORIAN MONTH = "INVALID MONTH NUMBER";

ISLAMIC MONTH = "INVALID MONTH NUMBER";

S [Link]("GREGORIAN MONTH TO THE NUMBER " + MONTHNUMBER + " IS: " +


GREGORIAN MONTH);

S [Link]("ISLAMIC MONTH TO THE NUMBER " + MONTHNUMBER + " IS: " +


ISLAMIC MONTH);

SCANNER .CLOSE ();

}
}

Common questions

Powered by AI

Loops in Java, such as 'for', 'while', and 'do-while', provide powerful ways to automate repetitive tasks efficiently. For instance, they can iterate over collections of data, execute code blocks a specific number of times, or continue executing while specified conditions hold true. A 'for' loop can be used to print numbers from 1 to 10, while a 'while' loop might continually check a condition until it becomes false. This ability to repeat operations without redundant code is crucial for writing scalable, maintainable, and less error-prone Java applications .

A 'for' loop is suited for cases where the number of iterations is predetermined, as its init and update expressions provide clear iteration control. An example would be iterating over an array where the index bounds are known. A 'while' loop, however, excels in situations where the termination condition depends on dynamic factors not predetermined, such as reading user input until a specific value is entered. This makes it favorable when the exact count is uncertain at the loop's start .

Using a 'switch' statement in a menu-driven console application in Java can be very effective due to its ability to select a path of execution based on the value of a single variable. This structure increases readability and maintainability compared to multiple 'if-else' statements, especially when dealing with discrete choices such as picking an operation type in a calculator . However, it is limited to integral types and strings, which may necessitate working around its constraints or using more dynamic control structures like 'if-else' chains when dealing with more complex conditions or variable types .

Arrays in Java are reference data types that store collections of elements of the same type, providing fast access based on index and ideal for fixed-size collections or when performance is a priority. Classes, on the other hand, are user-defined data types that encapsulate data and behavior. They offer more flexibility than arrays by allowing attributes to be of different types, making them suitable for modeling complex data structures with methods for data manipulation .

The Java 'Scanner' class is a flexible, convenient method for parsing input from various input streams like keyboard (System.in). It simplifies reading different data types and handling user input in console-based applications. However, it suffers from common pitfalls, such as issues with buffer cleaning between different types of input and potential performance inefficiencies due to significant overhead, especially when parsing large amounts of data .

'Try-catch' blocks are preferable in scenarios where exceptions cannot be avoided through simple condition checks, such as when dealing with I/O operations or other unpredictable runtime situations. They enable graceful handling and recovery from errors like file not found or invalid input, where the program can execute corrective actions or fallback procedures. Conversely, for predictable conditions like value range checks, using conditional statements can prevent errors more efficiently without the overhead of exceptions .

A programmer might choose 'double' over 'float' in Java for high precision calculations because a 'double' is a 64-bit floating-point data type, providing roughly double the precision compared to a 32-bit 'float'. This extra precision helps in minimizing rounding errors in complex calculations, which is crucial in applications requiring high accuracy .

Choosing appropriate data types in Java numerical operations is crucial for avoiding overflow errors. For instance, using 'int' for calculations potentially exceeding its range [-2^31 to 2^31-1] risks overflow. Opting for 'long' extends the range significantly (-2^63 to 2^63-1), providing a solution for larger numbers. However, even 'long' may be insufficient, requiring BigInteger for very high precision needs. These choices ensure that operations do not wrap around and produce erroneous results, especially in computational tasks with large datasets or mathematical computations .

In scientific computations, the precision of 'float' and 'double' in Java can significantly affect accuracy and reliability. The inherent imprecision of floating-point arithmetic, due to binary representation of decimal numbers, can lead to small errors being magnified in iterative calculations. Choosing 'double' over 'float' often improves accuracy but does not eliminate these limitations entirely. High precision libraries or BigDecimal may be necessary for critical applications such as simulations or financial calculations where precision losses could compromise results .

Java's type system, which is based on both primitive and reference data types, ensures type safety and maintains the integrity of structured data. Primitive data types like int, char, and boolean provide basic operations and are directly operated upon by the JVM. Reference types, such as classes and interfaces, support user-defined data types and encapsulate complex data structures and behaviors .

You might also like