0% found this document useful (0 votes)
4 views21 pages

Lec 1

This document serves as a comprehensive introduction to Java programming, covering essential topics such as Java syntax, data types, conditional statements, loops, and the differences between procedural and object-oriented programming. It provides examples of basic Java code, including the use of print methods, comments, and various operators, along with exercises for practice. The document also highlights the distinctions between procedural and object-oriented programming paradigms.

Uploaded by

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

Lec 1

This document serves as a comprehensive introduction to Java programming, covering essential topics such as Java syntax, data types, conditional statements, loops, and the differences between procedural and object-oriented programming. It provides examples of basic Java code, including the use of print methods, comments, and various operators, along with exercises for practice. The document also highlights the distinctions between procedural and object-oriented programming paradigms.

Uploaded by

Sayed Ghazal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Lecture 1

Outline
• Java Quickstart (print – println - printf) methods
• Java Comments
• Java Data Types
• JAVA Conditions if else-if – shorthand if...else
• Loops ( while – do while – for)
• Exercises
• Procedural vs Object Oriented Programming OOP
• Java Operators

1
Java Quickstart
In Java, every application begins with a class name, and that class must match the filename.

Let's create our first Java file, called Main.java, which can be done in any text editor (like Notepad).

The file should contain a "Hello World" message, which is written with the following code:

The println() method:


Main.java

public class Main {

public static void main(String[] args) {

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

Note: The curly braces {} marks the beginning and the end of a block of code.

System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).

Don't worry too much about System, out and println(). Just know that you need them together to
print stuff to the screen.

You should also note that each code statement must end with a semicolon (;).

You can add as many println() methods as you want. Note that it will add a new line for each method:

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

System.out.println("I am learning Java.");

System.out.println("It is awesome!");

2
The print() method

There is also a print() method, which is similar to println().

The only difference is that it does not insert a new line at the end of the output:

Example

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

System.out.print("I will print on the same line.");

Java Output Numbers


Print Numbers
You can also use the println() method to print numbers.
However, unlike text, we don't put numbers inside double quotes:

Example

System.out.println(3);

System.out.println(358);

System.out.println(50000);

You can also perform mathematical calculations inside the println() method:

System.out.println(3 + 3); → 6

System.out.println(2 * 5); → 10

printf() Method
The printf() method outputs a formatted string.
Example

Print a formatted text containing a string and an integer:

System.out.printf("Hello %s! One kilobyte is %,d bytes.", "World", 1024);

3
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used
to prevent execution when testing alternative code.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment

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

Example

System.out.println("Hello World"); // This is a comment

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example

/* The code below will print the words Hello World

to the screen, and it is amazing */

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

4
Java Data Types
Example

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

float myFloatNum = 5.99f; // Floating point number

char myLetter = 'D'; // Character

boolean myBool = true; // Boolean

String myText = "Hello"; // String

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
a. 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 Type Size Description(

byte 1 byte Stores whole numbers from -128 to 127 (-2n-1 to 2n-1 – 1)
n : No of bits

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

5
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

- The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Example

char myGrade = 'B';

System.out.println(myGrade);

Output: B

Alternatively, if you are familiar with ASCII (American Standard Code for Information
Interchange) values, you can use those to display certain characters:
Example

char myVar1 = 65, myVar2 = 66, myVar3 = 67;

System.out.println(myVar1);

6
System.out.println(myVar2);

System.out.println(myVar3);

b. Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

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 starts 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.

Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:

Example

public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

7
JAVA Conditional Statements -if Statement:
Syntax
if (condition) {

// block of code to be executed if the condition is true

Example
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
}
}

The else if Statement


Example
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}

8
Short Hand if...else:
variable = (condition) ? expressionTrue : expressionFalse ;

Example
public class Main {
public static void main(String[] args) {
int time = 20;
String result;
result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
}
}

Java Switch Statements


Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Example
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");

9
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
}
}

JAVA Loops ( while – do while – for)


While Loop
Example
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
output
0
1
2
3
4

10
Do/While Loop
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
output
0
1
2
3
4

For Loop:
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}

output
0
1
2
3
4

11
Nested Loops
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i);
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j);
}
}
}
}
output
Outer: 1
Inner: 1
Inner: 2
Inner: 3
Outer: 2
Inner: 1
Inner: 2
Inner: 3

Exercises:
1. Write a Java program that reads a floating-point number and prints "zero" if the number
is zero. Otherwise, print "positive" or "negative". Add "small" if the absolute value of the
number is less than 1, or "large" if it exceeds 1,000,000.

Test Data
Input a number: 25
Expected Output :
Input value: 25
Positive number

2. Write a Java program to display n terms of natural numbers and their sum.

[Input number: 3
The first n natural numbers are : 3
1
2
3

12
The Sum of Natural Number upto n terms : 6 ]

Difference Between Procedural and Object Oriented Programming OOP


Parameter Procedural Programming Object Oriented Programming

Definition This programming language makes This programming language


use of a step by step approach for uses objects and classes for
breaking down a task into a creating models based on the
collection of routines (or real-world environment. This
subroutines) and variables by model makes it very easy for a
following a sequence of instructions. user to modify as well as
It carries out each step systematically maintain the existing code while
in order so that a computer easily new objects get created by
gets to understand what to do. inheriting the characteristics of
the present ones.

Security Procedural Programming does not Hiding data is possible with


offer any method of hiding data. Object Oriented Programming
Thus, it is less secure when due to the abstraction. Thus, it
compared to Object Oriented is more secure than the
Programming. Procedural Programming.

Method The main program gets divided into It involves the concept of classes
minute parts on the basis of the and objects. Hence, it divides
functions. It then treats them as the program into minute chunks
separate programs for smaller known as objects. These are
programs individually. actually instances of classes.

Division of Procedural Programming divides the Object Oriented Programming


Program program into small programs and divides the program into small
refers to them as functions. parts and refers to them as
objects.

Movement of Available data is capable of moving The objects are capable of


Data freely within the system from one moving and communicating
function to another. with each other through the
member functions.

Approach The Procedural Programming follows The Object Oriented


a Top-Down approach. Programming follows a Bottom-
Up approach.

13
Importance This programming model does not This programming model gives
give importance to data. It prioritizes importance to the data rather
the functions along with the than functions or procedures. It
sequence of actions that needs to is because it works on the basis
follow. of the real world.

Orientation It is Structure/Procedure oriented. It is Object Oriented.

Basis The main focus in Procedural The main focus in Object


Programming is on how to do the Oriented Programming is on
task, meaning, on the structure or data security. Hence, it only
procedure of the program. permits objects to access the
class entities.

Type of It divides any large program into It divides the entire program
Division small units called functions. into small units called objects.

Inheritance It does not provide any inheritance. It achieves inheritance in three


modes- protected, private, and
public.

Virtual There is no concept of virtual classes. The concept of virtual functions


Classes appears at the time of
inheritance.

Overloading The case of overloading isn’t possible Overloading is possible in the


in the case of Procedural form of operator overloading
Programming. and function overloading in the
case of Object Oriented
Programming.

Reusability of No feature of reusing codes is Object Oriented Programming


Code present in Procedural Programming. offers the feature to reuse any
existing codes in it by utilizing a
feature known as inheritance.

Most It prioritizes function over data. It prioritizes data over function.


Important
Attribute

14
Modes of The Procedural Programming offers The Object Oriented
Access no specific accessing mode for Programming offers three
accessing functions or attributes in a accessing modes- protected,
program. private, and public. These, then,
serve as a share to access
functions of attributes.

Size of It is not very suitable for solving any It is suitable for solving any big
Problems big or complex problems. or complex problems.

Addition of It is not very easy to add new It is very easy to add new
New functions and data in the Procedural functions and data in the Object
Function and Programming. Oriented Programming.
Data

Access to In the Procedural Programming, In the Object Oriented


Data most of the functions use global data Programming, the present data
for sharing. They can access freely cannot easily move easily from
from one function to another in any one function to another. One
given system. can keep it private or even
public. Thus, a user can control
the data access.

Data Sharing It shares the global data among the It shares data among the objects
functions present in the program. through its member functions.

Data Hiding No proper way is available for hiding It can hide data in three modes-
the data. Thus, the data remains protected, private, and public. It
insecure. increases the overall data
security.

Basis of The Procedural Programming follows The Object Oriented


World an unreal world. programming follows the real
world.

Friend It doesn’t involve any concept of Any class or function is capable


Classes or friend function. of becoming a friend of any
Friend other class that contains the
Functions keyword “friend.”
Note – The keyword “friend”
only works for C++.

15
Examples Some common examples of The examples of Object
Procedural Programming are C, Oriented Programming
Fortran, VB, and Pascal. languages are Java, C++, VB.NET,
Python, and C#.NET.

Java Operators
Java divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

16
++ Increment Increases the value of a variable by 1 ++x

Decreases the value of a variable by


-- Decrement --x
1

Java Assignment Operators


Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

17
Java Comparison Operators
Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Java Logical Operators

Operator Name Description Example

Logical
&& Returns true if both statements are true x < 5 && x < 10
and

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

Logical Reverse the result, returns false if the result


! !(x < 5 && x < 10)
not is true

18
Example:

Find the output of the following JAVA code?

public class Test {


public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 0;
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c = a + b = 30
c *= a ;
System.out.println("c *= a = " + c ); c += a = 40
a = 10; c -= a = 30
c = 15;
c *= a = 300
c /= a ;
System.out.println("c /= a = " + c ); c /= a = 1

a = 10; c %= a = 5
c = 15; c <<= 2 = 20
c %= a ;
System.out.println("c %= a = " + c ); c >>= 2 = 5
c >>= 2 = 1
c <<= 2 ;
System.out.println("c <<= 2 = " + c ); c &= a = 0

c >>= 2 ; c ^= a = 10
System.out.println("c >>= 2 = " + c ); c |= a = 10
c >>= 2 ;
System.out.println("c >>= 2 = " + c );

c &= a ;
System.out.println("c &= a = " + c );

c ^= a ;

19
System.out.println("c ^= a = " + c );

c |= a ;
System.out.println("c |= a = " + c );
}
}

20

You might also like