You are on page 1of 11

Week #2

Java Source File / Source Code


In Java, a source file is officially called a compilation unit. It is a text file that contains
(among other things) one or more class definitions. The java compiler requires that a source
file use the .java filename extension.

In Java, all code must reside inside a class. By cconvention, the name of the main class
should match the name of the file that holds the program.

You should also make sure that the capitalization of the filename matches the class name.

The reason for this is that Java is CASE-SENSITIVE.

Java Basic Syntax


Class - A class can be described as a blueprint that portrays the practices/ expresses all the
behaviors and states of its objects.

Object - Objects are characterized by two components namely, methods and attributes or
variables. Any object is nothing but an instance of a class.

Instance Variables - each object has its set of variables. An object's state is made by the
qualities allotted to these variables during program execution.

Methods - A method is the definition of a method. Moreover, a class can contain numerous
methods. It is in these methods that behaviors like where the rationaes are composed,
information is controlled and all the activities are executed.

Arguments - are pieves of information that are sent into, or passed to, a method, usually
because the method requires the information to perform its task or carry out its purpose.

- Basic Syntax of a Java Code


1 import java.util.Scanner;

2 //Using * means we are using java wildcard

import javax.swing.*;

3 /*

* @author InFeliouS

*/

4 public class DemoWeek2 {

5-6 public static void main(String[] args) {

String name = "Infelious Rhaplanca";

char gender = 'M';

int age = 18;

7 System.out.println("Hello World!");

System.out.println("My name is " + name);

System.out.println("My age is: " + age);

System.out.println("My sex is: " + gender);

1. Gets the Scanner class from the package (library) java.util

2. Single-line comments start w/ 2 forward slashes // .

3. Multi-line comments start with /* and ends with */ . Any text between /* and */ will
be ignored by Java (inshort, comment).

4. DemoWeek2 is an identifier that is the name of the class (user-defined) "This should be in a
file named DemoWeek2"

5. As a general rule, a Java program begins execution by calling main() .

6. static means this method works withour instantiationg an object of the class.

7. Sends output to the screen.

- Anatomy of a Java Statement

public class DemoWeek2 {

1-4 public static void main(String [] args) {

5-7 System.out.println("Hello World!");

8 }

9 }
1. The public keyword is an access modifier, which allows the programmer to control the
visibility of class members.

2. The keyword static allows main() to be called without having to instantiate a particular
instance of the class.

3. The keyword void simply tells the compiler that main() does not return a value.

4. The last character on the line is the { . This signals the start of main() 's body. All of the
code that comprises a method will occur between the method's { and its } .

5. System is a predefined class that provides access to the system, and out is the output
stream that is connected to the console.

6. println() is a method. Method names are always followed by parentheses.

7. "Hello World!" is a literal string that is the argument to the println() method.

8. Closing curly braces } of method main.

9. Closing curly braces } of class DemoWeek2.

Variables, Datatypes and Identifiers

- Using Constants and Variables


A data item is constant when its value cannot be changed while a program is running; a
data item is variable when its value might change. For example, when you include the
following statement in a Java class, the number 459 is a constant:

System.out.println(459);

Every time an application containing the constant 459 is executed, the value 459 is
displayed.

A variable is a name memory location that you can use to store value.It can only hold one
value at a time, but the value it can holds can change.

//the variable here is "num1"

int num1 = 459


- Datatypes
An item's data type describes the type of data that can be stored there, how much memory
the item occupies, and what types of operations can be performed on the data. Java
provides for 8 primitive data types of data. A primitive type is a sumple data type.

byte

byte information sort is a 8-bit marked two's supplament whole number.

Max = 127 ; Min = - 128 (inclusive)

Default value stored in a variable of this type is 0.

4 times smaller than int .

byte x = 100;

byte y = -47;

short

short information sort is a 16-bit marked two's supplament whole number.

Max = 32 767 ; Min = - 32 768 (inclusive)

Default value stored in a variable of this type is 0 .

2 times smaller than int .

short x = 25949;

short y = -1294;

int

int information sort is a 32-bit marked two's supplament whole number.

Max = 2 147 483 647 ; Min = - 2 147 483 648 (inclusive)

Default value stored in a variable of this type is 0.

Main datatype to be used when dealing with numerical data w/o decimals.

int x = 5341312;

int y = -95739;
long

int information sort is a 64-bit marked two's supplament whole number.

Max = 9 223 372 036 834 775 807 ; Min = - 9 223 372 036 834 775 808 (inclusive)

Default value stored in a variable of this type is 0 .

This sort is utilized when a more extensive memory range than int is required.

long x = 7817423190672;

long y = - 192847359218523;

float

A dataype which is known for its solitary exactness, 32-bit IEEE 754 gliding point

float is for the most part used to spare memory in vast exhibits of coasting numbers

Default value stored in a variable of this type is 0.0f .

float x = 51.125f;

double

A dataype which is known for its solitary exactness, 64-bit IEEE 754 gliding point

double is for the most part utulized as the default information sort for deciaml
qualities.

Default value stored in a variable of this type is 0.0d .

double x = 891453.52314;

boolean

boolean information sort speaks to one bit of data.

Any boolean variable can assume one of the two values: true or false .

this is utilized for basic banners that track genuine/false conditions.

The default value for this data type is false .


boolean check = true;

char

char information sort is a solitary 16-bit Unicode character.

It is utilized to store any character.

char text = 'M';

- Identifiers
Identifier - In programming languages, identifiers are used for identification purposes.

Case-sensitivity - Java is case sensitive, which implies that the identifier Hi and hi would
have distinctive importance in Java. (Basically means Hi and hi are different from each
other, both of them may be used as variables seperately)

All identifiers ought to start with a letter (beginning to end or a to z), underscore _ or
specia character $ .

After the first character, identifiers can have any mix of characters.

You cannot use a keyword as an identifier, such as public or int .

Most significantly, identifiers are case-sensitive (Sample is not the same with sample).

Examples of identifiers include: $salary , __1_value , and value .

Examples of illicit identifiers include: -compensation , 123abc and any keyword.

- Basic Java Operators


Arithmetic Operators

+ - Addition (Sum)

- - Subtraction (Difference)

* - Multiplication (Product)

/ - Division (Remainder)

% - Modulo (Remainder)
++ - Increment (increases the value of a variable by 1)

-- - Decrement (decreases the value of a variable by 1)

Simple Coding in Java

- Printing using println()


this method prints the text on the console and the cursor remains at the start of the next
line at the console. The next printing takes place from next line.

package demoweek2;

/*

* @author InFeliouS

*/

public class DemoWeek2 {

public static void main(String[] args) {

System.out.println("Hello World!");

System.out.println("Hello Pogi");

Output:

Hello World!

Hello Pogi!

- Printing using print()


After printing the statement, the cursor remains on the same time. The next printing takes
place from just here.
package demoweek2;

/*

* @author InFeliouS

*/

public class DemoWeek2 {

public static void main(String[] args) {

System.out.print("Hello World!");

System.out.print("Hello Pogi");

Output:

Hello World!Hello Pogi!

- Creating and calling a Method

package demoweek2;

/*

* @author InFeliouS

*/

public class DemoWeek2 {

public static void main(String[] args) {

//to call a method, go to main method and write it's modifier

//Don't foget the parenthesis () and terminator ;

newMethod();

/*

We will use public for the access specifier

this method is static and will not have a return value

*/

public static void newMethod() {

System.out.print("Hi BSIT 1-4, this is a test print");

Output:
Hi BSIT 1-4, this is a test print

Note: Hindi ko na sinama yung "Variable Declaration" dahil may notes na about sa datatypes
and variables.

- Using Basic Operator


For this example, we will use + addition

public class DemoWeek2 {

public static void main(String[] args) {

// TODO code application logic here

useBasicOperator();

//using basic operator

public static void useBasicOperator() {

int num1,num2,result;

num1 = 10;

num2 = 25

result = num1 + num2;

System.out.println(result);

Output:

35

- Concatenation
Concatenation is the process of combining two or more strings to form a new string by
subsequently appending the next string to the end of the previous strings.
public class DemoWeek2 {

public static void main(String[] args) {

//This is to concatenante a string

String firstName = "Infelious ";

String lastName = "Rhaplanca";

//This one uses operators

System.out.println(firstName + lastName);

//This one uses the concat() method

System.out.println(firstName.concat(lastName));

//Both works when concatinating

System.out.println("My name is " firstName + lastName + " nice to meet you!");

Output:

Infelious Rhaplanca

Infelious Rhaplanca

My name is Infelious Rhaplanca nice to meet you!

- Using Scanner for Input


Reccommended to try it for yourself
//Importing Scanner

Import java.util.Scanner;

// NOTE: usingScanner(); MUST BE CALLED IN main method to work

//Using Scanner method

public static void usingScanner(){

// Instantiation & Variable

Scanner input = new Scanner(System.in);

String FirstName, LastName;

//Setting up Input

System.out.println("What is your First Name?");

FirstName = input.nextLine();

System.out.println("What is your Last Name");

LastName = input.nextLine();

//Output line after user input

System.out.println("Your Name is: " + FirstName + " " + LastName);

Output:

What is your First Name?

InFelious

What is your Last Name?

Rhaplanca

Your name is: Infelious Rhaplanca

You might also like