Day 6 : Variables( 2 )

Chi-Tse Chiang
2022-09-21 04:16:13

Primitive v.s Non-Primitive

Different variables are stored in memory in different ways. In Java, we can simply divide the data types of variables into two types:

Primitive Data Types

Non-Primitive Data Types

Primitive

As the name suggests, they are immutable (immutable) variables that have been defined (predfined) in Java. They are processed using the code-by-value method, which means that their values (stack memory addresses) are directly copied when passed in memory.
-> Includes: numbers (integers and decimals), characters char, Boolean boolean

Non-Primitive

Also known as Reference Types / Object type, because the way it stores values in memory is by reference (heap memory address). It is not defined in advance in Java and needs to be created by the programmer.
-> Includes: String*, Array*, Classes*, etc.

Difference

1. Primitives are already defined, and non-primitives need to be designed.

2. Non-primitives can be used to call functions to execute operating procedures, while primitives cannot.

3. Primitive data type variables always have a value, while non-primitives can be null (NULL).

4. The size of a primitive variable depends on its type, while non-primitives are all the same size.

String Methods

Now we know that a String is a class in Java that is made up of a sequence of characters. Then provide some practical keywords to make the use of strings more flexible!!!

length() Calculate the length of a string

String code = "Hello World!";
System.out.println( code.length() );     //Output : 12

Program analysis: When calculating the length of a string, spaces and punctuation are included. And remember to add a period (.) before a keyword when you want to use a command.

toUpperCase() & toLowerCase() Convert all words to upper or lower case

concat (StringName) combine two strings

String greeting = "Hello ";
String person = "Chi";
String NewG = greeting.toUpperCase();
String NewP = person.toLowerCase();
System.out.println(NewG.concat(NewP));       //Outputs : HELLO chi

indexOf( ) returns the index of the first occurrence of the searched string (if there are multiple occurrences, the first occurrence is returned)
by the way: for strings and arrays, the first index is always 0

String txt = "Please locate where 'locate' occurs!";
System.out.println( txt.indexOf("locate") );     // Outputs 7  (內容注意使用雙引號)